| 1 |
""" |
| 2 |
Base class for generating code in different programming languages, gives the |
| 3 |
methods which should be overridden to implement a new language. |
| 4 |
""" |
| 5 |
|
| 6 |
from brian2.codegen.permutation_analysis import ( |
| 7 |
OrderDependenceError, |
| 8 |
check_for_order_independence, |
| 9 |
) |
| 10 |
from brian2.codegen.translation import make_statements |
| 11 |
from brian2.core.functions import Function |
| 12 |
from brian2.core.variables import ArrayVariable |
| 13 |
from brian2.utils.logger import get_logger |
| 14 |
from brian2.utils.stringtools import get_identifiers |
| 15 |
|
| 16 |
__all__ = ["CodeGenerator"] |
| 17 |
|
| 18 |
|
| 19 |
logger = get_logger(__name__) |
| 20 |
|
| 21 |
|
| 22 |
class CodeGenerator: |
| 23 |
""" |
| 24 |
Base class for all languages. |
| 25 |
|
| 26 |
See definition of methods below. |
| 27 |
|
| 28 |
TODO: more details here |
| 29 |
""" |
| 30 |
|
| 31 |
# Subclasses should override this |
| 32 |
class_name = "" |
| 33 |
|
| 34 |
def __init__( |
| 35 |
self, |
| 36 |
variables, |
| 37 |
variable_indices, |
| 38 |
owner, |
| 39 |
iterate_all, |
| 40 |
codeobj_class, |
| 41 |
name, |
| 42 |
template_name, |
| 43 |
override_conditional_write=None, |
| 44 |
allows_scalar_write=False, |
| 45 |
): |
| 46 |
# We have to do the import here to avoid circular import dependencies. |
| 47 |
from brian2.devices.device import get_device |
| 48 |
|
| 49 |
self.device = get_device() |
| 50 |
self.variables = variables |
| 51 |
self.variable_indices = variable_indices |
| 52 |
self.func_name_replacements = {} |
| 53 |
for varname, var in variables.items(): |
| 54 |
if isinstance(var, Function): |
| 55 |
if codeobj_class in var.implementations: |
| 56 |
impl_name = var.implementations[codeobj_class].name |
| 57 |
if impl_name is not None: |
| 58 |
self.func_name_replacements[varname] = impl_name |
| 59 |
self.iterate_all = iterate_all |
| 60 |
self.codeobj_class = codeobj_class |
| 61 |
self.owner = owner |
| 62 |
if override_conditional_write is None: |
| 63 |
self.override_conditional_write = set() |
| 64 |
else: |
| 65 |
self.override_conditional_write = set(override_conditional_write) |
| 66 |
self.allows_scalar_write = allows_scalar_write |
| 67 |
self.name = name |
| 68 |
self.template_name = template_name |
| 69 |
# Gather the names of functions that should get an additional |
| 70 |
# "_vectorisation_idx" argument in the generated code. Take care |
| 71 |
# of storing their translated name (e.g. "_rand" instead of "rand") |
| 72 |
# if necessary |
| 73 |
self.auto_vectorise = { |
| 74 |
self.func_name_replacements.get(name, name) |
| 75 |
for name in self.variables |
| 76 |
if getattr(self.variables[name], "auto_vectorise", False) |
| 77 |
} |
| 78 |
|
| 79 |
@staticmethod |
| 80 |
def get_array_name(var, access_data=True): |
| 81 |
""" |
| 82 |
Get a globally unique name for a `ArrayVariable`. |
| 83 |
|
| 84 |
Parameters |
| 85 |
---------- |
| 86 |
var : `ArrayVariable` |
| 87 |
The variable for which a name should be found. |
| 88 |
access_data : bool, optional |
| 89 |
For `DynamicArrayVariable` objects, specifying `True` here means the |
| 90 |
name for the underlying data is returned. If specifying `False`, |
| 91 |
the name of object itself is returned (e.g. to allow resizing). |
| 92 |
Returns |
| 93 |
------- |
| 94 |
name : str |
| 95 |
A uniqe name for `var`. |
| 96 |
""" |
| 97 |
# We have to do the import here to avoid circular import dependencies. |
| 98 |
from brian2.devices.device import get_device |
| 99 |
|
| 100 |
device = get_device() |
| 101 |
return device.get_array_name(var, access_data=access_data) |
| 102 |
|
| 103 |
def translate_expression(self, expr): |
| 104 |
""" |
| 105 |
Translate the given expression string into a string in the target |
| 106 |
language, returns a string. |
| 107 |
""" |
| 108 |
raise NotImplementedError |
| 109 |
|
| 110 |
def translate_statement(self, statement): |
| 111 |
""" |
| 112 |
Translate a single line `Statement` into the target language, returns |
| 113 |
a string. |
| 114 |
""" |
| 115 |
raise NotImplementedError |
| 116 |
|
| 117 |
def determine_keywords(self): |
| 118 |
""" |
| 119 |
A dictionary of values that is made available to the templated. This is |
| 120 |
used for example by the `CPPCodeGenerator` to set up all the supporting |
| 121 |
code |
| 122 |
""" |
| 123 |
return {} |
| 124 |
|
| 125 |
def translate_one_statement_sequence(self, statements, scalar=False): |
| 126 |
raise NotImplementedError |
| 127 |
|
| 128 |
def translate_statement_sequence(self, scalar_statements, vector_statements): |
| 129 |
""" |
| 130 |
Translate a sequence of `Statement` into the target language, taking |
| 131 |
care to declare variables, etc. if necessary. |
| 132 |
|
| 133 |
Returns a tuple ``(scalar_code, vector_code, kwds)`` where |
| 134 |
``scalar_code`` is a list of the lines of code executed before the inner |
| 135 |
loop, ``vector_code`` is a list of the lines of code in the inner |
| 136 |
loop, and ``kwds`` is a dictionary of values that is made available to |
| 137 |
the template. |
| 138 |
""" |
| 139 |
scalar_code = {} |
| 140 |
vector_code = {} |
| 141 |
for name, block in scalar_statements.items(): |
| 142 |
scalar_code[name] = self.translate_one_statement_sequence( |
| 143 |
block, scalar=True |
| 144 |
) |
| 145 |
for name, block in vector_statements.items(): |
| 146 |
vector_code[name] = self.translate_one_statement_sequence( |
| 147 |
block, scalar=False |
| 148 |
) |
| 149 |
|
| 150 |
kwds = self.determine_keywords() |
| 151 |
|
| 152 |
return scalar_code, vector_code, kwds |
| 153 |
|
| 154 |
def array_read_write(self, statements): |
| 155 |
""" |
| 156 |
Helper function, gives the set of ArrayVariables that are read from and |
| 157 |
written to in the series of statements. Returns the pair read, write |
| 158 |
of sets of variable names. |
| 159 |
""" |
| 160 |
variables = self.variables |
| 161 |
variable_indices = self.variable_indices |
| 162 |
read = set() |
| 163 |
write = set() |
| 164 |
for stmt in statements: |
| 165 |
ids = get_identifiers(stmt.expr) |
| 166 |
# if the operation is inplace this counts as a read. |
| 167 |
if stmt.inplace: |
| 168 |
ids.add(stmt.var) |
| 169 |
read = read.union(ids) |
| 170 |
if stmt.scalar or variable_indices[stmt.var] == "0": |
| 171 |
if stmt.op != ":=" and not self.allows_scalar_write: |
| 172 |
raise SyntaxError( |
| 173 |
f"Writing to scalar variable {stmt.var} not allowed in this" |
| 174 |
" context." |
| 175 |
) |
| 176 |
for name in ids: |
| 177 |
if ( |
| 178 |
name in variables |
| 179 |
and isinstance(variables[name], ArrayVariable) |
| 180 |
and not ( |
| 181 |
variables[name].scalar or variable_indices[name] == "0" |
| 182 |
) |
| 183 |
): |
| 184 |
raise SyntaxError( |
| 185 |
"Cannot write to scalar variable " |
| 186 |
f"'{stmt.var}' with an expression " |
| 187 |
f"referring to vector variable '{name}'" |
| 188 |
) |
| 189 |
write.add(stmt.var) |
| 190 |
read = { |
| 191 |
varname |
| 192 |
for varname, var in list(variables.items()) |
| 193 |
if isinstance(var, ArrayVariable) and varname in read |
| 194 |
} |
| 195 |
write = { |
| 196 |
varname |
| 197 |
for varname, var in list(variables.items()) |
| 198 |
if isinstance(var, ArrayVariable) and varname in write |
| 199 |
} |
| 200 |
# Gather the indices stored as arrays (ignore _idx which is special) |
| 201 |
indices = set() |
| 202 |
indices |= { |
| 203 |
variable_indices[varname] |
| 204 |
for varname in read |
| 205 |
if variable_indices[varname] not in ("_idx", "0") |
| 206 |
and isinstance(variables[variable_indices[varname]], ArrayVariable) |
| 207 |
} |
| 208 |
indices |= { |
| 209 |
variable_indices[varname] |
| 210 |
for varname in write |
| 211 |
if variable_indices[varname] not in ("_idx", "0") |
| 212 |
and isinstance(variables[variable_indices[varname]], ArrayVariable) |
| 213 |
} |
| 214 |
# don't list arrays that are read explicitly and used as indices twice |
| 215 |
read -= indices |
| 216 |
return read, write, indices |
| 217 |
|
| 218 |
def get_conditional_write_vars(self): |
| 219 |
""" |
| 220 |
Helper function, returns a dict of mappings ``(varname, condition_var_name)`` indicating that |
| 221 |
when ``varname`` is written to, it should only be when ``condition_var_name`` is ``True``. |
| 222 |
""" |
| 223 |
conditional_write_vars = {} |
| 224 |
for varname, var in list(self.variables.items()): |
| 225 |
if getattr(var, "conditional_write", None) is not None: |
| 226 |
cvar = var.conditional_write |
| 227 |
cname = cvar.name |
| 228 |
if cname not in self.override_conditional_write: |
| 229 |
conditional_write_vars[varname] = cname |
| 230 |
return conditional_write_vars |
| 231 |
|
| 232 |
def arrays_helper(self, statements): |
| 233 |
""" |
| 234 |
Combines the two helper functions `array_read_write` and `get_conditional_write_vars`, and updates the |
| 235 |
``read`` set. |
| 236 |
""" |
| 237 |
read, write, indices = self.array_read_write(statements) |
| 238 |
conditional_write_vars = self.get_conditional_write_vars() |
| 239 |
read |= {var for var in write if var in conditional_write_vars} |
| 240 |
read |= { |
| 241 |
conditional_write_vars[var] |
| 242 |
for var in write |
| 243 |
if var in conditional_write_vars |
| 244 |
} |
| 245 |
return read, write, indices, conditional_write_vars |
| 246 |
|
| 247 |
def has_repeated_indices(self, statements): |
| 248 |
""" |
| 249 |
Whether any of the statements potentially uses repeated indices (e.g. |
| 250 |
pre- or postsynaptic indices). |
| 251 |
""" |
| 252 |
variables = self.variables |
| 253 |
variable_indices = self.variable_indices |
| 254 |
read, write, indices, conditional_write_vars = self.arrays_helper(statements) |
| 255 |
# Check whether we potentially deal with repeated indices (which will |
| 256 |
# be the case most importantly when we write to pre- or post-synaptic |
| 257 |
# variables in synaptic code) |
| 258 |
used_indices = {variable_indices[var] for var in write} |
| 259 |
all_unique = all( |
| 260 |
variables[index].unique |
| 261 |
for index in used_indices |
| 262 |
if index not in ("_idx", "0") |
| 263 |
) |
| 264 |
return not all_unique |
| 265 |
|
| 266 |
def translate(self, code, dtype): |
| 267 |
""" |
| 268 |
Translates an abstract code block into the target language. |
| 269 |
""" |
| 270 |
scalar_statements = {} |
| 271 |
vector_statements = {} |
| 272 |
for ac_name, ac_code in code.items(): |
| 273 |
statements = make_statements( |
| 274 |
ac_code, self.variables, dtype, optimise=True, blockname=ac_name |
| 275 |
) |
| 276 |
scalar_statements[ac_name], vector_statements[ac_name] = statements |
| 277 |
for vs in vector_statements.values(): |
| 278 |
# Check that the statements are meaningful independent on the order of |
| 279 |
# execution (e.g. for synapses) |
| 280 |
try: |
| 281 |
if self.has_repeated_indices( |
| 282 |
vs |
| 283 |
): # only do order dependence if there are repeated indices |
| 284 |
check_for_order_independence( |
| 285 |
vs, self.variables, self.variable_indices |
| 286 |
) |
| 287 |
except OrderDependenceError: |
| 288 |
# If the abstract code is only one line, display it in full |
| 289 |
if len(vs) <= 1: |
| 290 |
error_msg = f"Abstract code: '{vs[0]}'\n" |
| 291 |
else: |
| 292 |
error_msg = ( |
| 293 |
f"{len(vs)} lines of abstract code, first line is: '{vs[0]}'\n" |
| 294 |
) |
| 295 |
logger.warn( |
| 296 |
"Came across an abstract code block that may not be " |
| 297 |
"well-defined: the outcome may depend on the " |
| 298 |
"order of execution. You can ignore this warning if " |
| 299 |
"you are sure that the order of operations does not " |
| 300 |
"matter. " + error_msg |
| 301 |
) |
| 302 |
|
| 303 |
translated = self.translate_statement_sequence( |
| 304 |
scalar_statements, vector_statements |
| 305 |
) |
| 306 |
|
| 307 |
return translated |