| 1 |
""" |
| 2 |
This module translates a series of statements into a language-specific |
| 3 |
syntactically correct code block that can be inserted into a template. |
| 4 |
|
| 5 |
It infers whether or not a variable can be declared as |
| 6 |
constant, etc. It should handle common subexpressions, and so forth. |
| 7 |
|
| 8 |
The input information needed: |
| 9 |
|
| 10 |
* The sequence of statements (a multiline string) in standard mathematical form |
| 11 |
* The list of known variables, common subexpressions and functions, and for each |
| 12 |
variable whether or not it is a value or an array, and if an array what the |
| 13 |
dtype is. |
| 14 |
* The dtype to use for newly created variables |
| 15 |
* The language to translate to |
| 16 |
""" |
| 17 |
|
| 18 |
import re |
| 19 |
from collections.abc import Mapping |
| 20 |
|
| 21 |
import numpy as np |
| 22 |
import sympy |
| 23 |
|
| 24 |
from brian2.core.functions import Function |
| 25 |
from brian2.core.preferences import prefs |
| 26 |
from brian2.core.variables import AuxiliaryVariable, Subexpression, Variable |
| 27 |
from brian2.parsing.bast import brian_ast |
| 28 |
from brian2.parsing.statements import parse_statement |
| 29 |
from brian2.parsing.sympytools import str_to_sympy, sympy_to_str |
| 30 |
from brian2.utils.caching import cached |
| 31 |
from brian2.utils.stringtools import deindent, get_identifiers, strip_empty_lines |
| 32 |
from brian2.utils.topsort import topsort |
| 33 |
|
| 34 |
from .optimisation import optimise_statements |
| 35 |
from .statements import Statement |
| 36 |
|
| 37 |
__all__ = ["analyse_identifiers", "get_identifiers_recursively"] |
| 38 |
|
| 39 |
|
| 40 |
class LineInfo: |
| 41 |
""" |
| 42 |
A helper class, just used to store attributes. |
| 43 |
""" |
| 44 |
|
| 45 |
def __init__(self, **kwds): |
| 46 |
for k, v in kwds.items(): |
| 47 |
setattr(self, k, v) |
| 48 |
|
| 49 |
# TODO: This information should go somewhere else, I guess |
| 50 |
|
| 51 |
|
| 52 |
STANDARD_IDENTIFIERS = {"and", "or", "not", "True", "False"} |
| 53 |
|
| 54 |
|
| 55 |
def analyse_identifiers(code, variables, recursive=False): |
| 56 |
""" |
| 57 |
Analyses a code string (sequence of statements) to find all identifiers by type. |
| 58 |
|
| 59 |
In a given code block, some variable names (identifiers) must be given as inputs to the code |
| 60 |
block, and some are created by the code block. For example, the line:: |
| 61 |
|
| 62 |
a = b+c |
| 63 |
|
| 64 |
This could mean to create a new variable a from b and c, or it could mean modify the existing |
| 65 |
value of a from b or c, depending on whether a was previously known. |
| 66 |
|
| 67 |
Parameters |
| 68 |
---------- |
| 69 |
code : str |
| 70 |
The code string, a sequence of statements one per line. |
| 71 |
variables : dict of `Variable`, set of names |
| 72 |
Specifiers for the model variables or a set of known names |
| 73 |
recursive : bool, optional |
| 74 |
Whether to recurse down into subexpressions (defaults to ``False``). |
| 75 |
|
| 76 |
Returns |
| 77 |
------- |
| 78 |
newly_defined : set |
| 79 |
A set of variables that are created by the code block. |
| 80 |
used_known : set |
| 81 |
A set of variables that are used and already known, a subset of the |
| 82 |
``known`` parameter. |
| 83 |
unknown : set |
| 84 |
A set of variables which are used by the code block but not defined by |
| 85 |
it and not previously known. Should correspond to variables in the |
| 86 |
external namespace. |
| 87 |
""" |
| 88 |
if isinstance(variables, Mapping): |
| 89 |
known = { |
| 90 |
k for k, v in variables.items() if not isinstance(k, AuxiliaryVariable) |
| 91 |
} |
| 92 |
else: |
| 93 |
known = set(variables) |
| 94 |
variables = {k: Variable(name=k, dtype=np.float64) for k in known} |
| 95 |
|
| 96 |
known |= STANDARD_IDENTIFIERS |
| 97 |
scalar_stmts, vector_stmts = make_statements( |
| 98 |
code, variables, np.float64, optimise=False |
| 99 |
) |
| 100 |
stmts = scalar_stmts + vector_stmts |
| 101 |
defined = {stmt.var for stmt in stmts if stmt.op == ":="} |
| 102 |
if len(stmts) == 0: |
| 103 |
allids = set() |
| 104 |
elif recursive: |
| 105 |
if not isinstance(variables, Mapping): |
| 106 |
raise TypeError("Have to specify a variables dictionary.") |
| 107 |
allids = get_identifiers_recursively( |
| 108 |
[stmt.expr for stmt in stmts], variables |
| 109 |
) | {stmt.var for stmt in stmts} |
| 110 |
else: |
| 111 |
allids = set.union(*[get_identifiers(stmt.expr) for stmt in stmts]) | { |
| 112 |
stmt.var for stmt in stmts |
| 113 |
} |
| 114 |
dependent = allids.difference(defined, known) |
| 115 |
used_known = allids.intersection(known) - STANDARD_IDENTIFIERS |
| 116 |
return defined, used_known, dependent |
| 117 |
|
| 118 |
|
| 119 |
def get_identifiers_recursively(expressions, variables, include_numbers=False): |
| 120 |
""" |
| 121 |
Gets all the identifiers in a list of expressions, recursing down into |
| 122 |
subexpressions. |
| 123 |
|
| 124 |
Parameters |
| 125 |
---------- |
| 126 |
expressions : list of str |
| 127 |
List of expressions to check. |
| 128 |
variables : dict-like |
| 129 |
Dictionary of `Variable` objects |
| 130 |
include_numbers : bool, optional |
| 131 |
Whether to include number literals in the output. Defaults to ``False``. |
| 132 |
""" |
| 133 |
if len(expressions): |
| 134 |
identifiers = set.union( |
| 135 |
*[ |
| 136 |
get_identifiers(expr, include_numbers=include_numbers) |
| 137 |
for expr in expressions |
| 138 |
] |
| 139 |
) |
| 140 |
else: |
| 141 |
identifiers = set() |
| 142 |
for name in set(identifiers): |
| 143 |
if name in variables and isinstance(variables[name], Subexpression): |
| 144 |
s_identifiers = get_identifiers_recursively( |
| 145 |
[variables[name].expr], variables, include_numbers=include_numbers |
| 146 |
) |
| 147 |
identifiers |= s_identifiers |
| 148 |
return identifiers |
| 149 |
|
| 150 |
|
| 151 |
def is_scalar_expression(expr, variables): |
| 152 |
""" |
| 153 |
Whether the given expression is scalar. |
| 154 |
|
| 155 |
Parameters |
| 156 |
---------- |
| 157 |
expr : str |
| 158 |
The expression to check |
| 159 |
variables : dict-like |
| 160 |
`Variable` and `Function` object for all the identifiers used in `expr` |
| 161 |
|
| 162 |
Returns |
| 163 |
------- |
| 164 |
scalar : bool |
| 165 |
Whether `expr` is a scalar expression |
| 166 |
""" |
| 167 |
# determine whether this is a scalar variable |
| 168 |
identifiers = get_identifiers_recursively([expr], variables) |
| 169 |
# In the following we assume that all unknown identifiers are |
| 170 |
# scalar constants -- this should cover numerical literals and |
| 171 |
# e.g. "True" or "inf". |
| 172 |
return all( |
| 173 |
name not in variables |
| 174 |
or getattr(variables[name], "scalar", False) |
| 175 |
or (isinstance(variables[name], Function) and variables[name].stateless) |
| 176 |
for name in identifiers |
| 177 |
) |
| 178 |
|
| 179 |
|
| 180 |
@cached |
| 181 |
def make_statements(code, variables, dtype, optimise=True, blockname=""): |
| 182 |
""" |
| 183 |
make_statements(code, variables, dtype, optimise=True, blockname='') |
| 184 |
|
| 185 |
Turn a series of abstract code statements into Statement objects, inferring |
| 186 |
whether each line is a set/declare operation, whether the variables are |
| 187 |
constant or not, and handling the cacheing of subexpressions. |
| 188 |
|
| 189 |
Parameters |
| 190 |
---------- |
| 191 |
code : str |
| 192 |
A (multi-line) string of statements. |
| 193 |
variables : dict-like |
| 194 |
A dictionary of with `Variable` and `Function` objects for every |
| 195 |
identifier used in the `code`. |
| 196 |
dtype : `dtype` |
| 197 |
The data type to use for temporary variables |
| 198 |
optimise : bool, optional |
| 199 |
Whether to optimise expressions, including |
| 200 |
pulling out loop invariant expressions and putting them in new |
| 201 |
scalar constants. Defaults to ``False``, since this function is also |
| 202 |
used just to in contexts where we are not interested by this kind of |
| 203 |
optimisation. For the main code generation stage, its value is set by |
| 204 |
the `codegen.loop_invariant_optimisations` preference. |
| 205 |
blockname : str, optional |
| 206 |
A name for the block (used to name intermediate variables to avoid |
| 207 |
name clashes when multiple blocks are used together) |
| 208 |
Returns |
| 209 |
------- |
| 210 |
scalar_statements, vector_statements : (list of `Statement`, list of `Statement`) |
| 211 |
Lists with statements that are to be executed once and statements that |
| 212 |
are to be executed once for every neuron/synapse/... (or in a vectorised |
| 213 |
way) |
| 214 |
|
| 215 |
Notes |
| 216 |
----- |
| 217 |
If ``optimise`` is ``True``, then the |
| 218 |
``scalar_statements`` may include newly introduced scalar constants that |
| 219 |
have been identified as loop-invariant and have therefore been pulled out |
| 220 |
of the vector statements. The resulting statements will also use augmented |
| 221 |
assignments where possible, i.e. a statement such as ``w = w + 1`` will be |
| 222 |
replaced by ``w += 1``. Also, statements involving booleans will have |
| 223 |
additional information added to them (see `Statement` for details) |
| 224 |
describing how the statement can be reformulated as a sequence of if/then |
| 225 |
statements. Calls `~brian2.codegen.optimisation.optimise_statements`. |
| 226 |
""" |
| 227 |
code = strip_empty_lines(deindent(code)) |
| 228 |
lines = re.split(r"[;\n]", code) |
| 229 |
lines = [LineInfo(code=line) for line in lines if len(line)] |
| 230 |
# Do a copy so we can add stuff without altering the original dict |
| 231 |
variables = dict(variables) |
| 232 |
# we will do inference to work out which lines are := and which are = |
| 233 |
defined = {k for k, v in variables.items() if not isinstance(v, AuxiliaryVariable)} |
| 234 |
for line in lines: |
| 235 |
statement = None |
| 236 |
# parse statement into "var op expr" |
| 237 |
var, op, expr, comment = parse_statement(line.code) |
| 238 |
if var in variables and isinstance(variables[var], Subexpression): |
| 239 |
raise SyntaxError( |
| 240 |
f"Illegal line '{line.code}' in abstract code. Cannot write to" |
| 241 |
f" subexpression '{var}'." |
| 242 |
) |
| 243 |
if op == "=": |
| 244 |
if var not in defined: |
| 245 |
op = ":=" |
| 246 |
defined.add(var) |
| 247 |
if var not in variables: |
| 248 |
annotated_ast = brian_ast(expr, variables) |
| 249 |
is_scalar = annotated_ast.scalar |
| 250 |
if annotated_ast.dtype == "boolean": |
| 251 |
use_dtype = bool |
| 252 |
elif annotated_ast.dtype == "integer": |
| 253 |
use_dtype = int |
| 254 |
else: |
| 255 |
use_dtype = dtype |
| 256 |
new_var = AuxiliaryVariable(var, dtype=use_dtype, scalar=is_scalar) |
| 257 |
variables[var] = new_var |
| 258 |
elif not variables[var].is_boolean: |
| 259 |
sympy_expr = str_to_sympy(expr, variables) |
| 260 |
if variables[var].is_integer: |
| 261 |
sympy_var = sympy.Symbol(var, integer=True) |
| 262 |
else: |
| 263 |
sympy_var = sympy.Symbol(var, real=True) |
| 264 |
try: |
| 265 |
collected = sympy.collect( |
| 266 |
sympy_expr, sympy_var, exact=True, evaluate=False |
| 267 |
) |
| 268 |
except AttributeError: |
| 269 |
# If something goes wrong during collection, e.g. collect |
| 270 |
# does not work for logical expressions |
| 271 |
collected = {1: sympy_expr} |
| 272 |
|
| 273 |
if ( |
| 274 |
len(collected) == 2 |
| 275 |
and set(collected.keys()) == {1, sympy_var} |
| 276 |
and collected[sympy_var] == 1 |
| 277 |
): |
| 278 |
# We can replace this statement by a += assignment |
| 279 |
statement = Statement( |
| 280 |
var, |
| 281 |
"+=", |
| 282 |
sympy_to_str(collected[1]), |
| 283 |
comment, |
| 284 |
dtype=variables[var].dtype, |
| 285 |
scalar=variables[var].scalar, |
| 286 |
) |
| 287 |
elif len(collected) == 1 and sympy_var in collected: |
| 288 |
# We can replace this statement by a *= assignment |
| 289 |
statement = Statement( |
| 290 |
var, |
| 291 |
"*=", |
| 292 |
sympy_to_str(collected[sympy_var]), |
| 293 |
comment, |
| 294 |
dtype=variables[var].dtype, |
| 295 |
scalar=variables[var].scalar, |
| 296 |
) |
| 297 |
if statement is None: |
| 298 |
statement = Statement( |
| 299 |
var, |
| 300 |
op, |
| 301 |
expr, |
| 302 |
comment, |
| 303 |
dtype=variables[var].dtype, |
| 304 |
scalar=variables[var].scalar, |
| 305 |
) |
| 306 |
|
| 307 |
line.statement = statement |
| 308 |
# for each line will give the variable being written to |
| 309 |
line.write = var |
| 310 |
# each line will give a set of variables which are read |
| 311 |
line.read = get_identifiers_recursively([expr], variables) |
| 312 |
|
| 313 |
# All writes to scalar variables must happen before writes to vector |
| 314 |
# variables |
| 315 |
scalar_write_done = False |
| 316 |
for line in lines: |
| 317 |
stmt = line.statement |
| 318 |
if stmt.op != ":=" and variables[stmt.var].scalar and scalar_write_done: |
| 319 |
raise SyntaxError( |
| 320 |
"All writes to scalar variables in a code block " |
| 321 |
"have to be made before writes to vector " |
| 322 |
f"variables. Illegal write to '{line.write}'." |
| 323 |
) |
| 324 |
elif not variables[stmt.var].scalar: |
| 325 |
scalar_write_done = True |
| 326 |
|
| 327 |
# backwards compute whether or not variables will be read again |
| 328 |
# note that will_read for a line gives the set of variables it will read |
| 329 |
# on the current line or subsequent ones. will_write gives the set of |
| 330 |
# variables that will be written after the current line |
| 331 |
will_read = set() |
| 332 |
will_write = set() |
| 333 |
for line in lines[::-1]: |
| 334 |
will_read = will_read.union(line.read) |
| 335 |
line.will_read = will_read.copy() |
| 336 |
line.will_write = will_write.copy() |
| 337 |
will_write.add(line.write) |
| 338 |
|
| 339 |
subexpressions = { |
| 340 |
name: val for name, val in variables.items() if isinstance(val, Subexpression) |
| 341 |
} |
| 342 |
# Check that no scalar subexpression refers to a vectorised function |
| 343 |
# (e.g. rand()) -- otherwise it would be differently interpreted depending |
| 344 |
# on whether it is used in a scalar or a vector context (i.e., even though |
| 345 |
# the subexpression is supposed to be scalar, it would be vectorised when |
| 346 |
# used as part of non-scalar expressions) |
| 347 |
for name, subexpr in subexpressions.items(): |
| 348 |
if subexpr.scalar: |
| 349 |
identifiers = get_identifiers(subexpr.expr) |
| 350 |
for identifier in identifiers: |
| 351 |
if identifier in variables and getattr( |
| 352 |
variables[identifier], "auto_vectorise", False |
| 353 |
): |
| 354 |
raise SyntaxError( |
| 355 |
f"The scalar subexpression '{name}' refers to " |
| 356 |
f"the implicitly vectorised function '{identifier}' " |
| 357 |
"-- this is not allowed since it leads " |
| 358 |
"to different interpretations of this " |
| 359 |
"subexpression depending on whether it " |
| 360 |
"is used in a scalar or vector " |
| 361 |
"context." |
| 362 |
) |
| 363 |
|
| 364 |
# sort subexpressions into an order so that subexpressions that don't depend |
| 365 |
# on other subexpressions are first |
| 366 |
subexpr_deps = { |
| 367 |
name: [dep for dep in subexpr.identifiers if dep in subexpressions] |
| 368 |
for name, subexpr in subexpressions.items() |
| 369 |
} |
| 370 |
sorted_subexpr_vars = topsort(subexpr_deps) |
| 371 |
|
| 372 |
statements = [] |
| 373 |
|
| 374 |
# none are yet defined (or declared) |
| 375 |
subdefined = {name: None for name in subexpressions} |
| 376 |
for line in lines: |
| 377 |
# update/define all subexpressions needed by this statement |
| 378 |
for var in sorted_subexpr_vars: |
| 379 |
if var not in line.read: |
| 380 |
continue |
| 381 |
|
| 382 |
subexpression = subexpressions[var] |
| 383 |
# if already defined/declared |
| 384 |
if subdefined[var] == "constant": |
| 385 |
continue |
| 386 |
elif subdefined[var] == "variable": |
| 387 |
op = "=" |
| 388 |
constant = False |
| 389 |
else: |
| 390 |
op = ":=" |
| 391 |
# check if the referred variables ever change |
| 392 |
ids = subexpression.identifiers |
| 393 |
constant = all(v not in line.will_write for v in ids) |
| 394 |
subdefined[var] = "constant" if constant else "variable" |
| 395 |
|
| 396 |
statement = Statement( |
| 397 |
var, |
| 398 |
op, |
| 399 |
subexpression.expr, |
| 400 |
comment="", |
| 401 |
dtype=variables[var].dtype, |
| 402 |
constant=constant, |
| 403 |
subexpression=True, |
| 404 |
scalar=variables[var].scalar, |
| 405 |
) |
| 406 |
statements.append(statement) |
| 407 |
|
| 408 |
stmt = line.statement |
| 409 |
var, op, expr, comment = stmt.var, stmt.op, stmt.expr, stmt.comment |
| 410 |
|
| 411 |
# constant only if we are declaring a new variable and we will not |
| 412 |
# write to it again |
| 413 |
constant = op == ":=" and var not in line.will_write |
| 414 |
statement = Statement( |
| 415 |
var, |
| 416 |
op, |
| 417 |
expr, |
| 418 |
comment, |
| 419 |
dtype=variables[var].dtype, |
| 420 |
constant=constant, |
| 421 |
scalar=variables[var].scalar, |
| 422 |
) |
| 423 |
statements.append(statement) |
| 424 |
|
| 425 |
scalar_statements = [s for s in statements if s.scalar] |
| 426 |
vector_statements = [s for s in statements if not s.scalar] |
| 427 |
|
| 428 |
if optimise and prefs.codegen.loop_invariant_optimisations: |
| 429 |
scalar_statements, vector_statements = optimise_statements( |
| 430 |
scalar_statements, vector_statements, variables, blockname=blockname |
| 431 |
) |
| 432 |
|
| 433 |
return scalar_statements, vector_statements |