| 1 |
import inspect |
| 2 |
import types |
| 3 |
from collections.abc import Callable, Mapping |
| 4 |
|
| 5 |
import numpy as np |
| 6 |
import sympy |
| 7 |
from numpy.random import rand, randn |
| 8 |
from sympy import Function as sympy_Function |
| 9 |
from sympy import S |
| 10 |
from sympy.codegen import cfunctions as sympy_cfunctions |
| 11 |
|
| 12 |
import brian2.units.unitsafefunctions as unitsafe |
| 13 |
from brian2.core.preferences import prefs |
| 14 |
from brian2.core.variables import Constant |
| 15 |
from brian2.units.allunits import second |
| 16 |
from brian2.units.fundamentalunits import ( |
| 17 |
DIMENSIONLESS, |
| 18 |
Quantity, |
| 19 |
fail_for_dimension_mismatch, |
| 20 |
get_dimensions, |
| 21 |
is_dimensionless, |
| 22 |
) |
| 23 |
|
| 24 |
__all__ = ["DEFAULT_FUNCTIONS", "Function", "implementation", "declare_types"] |
| 25 |
|
| 26 |
|
| 27 |
BRIAN_DTYPES = ["boolean", "integer", "float"] |
| 28 |
VALID_ARG_TYPES = BRIAN_DTYPES + ["any"] |
| 29 |
VALID_RETURN_TYPES = BRIAN_DTYPES + ["highest"] |
| 30 |
|
| 31 |
|
| 32 |
def declare_types(**types): |
| 33 |
""" |
| 34 |
Decorator to declare argument and result types for a function |
| 35 |
|
| 36 |
Usage is similar to `check_units` except that types must be one of ``{VALID_ARG_TYPES}`` |
| 37 |
and the result type must be one of ``{VALID_RETURN_TYPES}``. Unspecified argument |
| 38 |
types are assumed to be ``'all'`` (i.e. anything is permitted), and an unspecified |
| 39 |
result type is assumed to be ``'float'``. Note that the ``'highest'`` option for |
| 40 |
result type will give the highest type of its argument, e.g. if the arguments |
| 41 |
were boolean and integer then the result would be integer, if the arguments were |
| 42 |
integer and float it would be float. |
| 43 |
""" |
| 44 |
|
| 45 |
def annotate_function_with_types(f): |
| 46 |
if hasattr(f, "_orig_arg_names"): |
| 47 |
arg_names = f._orig_arg_names |
| 48 |
else: |
| 49 |
arg_names = f.__code__.co_varnames[0 : f.__code__.co_argcount] |
| 50 |
argtypes = [] |
| 51 |
for name in arg_names: |
| 52 |
arg_type = types.get(name, "any") |
| 53 |
if arg_type not in VALID_ARG_TYPES: |
| 54 |
raise ValueError( |
| 55 |
f"Argument type {arg_type} is not valid, must be one of" |
| 56 |
f" {VALID_ARG_TYPES}, for argument {name}" |
| 57 |
) |
| 58 |
argtypes.append(arg_type) |
| 59 |
for n in types: |
| 60 |
if n not in arg_names and n != "result": |
| 61 |
raise ValueError(f"Type specified for unknown argument {n}") |
| 62 |
return_type = types.get("result", "float") |
| 63 |
if return_type not in VALID_RETURN_TYPES: |
| 64 |
raise ValueError( |
| 65 |
f"Result type {return_type} is not valid, must be one of" |
| 66 |
f" {VALID_RETURN_TYPES}" |
| 67 |
) |
| 68 |
f._arg_types = argtypes |
| 69 |
f._return_type = return_type |
| 70 |
f._orig_arg_names = arg_names |
| 71 |
f._annotation_attributes = getattr(f, "_annotation_attributes", []) + [ |
| 72 |
"_arg_types", |
| 73 |
"_return_type", |
| 74 |
] |
| 75 |
return f |
| 76 |
|
| 77 |
return annotate_function_with_types |
| 78 |
|
| 79 |
|
| 80 |
class Function: |
| 81 |
""" |
| 82 |
An abstract specification of a function that can be used as part of |
| 83 |
model equations, etc. |
| 84 |
|
| 85 |
Parameters |
| 86 |
---------- |
| 87 |
pyfunc : function |
| 88 |
A Python function that is represented by this `Function` object. |
| 89 |
sympy_func : `sympy.Function`, optional |
| 90 |
A corresponding sympy function (if any). Allows functions to be |
| 91 |
interpreted by sympy and potentially make simplifications. For example, |
| 92 |
``sqrt(x**2)`` could be replaced by ``abs(x)``. |
| 93 |
arg_units : list of `Unit`, optional |
| 94 |
If `pyfunc` does not provide unit information (which typically means |
| 95 |
that it was not annotated with a `check_units` decorator), the |
| 96 |
units of the arguments have to specified explicitly using this |
| 97 |
parameter. |
| 98 |
return_unit : `Unit` or callable, optional |
| 99 |
Same as for `arg_units`: if `pyfunc` does not provide unit information, |
| 100 |
this information has to be provided explictly here. `return_unit` can |
| 101 |
either be a specific `Unit`, if the function always returns the same |
| 102 |
unit, or a function of the input units, e.g. a "square" function would |
| 103 |
return the square of its input units, i.e. `return_unit` could be |
| 104 |
specified as ``lambda u: u**2``. |
| 105 |
arg_types : list of str, optional |
| 106 |
Similar to `arg_units`, but gives the type of the argument rather than |
| 107 |
its unit. In the current version of Brian arguments are specified |
| 108 |
by one of the following strings: 'boolean', 'integer', 'float', 'any'. |
| 109 |
If `arg_types` is not specified, 'any' will be assumed. In |
| 110 |
future versions, a more refined specification may be possible. Note that |
| 111 |
any argument with a type other than float should have no units. If |
| 112 |
return_type : str, optional |
| 113 |
Similar to `return_unit` and `arg_types`. In addition to 'boolean', |
| 114 |
'integer' and 'float' you can also use 'highest' which will return the |
| 115 |
highest type of its arguments. You can also give a function, as for |
| 116 |
`return_unit`. If the return type is not specified, it is assumed to |
| 117 |
be 'float'. |
| 118 |
stateless : bool, optional |
| 119 |
Whether this function does not have an internal state, i.e. if it |
| 120 |
always returns the same output when called with the same arguments. |
| 121 |
This is true for mathematical functions but not true for ``rand()``, for |
| 122 |
example. Defaults to ``True``. |
| 123 |
auto_vectorise : bool, optional |
| 124 |
Whether the implementations of this function should get an additional |
| 125 |
argument (not specified in abstract code) that can be used to determine |
| 126 |
the number of values that should be returned (for the numpy target), or |
| 127 |
an index potentially useful for generating deterministic values |
| 128 |
independent of the order of vectorisation (for all other targets). The |
| 129 |
main use case are random number functions, e.g. equations refer to |
| 130 |
``rand()``, but the generate code will actually call |
| 131 |
``rand(_vectorisation_idx)``. Defaults to ``False``. |
| 132 |
|
| 133 |
Notes |
| 134 |
----- |
| 135 |
If a function should be usable for code generation targets other than |
| 136 |
Python/numpy, implementations for these target languages have to be added |
| 137 |
using the `~brian2.codegen.functions.implementation` decorator or using the |
| 138 |
`~brian2.codegen.functions.add_implementations` function. |
| 139 |
""" |
| 140 |
|
| 141 |
def __init__( |
| 142 |
self, |
| 143 |
pyfunc, |
| 144 |
sympy_func=None, |
| 145 |
arg_units=None, |
| 146 |
arg_names=None, |
| 147 |
return_unit=None, |
| 148 |
arg_types=None, |
| 149 |
return_type=None, |
| 150 |
stateless=True, |
| 151 |
auto_vectorise=False, |
| 152 |
): |
| 153 |
self.pyfunc = pyfunc |
| 154 |
self.sympy_func = sympy_func |
| 155 |
self._arg_units = arg_units |
| 156 |
self._arg_names = arg_names |
| 157 |
self._return_unit = return_unit |
| 158 |
if return_unit is bool: |
| 159 |
self._returns_bool = True |
| 160 |
else: |
| 161 |
self._returns_bool = False |
| 162 |
self._arg_types = arg_types |
| 163 |
self._return_type = return_type |
| 164 |
self.stateless = stateless |
| 165 |
self.auto_vectorise = auto_vectorise |
| 166 |
if self._arg_units is None: |
| 167 |
if not hasattr(pyfunc, "_arg_units"): |
| 168 |
raise ValueError( |
| 169 |
f"The Python function '{pyfunc.__name__}' does not specify " |
| 170 |
"how it deals with units, need to specify " |
| 171 |
"'arg_units' or use the '@check_units' " |
| 172 |
"decorator." |
| 173 |
) |
| 174 |
elif pyfunc._arg_units is None: |
| 175 |
# @check_units sets _arg_units to None if the units aren't |
| 176 |
# specified for all of its arguments |
| 177 |
raise ValueError( |
| 178 |
f"The Python function '{pyfunc.__name__}' does not " |
| 179 |
"specify the units for all of its arguments." |
| 180 |
) |
| 181 |
else: |
| 182 |
self._arg_units = pyfunc._arg_units |
| 183 |
else: |
| 184 |
if any(isinstance(u, str) for u in self._arg_units): |
| 185 |
if self._arg_names is None: |
| 186 |
raise TypeError("Need to specify the names of the arguments.") |
| 187 |
if len(self._arg_names) != len(self._arg_units): |
| 188 |
raise TypeError( |
| 189 |
"arg_names and arg_units need to have the " |
| 190 |
f"same length ({len(self._arg_names)} != " |
| 191 |
f"({len(self._arg_units)})" |
| 192 |
) |
| 193 |
|
| 194 |
if self._return_unit is None: |
| 195 |
if not hasattr(pyfunc, "_return_unit"): |
| 196 |
raise ValueError( |
| 197 |
f"The Python function '{pyfunc.__name__}' does not " |
| 198 |
"specify how it deals with units, need to specify " |
| 199 |
"'return_unit' or use the '@check_units' decorator." |
| 200 |
) |
| 201 |
elif pyfunc._return_unit is None: |
| 202 |
# @check_units sets _return_unit to None if no "result=..." |
| 203 |
# keyword is specified. |
| 204 |
raise ValueError( |
| 205 |
f"The Python function '{pyfunc.__name__}' does not " |
| 206 |
"specify the unit for its return value." |
| 207 |
) |
| 208 |
else: |
| 209 |
self._return_unit = pyfunc._return_unit |
| 210 |
|
| 211 |
if self._arg_types is None: |
| 212 |
if hasattr(pyfunc, "_arg_types"): |
| 213 |
self._arg_types = pyfunc._arg_types |
| 214 |
else: |
| 215 |
self._arg_types = ["any"] * len(self._arg_units) |
| 216 |
|
| 217 |
if self._return_type is None: |
| 218 |
self._return_type = getattr(pyfunc, "_return_type", "float") |
| 219 |
|
| 220 |
for argtype, u in zip(self._arg_types, self._arg_units, strict=True): |
| 221 |
if ( |
| 222 |
argtype != "float" |
| 223 |
and argtype != "any" |
| 224 |
and u is not None |
| 225 |
and not is_dimensionless(u) |
| 226 |
): |
| 227 |
raise TypeError( |
| 228 |
"Non-float arguments must be dimensionless in function" |
| 229 |
f" {pyfunc.__name__}" |
| 230 |
) |
| 231 |
if argtype not in VALID_ARG_TYPES: |
| 232 |
raise ValueError( |
| 233 |
f"Argument type {argtype} is not valid, must be one " |
| 234 |
f"of {VALID_ARG_TYPES}, in function " |
| 235 |
f"'{pyfunc.__name__}'." |
| 236 |
) |
| 237 |
|
| 238 |
if self._return_type not in VALID_RETURN_TYPES: |
| 239 |
raise ValueError( |
| 240 |
f"Return type {self._return_typ} is not valid, must " |
| 241 |
f"be one of {VALID_RETURN_TYPES}, in function " |
| 242 |
f"'{pyfunc.__name__}'" |
| 243 |
) |
| 244 |
|
| 245 |
#: Stores implementations for this function in a |
| 246 |
#: `FunctionImplementationContainer` |
| 247 |
self.implementations = FunctionImplementationContainer(self) |
| 248 |
|
| 249 |
def is_locally_constant(self, dt): |
| 250 |
""" |
| 251 |
Return whether this function (if interpreted as a function of time) |
| 252 |
should be considered constant over a timestep. This is most importantly |
| 253 |
used by `TimedArray` so that linear integration can be used. In its |
| 254 |
standard implementation, always returns ``False``. |
| 255 |
|
| 256 |
Parameters |
| 257 |
---------- |
| 258 |
dt : float |
| 259 |
The length of a timestep (without units). |
| 260 |
|
| 261 |
Returns |
| 262 |
------- |
| 263 |
constant : bool |
| 264 |
Whether the results of this function can be considered constant |
| 265 |
over one timestep of length `dt`. |
| 266 |
""" |
| 267 |
return False |
| 268 |
|
| 269 |
def __call__(self, *args): |
| 270 |
return self.pyfunc(*args) |
| 271 |
|
| 272 |
|
| 273 |
class FunctionImplementation: |
| 274 |
""" |
| 275 |
A simple container object for function implementations. |
| 276 |
|
| 277 |
Parameters |
| 278 |
---------- |
| 279 |
name : str, optional |
| 280 |
The name of the function in the target language. Should only be |
| 281 |
specified if the function has to be renamed for the target language. |
| 282 |
code : language-dependent, optional |
| 283 |
A language dependent argument specifying the implementation in the |
| 284 |
target language, e.g. a code string or a dictionary of code strings. |
| 285 |
namespace : dict-like, optional |
| 286 |
A dictionary of mappings from names to values that should be added |
| 287 |
to the namespace of a `CodeObject` using the function. |
| 288 |
dependencies : dict-like, optional |
| 289 |
A mapping of names to `Function` objects, for additional functions |
| 290 |
needed by this function. |
| 291 |
availability_check : callable, optional |
| 292 |
A function that will be called to check whether the function should be |
| 293 |
made available (e.g. depending on whether it is supported by the |
| 294 |
compiler). The function should do nothing if the function is |
| 295 |
available, or raise a ``NotImplementedError`` with a message |
| 296 |
explaining why it isn't. |
| 297 |
dynamic : bool, optional |
| 298 |
Whether this `code`/`namespace` is dynamic, i.e. generated for each |
| 299 |
new context it is used in. If set to ``True``, `code` and `namespace` |
| 300 |
have to be callable with a `Group` as an argument and are expected |
| 301 |
to return the final `code` and `namespace`. Defaults to ``False``. |
| 302 |
""" |
| 303 |
|
| 304 |
def __init__( |
| 305 |
self, |
| 306 |
name=None, |
| 307 |
code=None, |
| 308 |
namespace=None, |
| 309 |
dependencies=None, |
| 310 |
availability_check=None, |
| 311 |
dynamic=False, |
| 312 |
compiler_kwds=None, |
| 313 |
): |
| 314 |
if compiler_kwds is None: |
| 315 |
compiler_kwds = {} |
| 316 |
self.name = name |
| 317 |
if dependencies is None: |
| 318 |
dependencies = {} |
| 319 |
self.dependencies = dependencies |
| 320 |
self._code = code |
| 321 |
self._namespace = namespace |
| 322 |
self.dynamic = dynamic |
| 323 |
self.compiler_kwds = compiler_kwds |
| 324 |
self.availability_check = availability_check |
| 325 |
|
| 326 |
def get_code(self, owner): |
| 327 |
if self.availability_check is not None: |
| 328 |
self.availability_check() |
| 329 |
if self.dynamic: |
| 330 |
return self._code(owner) |
| 331 |
else: |
| 332 |
return self._code |
| 333 |
|
| 334 |
def get_namespace(self, owner): |
| 335 |
if self.dynamic: |
| 336 |
return self._namespace(owner) |
| 337 |
else: |
| 338 |
return self._namespace |
| 339 |
|
| 340 |
|
| 341 |
class FunctionImplementationContainer(Mapping): |
| 342 |
""" |
| 343 |
Helper object to store implementations and give access in a dictionary-like |
| 344 |
fashion, using `CodeGenerator` implementations as a fallback for `CodeObject` |
| 345 |
implementations. |
| 346 |
""" |
| 347 |
|
| 348 |
def __init__(self, function): |
| 349 |
self._function = function |
| 350 |
self._implementations = dict() |
| 351 |
|
| 352 |
def __getitem__(self, key): |
| 353 |
""" |
| 354 |
Find an implementation for this function that can be used by the |
| 355 |
`CodeObject` given as `key`. Will find implementations registered |
| 356 |
for `key` itself (or one of its parents), or for the `CodeGenerator` |
| 357 |
class that `key` uses (or one of its parents). In all cases, |
| 358 |
implementations registered for the corresponding names qualify as well. |
| 359 |
|
| 360 |
Parameters |
| 361 |
---------- |
| 362 |
key : `CodeObject` |
| 363 |
The `CodeObject` that will use the `Function` |
| 364 |
|
| 365 |
Returns |
| 366 |
------- |
| 367 |
implementation : `FunctionImplementation` |
| 368 |
An implementation suitable for `key`. |
| 369 |
""" |
| 370 |
fallback = getattr(key, "generator_class", None) |
| 371 |
# in some cases we do the code generation with original_generator_class instead (e.g. GSL) |
| 372 |
fallback_parent = getattr(key, "original_generator_class", None) |
| 373 |
|
| 374 |
for K in [key, fallback, fallback_parent]: |
| 375 |
name = getattr(K, "class_name", "no class name for key") |
| 376 |
for impl_key, impl in self._implementations.items(): |
| 377 |
impl_key_name = getattr( |
| 378 |
impl_key, "class_name", "no class name for implementation" |
| 379 |
) |
| 380 |
if (impl_key_name is not None and impl_key_name in [K, name]) or ( |
| 381 |
impl_key is not None and impl_key in [K, name] |
| 382 |
): |
| 383 |
return impl |
| 384 |
if hasattr(K, "__bases__"): |
| 385 |
for cls in inspect.getmro(K): |
| 386 |
if cls in self._implementations: |
| 387 |
return self._implementations[cls] |
| 388 |
name = getattr(cls, "class_name", None) |
| 389 |
if name in self._implementations: |
| 390 |
return self._implementations[name] |
| 391 |
|
| 392 |
# Give a nicer error message if possible |
| 393 |
if getattr(key, "class_name", None) is not None: |
| 394 |
key = key.class_name |
| 395 |
elif getattr(fallback, "class_name", None) is not None: |
| 396 |
key = fallback.class_name |
| 397 |
keys = ", ".join( |
| 398 |
[getattr(k, "class_name", str(k)) for k in self._implementations] |
| 399 |
) |
| 400 |
raise KeyError( |
| 401 |
f"No implementation available for target '{key}'. " |
| 402 |
f"Available implementations: {keys}" |
| 403 |
) |
| 404 |
|
| 405 |
def add_numpy_implementation( |
| 406 |
self, wrapped_func, dependencies=None, discard_units=None, compiler_kwds=None |
| 407 |
): |
| 408 |
""" |
| 409 |
Add a numpy implementation to a `Function`. |
| 410 |
|
| 411 |
Parameters |
| 412 |
---------- |
| 413 |
function : `Function` |
| 414 |
The function description for which an implementation should be added. |
| 415 |
wrapped_func : callable |
| 416 |
The original function (that will be used for the numpy implementation) |
| 417 |
dependencies : list of `Function`, optional |
| 418 |
A list of functions this function needs. |
| 419 |
discard_units : bool, optional |
| 420 |
See `implementation`. |
| 421 |
""" |
| 422 |
if discard_units is None: |
| 423 |
discard_units = prefs["codegen.runtime.numpy.discard_units"] |
| 424 |
|
| 425 |
# Get the original function inside the check_units decorator |
| 426 |
if hasattr(wrapped_func, "_orig_func"): |
| 427 |
orig_func = wrapped_func._orig_func |
| 428 |
else: |
| 429 |
orig_func = wrapped_func |
| 430 |
|
| 431 |
if discard_units: |
| 432 |
new_globals = dict(orig_func.__globals__) |
| 433 |
# strip away units in the function by changing its namespace |
| 434 |
for key, value in new_globals.items(): |
| 435 |
if isinstance(value, Quantity): |
| 436 |
new_globals[key] = np.asarray(value) |
| 437 |
unitless_func = types.FunctionType( |
| 438 |
orig_func.__code__, |
| 439 |
new_globals, |
| 440 |
orig_func.__name__, |
| 441 |
orig_func.__defaults__, |
| 442 |
orig_func.__closure__, |
| 443 |
) |
| 444 |
self._implementations["numpy"] = FunctionImplementation( |
| 445 |
name=None, |
| 446 |
code=unitless_func, |
| 447 |
dependencies=dependencies, |
| 448 |
compiler_kwds=None, |
| 449 |
) |
| 450 |
else: |
| 451 |
|
| 452 |
def wrapper_function(*args): |
| 453 |
arg_units = list(self._function._arg_units) |
| 454 |
|
| 455 |
if self._function.auto_vectorise: |
| 456 |
arg_units += [DIMENSIONLESS] |
| 457 |
if not len(args) == len(arg_units): |
| 458 |
func_name = self._function.pyfunc.__name__ |
| 459 |
raise ValueError( |
| 460 |
f"Function {func_name} got {len(args)} arguments, " |
| 461 |
f"expected {len(arg_units)}." |
| 462 |
) |
| 463 |
new_args = [] |
| 464 |
for arg, arg_unit in zip(args, arg_units, strict=True): |
| 465 |
if ( |
| 466 |
arg_unit is bool |
| 467 |
or arg_unit is None |
| 468 |
or isinstance(arg_unit, str) |
| 469 |
): |
| 470 |
new_args.append(arg) |
| 471 |
else: |
| 472 |
new_args.append( |
| 473 |
Quantity.with_dimensions(arg, get_dimensions(arg_unit)) |
| 474 |
) |
| 475 |
result = orig_func(*new_args) |
| 476 |
if isinstance(self._function._return_unit, Callable): |
| 477 |
return_unit = self._function._return_unit( |
| 478 |
*[get_dimensions(a) for a in args] |
| 479 |
) |
| 480 |
else: |
| 481 |
return_unit = self._function._return_unit |
| 482 |
if return_unit is bool: |
| 483 |
if not ( |
| 484 |
isinstance(result, bool) or np.asarray(result).dtype == bool |
| 485 |
): |
| 486 |
raise TypeError( |
| 487 |
f"The function {orig_func.__name__} returned " |
| 488 |
f"'{result}', but it was expected to return a " |
| 489 |
"boolean value " |
| 490 |
) |
| 491 |
elif ( |
| 492 |
isinstance(return_unit, int) and return_unit == 1 |
| 493 |
) or return_unit.dim is DIMENSIONLESS: |
| 494 |
fail_for_dimension_mismatch( |
| 495 |
result, |
| 496 |
return_unit, |
| 497 |
f"The function '{orig_func.__name__}' " |
| 498 |
f"returned {result}, but it was " |
| 499 |
"expected to return a dimensionless " |
| 500 |
"quantity.", |
| 501 |
) |
| 502 |
else: |
| 503 |
fail_for_dimension_mismatch( |
| 504 |
result, |
| 505 |
return_unit, |
| 506 |
f"The function '{orig_func.__name__}' " |
| 507 |
f"returned {result}, but it was " |
| 508 |
"expected to return a quantity with " |
| 509 |
f"units {return_unit!r}.", |
| 510 |
) |
| 511 |
return np.asarray(result) |
| 512 |
|
| 513 |
self._implementations["numpy"] = FunctionImplementation( |
| 514 |
name=None, code=wrapper_function, dependencies=dependencies |
| 515 |
) |
| 516 |
|
| 517 |
def add_implementation( |
| 518 |
self, |
| 519 |
target, |
| 520 |
code, |
| 521 |
namespace=None, |
| 522 |
dependencies=None, |
| 523 |
availability_check=None, |
| 524 |
name=None, |
| 525 |
compiler_kwds=None, |
| 526 |
): |
| 527 |
self._implementations[target] = FunctionImplementation( |
| 528 |
name=name, |
| 529 |
code=code, |
| 530 |
dependencies=dependencies, |
| 531 |
availability_check=availability_check, |
| 532 |
namespace=namespace, |
| 533 |
compiler_kwds=compiler_kwds, |
| 534 |
) |
| 535 |
|
| 536 |
def add_dynamic_implementation( |
| 537 |
self, |
| 538 |
target, |
| 539 |
code, |
| 540 |
namespace=None, |
| 541 |
dependencies=None, |
| 542 |
availability_check=None, |
| 543 |
name=None, |
| 544 |
compiler_kwds=None, |
| 545 |
): |
| 546 |
""" |
| 547 |
Adds an "dynamic implementation" for this function. `code` and `namespace` |
| 548 |
arguments are expected to be callables that will be called in |
| 549 |
`Network.before_run` with the owner of the `CodeObject` as an argument. |
| 550 |
This allows to generate code that depends on details of the context it |
| 551 |
is run in, e.g. the ``dt`` of a clock. |
| 552 |
""" |
| 553 |
if not callable(code): |
| 554 |
raise TypeError( |
| 555 |
f"code argument has to be a callable, is type {type(code)} instead" |
| 556 |
) |
| 557 |
if namespace is not None and not callable(namespace): |
| 558 |
raise TypeError( |
| 559 |
f"namespace argument has to be a callable, is type {type(code)} instead" |
| 560 |
) |
| 561 |
self._implementations[target] = FunctionImplementation( |
| 562 |
name=name, |
| 563 |
code=code, |
| 564 |
namespace=namespace, |
| 565 |
dependencies=dependencies, |
| 566 |
availability_check=availability_check, |
| 567 |
dynamic=True, |
| 568 |
compiler_kwds=compiler_kwds, |
| 569 |
) |
| 570 |
|
| 571 |
def __len__(self): |
| 572 |
return len(self._implementations) |
| 573 |
|
| 574 |
def __iter__(self): |
| 575 |
return iter(self._implementations) |
| 576 |
|
| 577 |
|
| 578 |
def implementation( |
| 579 |
target, |
| 580 |
code=None, |
| 581 |
namespace=None, |
| 582 |
dependencies=None, |
| 583 |
discard_units=None, |
| 584 |
name=None, |
| 585 |
**compiler_kwds, |
| 586 |
): |
| 587 |
""" |
| 588 |
A simple decorator to extend user-written Python functions to work with code |
| 589 |
generation in other languages. |
| 590 |
|
| 591 |
Parameters |
| 592 |
---------- |
| 593 |
target : str |
| 594 |
Name of the code generation target (e.g. ``'cython'``) for which to add |
| 595 |
an implementation. |
| 596 |
code : str or dict-like, optional |
| 597 |
What kind of code the target language expects is language-specific, |
| 598 |
e.g. C++ code allows for a dictionary of code blocks instead of a |
| 599 |
single string. |
| 600 |
namespaces : dict-like, optional |
| 601 |
A namespace dictionary (i.e. a mapping of names to values) that |
| 602 |
should be added to a `CodeObject` namespace when using this function. |
| 603 |
dependencies : dict-like, optional |
| 604 |
A mapping of names to `Function` objects, for additional functions |
| 605 |
needed by this function. |
| 606 |
discard_units: bool, optional |
| 607 |
Numpy functions can internally make use of the unit system. However, |
| 608 |
during a simulation run, state variables are passed around as unitless |
| 609 |
values for efficiency. If `discard_units` is set to ``False``, input |
| 610 |
arguments will have units added to them so that the function can still |
| 611 |
use units internally (the units will be stripped away from the return |
| 612 |
value as well). Alternatively, if `discard_units` is set to ``True``, |
| 613 |
the function will receive unitless values as its input. The namespace |
| 614 |
of the function will be altered to make references to units (e.g. |
| 615 |
``ms``) refer to the corresponding floating point values so that no |
| 616 |
unit mismatch errors are raised. Note that this system cannot work in |
| 617 |
all cases, e.g. it does not work with functions that internally imports |
| 618 |
values (e.g. does ``from brian2 import ms``) or access values with |
| 619 |
units indirectly (e.g. uses ``brian2.ms`` instead of ``ms``). If no |
| 620 |
value is given, defaults to the preference setting |
| 621 |
`codegen.runtime.numpy.discard_units`. |
| 622 |
name : str, optional |
| 623 |
The name of the function in the target language. Should only be |
| 624 |
specified if the function has to be renamed for the target language. |
| 625 |
compiler_kwds : dict, optional |
| 626 |
Additional keyword arguments will be transferred to the code generation |
| 627 |
stage, e.g. for C++-based targets, the code can make use of additional |
| 628 |
header files by providing a list of strings as the ``headers`` argument. |
| 629 |
|
| 630 |
Notes |
| 631 |
----- |
| 632 |
While it is in principle possible to provide a numpy implementation |
| 633 |
as an argument for this decorator, this is normally not necessary -- the |
| 634 |
numpy implementation should be provided in the decorated function. |
| 635 |
|
| 636 |
If this decorator is used with other decorators such as `check_units` or |
| 637 |
`declare_types`, it should be the uppermost decorator (that is, the |
| 638 |
last one to be applied). |
| 639 |
|
| 640 |
Examples |
| 641 |
-------- |
| 642 |
Sample usage:: |
| 643 |
|
| 644 |
@implementation('cpp',''' |
| 645 |
#include<math.h> |
| 646 |
inline double usersin(double x) |
| 647 |
{ |
| 648 |
return sin(x); |
| 649 |
} |
| 650 |
''') |
| 651 |
def usersin(x): |
| 652 |
return sin(x) |
| 653 |
""" |
| 654 |
|
| 655 |
def do_user_implementation(func): |
| 656 |
# Allow nesting of decorators |
| 657 |
if isinstance(func, Function): |
| 658 |
function = func |
| 659 |
else: |
| 660 |
function = Function(func) |
| 661 |
|
| 662 |
if discard_units: # Add a numpy implementation that discards units |
| 663 |
if not (target == "numpy" and code is None): |
| 664 |
raise TypeError( |
| 665 |
"'discard_units' can only be set for code " |
| 666 |
"generation target 'numpy', without providing " |
| 667 |
"any code." |
| 668 |
) |
| 669 |
function.implementations.add_numpy_implementation( |
| 670 |
wrapped_func=func, |
| 671 |
dependencies=dependencies, |
| 672 |
discard_units=discard_units, |
| 673 |
compiler_kwds=compiler_kwds, |
| 674 |
) |
| 675 |
else: |
| 676 |
function.implementations.add_implementation( |
| 677 |
target, |
| 678 |
code=code, |
| 679 |
dependencies=dependencies, |
| 680 |
namespace=namespace, |
| 681 |
name=name, |
| 682 |
compiler_kwds=compiler_kwds, |
| 683 |
) |
| 684 |
# # copy any annotation attributes |
| 685 |
# if hasattr(func, '_annotation_attributes'): |
| 686 |
# for attrname in func._annotation_attributes: |
| 687 |
# setattr(function, attrname, getattr(func, attrname)) |
| 688 |
# function._annotation_attributes = getattr(func, '_annotation_attributes', []) |
| 689 |
return function |
| 690 |
|
| 691 |
return do_user_implementation |
| 692 |
|
| 693 |
|
| 694 |
class SymbolicConstant(Constant): |
| 695 |
""" |
| 696 |
Class for representing constants (e.g. pi) that are understood by sympy. |
| 697 |
""" |
| 698 |
|
| 699 |
def __init__(self, name, sympy_obj, value): |
| 700 |
super().__init__(name, value=value) |
| 701 |
self.sympy_obj = sympy_obj |
| 702 |
|
| 703 |
|
| 704 |
################################################################################ |
| 705 |
# Standard functions and constants |
| 706 |
################################################################################ |
| 707 |
|
| 708 |
|
| 709 |
def _exprel(x): |
| 710 |
if x.is_zero: |
| 711 |
return S.One |
| 712 |
else: |
| 713 |
return (sympy.exp(x) - S.One) / x |
| 714 |
|
| 715 |
|
| 716 |
class exprel(sympy_Function): |
| 717 |
""" |
| 718 |
Represents ``(exp(x) - 1)/x``. |
| 719 |
|
| 720 |
The benefit of using ``exprel(x)`` over ``(exp(x) - 1)/x`` |
| 721 |
is that the latter is prone to cancellation under finite precision |
| 722 |
arithmetic when x is close to zero, and cannot be evaluated when x is |
| 723 |
equal to zero. |
| 724 |
""" |
| 725 |
|
| 726 |
nargs = 1 |
| 727 |
|
| 728 |
def fdiff(self, argindex=1): |
| 729 |
""" |
| 730 |
Returns the first derivative of this function. |
| 731 |
""" |
| 732 |
if argindex == 1: |
| 733 |
return (sympy.exp(*self.args) * (self.args[0] - S.One) + S.One) / self.args[ |
| 734 |
0 |
| 735 |
] ** 2 |
| 736 |
else: |
| 737 |
raise sympy.ArgumentIndexError(self, argindex) |
| 738 |
|
| 739 |
def _eval_expand_func(self, **hints): |
| 740 |
return _exprel(*self.args) |
| 741 |
|
| 742 |
def _eval_rewrite_as_exp(self, arg, **kwargs): |
| 743 |
if arg.is_zero: |
| 744 |
return S.One |
| 745 |
else: |
| 746 |
return (sympy.exp(arg) - S.One) / arg |
| 747 |
|
| 748 |
_eval_rewrite_as_tractable = _eval_rewrite_as_exp |
| 749 |
|
| 750 |
@classmethod |
| 751 |
def eval(cls, arg): |
| 752 |
if arg is None: |
| 753 |
return None |
| 754 |
if arg.is_zero: |
| 755 |
return S.One |
| 756 |
|
| 757 |
exp_arg = sympy.exp.eval(arg) |
| 758 |
if exp_arg is not None: |
| 759 |
return (exp_arg - S.One) / arg |
| 760 |
|
| 761 |
def _eval_is_real(self): |
| 762 |
return self.args[0].is_real |
| 763 |
|
| 764 |
def _eval_is_finite(self): |
| 765 |
return self.args[0].is_finite |
| 766 |
|
| 767 |
|
| 768 |
_infinity_int = 1073741823 # maximum 32bit integer divided by 2 |
| 769 |
|
| 770 |
|
| 771 |
def timestep(t, dt): |
| 772 |
""" |
| 773 |
Converts a given time to an integer time step. This function slightly shifts |
| 774 |
the time before dividing it by ``dt`` to make sure that multiples of ``dt`` |
| 775 |
do not end up in the preceding time step due to floating point issues. This |
| 776 |
function is used in the refractoriness calculation. |
| 777 |
|
| 778 |
.. versionadded:: 2.1.3 |
| 779 |
|
| 780 |
Parameters |
| 781 |
---------- |
| 782 |
t : np.ndarray, float, Quantity |
| 783 |
The time to convert. |
| 784 |
dt : float or Quantity |
| 785 |
The length of a simulation time step. |
| 786 |
|
| 787 |
Returns |
| 788 |
------- |
| 789 |
ts : np.ndarray, np.int64 |
| 790 |
The time step corresponding to the given time. |
| 791 |
|
| 792 |
Notes |
| 793 |
----- |
| 794 |
This function cannot handle infinity values, use big values instead (e.g. |
| 795 |
a `NeuronGroup` will use ``-1e4*second`` as the value of the ``lastspike`` |
| 796 |
variable for neurons that never spiked). |
| 797 |
""" |
| 798 |
elapsed_steps = np.array((t + 1e-3 * dt) / dt, dtype=np.int64) |
| 799 |
if elapsed_steps.shape == (): |
| 800 |
elapsed_steps = elapsed_steps.item() |
| 801 |
return elapsed_steps |
| 802 |
|
| 803 |
|
| 804 |
DEFAULT_FUNCTIONS = { |
| 805 |
# numpy functions that have the same name in numpy and math.h |
| 806 |
"cos": Function( |
| 807 |
unitsafe.cos, sympy_func=sympy.functions.elementary.trigonometric.cos |
| 808 |
), |
| 809 |
"sin": Function( |
| 810 |
unitsafe.sin, sympy_func=sympy.functions.elementary.trigonometric.sin |
| 811 |
), |
| 812 |
"tan": Function( |
| 813 |
unitsafe.tan, sympy_func=sympy.functions.elementary.trigonometric.tan |
| 814 |
), |
| 815 |
"cosh": Function( |
| 816 |
unitsafe.cosh, sympy_func=sympy.functions.elementary.hyperbolic.cosh |
| 817 |
), |
| 818 |
"sinh": Function( |
| 819 |
unitsafe.sinh, sympy_func=sympy.functions.elementary.hyperbolic.sinh |
| 820 |
), |
| 821 |
"tanh": Function( |
| 822 |
unitsafe.tanh, sympy_func=sympy.functions.elementary.hyperbolic.tanh |
| 823 |
), |
| 824 |
"exp": Function( |
| 825 |
unitsafe.exp, sympy_func=sympy.functions.elementary.exponential.exp |
| 826 |
), |
| 827 |
"log": Function( |
| 828 |
unitsafe.log, sympy_func=sympy.functions.elementary.exponential.log |
| 829 |
), |
| 830 |
"log10": Function(unitsafe.log10, sympy_func=sympy_cfunctions.log10), |
| 831 |
"expm1": Function(unitsafe.expm1, sympy_func=sympy_cfunctions.expm1), |
| 832 |
"exprel": Function(unitsafe.exprel, sympy_func=exprel), |
| 833 |
"log1p": Function(unitsafe.log1p, sympy_func=sympy_cfunctions.log1p), |
| 834 |
"sqrt": Function( |
| 835 |
np.sqrt, |
| 836 |
sympy_func=sympy.functions.elementary.miscellaneous.sqrt, |
| 837 |
arg_units=[None], |
| 838 |
return_unit=lambda u: u**0.5, |
| 839 |
), |
| 840 |
"ceil": Function( |
| 841 |
np.ceil, |
| 842 |
sympy_func=sympy.functions.elementary.integers.ceiling, |
| 843 |
arg_units=[None], |
| 844 |
return_unit=lambda u: u, |
| 845 |
), |
| 846 |
"floor": Function( |
| 847 |
np.floor, |
| 848 |
sympy_func=sympy.functions.elementary.integers.floor, |
| 849 |
arg_units=[None], |
| 850 |
return_unit=lambda u: u, |
| 851 |
), |
| 852 |
# numpy functions that have a different name in numpy and math.h |
| 853 |
"arccos": Function( |
| 854 |
unitsafe.arccos, sympy_func=sympy.functions.elementary.trigonometric.acos |
| 855 |
), |
| 856 |
"arcsin": Function( |
| 857 |
unitsafe.arcsin, sympy_func=sympy.functions.elementary.trigonometric.asin |
| 858 |
), |
| 859 |
"arctan": Function( |
| 860 |
unitsafe.arctan, sympy_func=sympy.functions.elementary.trigonometric.atan |
| 861 |
), |
| 862 |
"abs": Function( |
| 863 |
np.abs, |
| 864 |
return_type="highest", |
| 865 |
sympy_func=sympy.functions.elementary.complexes.Abs, |
| 866 |
arg_units=[None], |
| 867 |
return_unit=lambda u: u, |
| 868 |
), |
| 869 |
"sign": Function( |
| 870 |
pyfunc=np.sign, |
| 871 |
sympy_func=sympy.sign, |
| 872 |
return_type="highest", |
| 873 |
arg_units=[None], |
| 874 |
return_unit=1, |
| 875 |
), |
| 876 |
# functions that need special treatment |
| 877 |
"rand": Function( |
| 878 |
pyfunc=rand, arg_units=[], return_unit=1, stateless=False, auto_vectorise=True |
| 879 |
), |
| 880 |
"randn": Function( |
| 881 |
pyfunc=randn, arg_units=[], return_unit=1, stateless=False, auto_vectorise=True |
| 882 |
), |
| 883 |
"poisson": Function( |
| 884 |
pyfunc=np.random.poisson, |
| 885 |
arg_units=[1], |
| 886 |
return_unit=1, |
| 887 |
return_type="integer", |
| 888 |
stateless=False, |
| 889 |
auto_vectorise=True, |
| 890 |
), |
| 891 |
"clip": Function( |
| 892 |
pyfunc=np.clip, |
| 893 |
arg_units=[None, "a", "a"], |
| 894 |
arg_names=["a", "a_min", "a_max"], |
| 895 |
return_type="highest", |
| 896 |
return_unit=lambda u1, u2, u3: u1, |
| 897 |
), |
| 898 |
"int": Function( |
| 899 |
pyfunc=np.int_, return_type="integer", arg_units=[1], return_unit=1 |
| 900 |
), |
| 901 |
"timestep": Function( |
| 902 |
pyfunc=timestep, |
| 903 |
return_type="integer", |
| 904 |
arg_units=[second, second], |
| 905 |
return_unit=1, |
| 906 |
), |
| 907 |
} |
| 908 |
|
| 909 |
DEFAULT_CONSTANTS = { |
| 910 |
"pi": SymbolicConstant("pi", sympy.pi, value=np.pi), |
| 911 |
"e": SymbolicConstant("e", sympy.E, value=np.e), |
| 912 |
"inf": SymbolicConstant("inf", S.Infinity, value=np.inf), |
| 913 |
"-inf": SymbolicConstant("-inf", S.NegativeInfinity, value=-np.inf), |
| 914 |
} |