| 1 |
""" |
| 2 |
This module defines the `StateUpdateMethod` class that acts as a base class for |
| 3 |
all stateupdaters and allows to register stateupdaters so that it is able to |
| 4 |
return a suitable stateupdater object for a given set of equations. This is used |
| 5 |
for example in `NeuronGroup` when no state updater is given explicitly. |
| 6 |
""" |
| 7 |
|
| 8 |
import time |
| 9 |
from abc import ABCMeta, abstractmethod |
| 10 |
from collections.abc import Iterable |
| 11 |
|
| 12 |
from brian2.utils.caching import cached |
| 13 |
from brian2.utils.logger import get_logger |
| 14 |
|
| 15 |
__all__ = ["StateUpdateMethod"] |
| 16 |
|
| 17 |
logger = get_logger(__name__) |
| 18 |
|
| 19 |
|
| 20 |
class UnsupportedEquationsException(Exception): |
| 21 |
pass |
| 22 |
|
| 23 |
|
| 24 |
def extract_method_options(method_options, default_options): |
| 25 |
""" |
| 26 |
Helper function to check ``method_options`` against options understood by |
| 27 |
this state updater, and setting default values for all unspecified options. |
| 28 |
|
| 29 |
Parameters |
| 30 |
---------- |
| 31 |
method_options : dict or None |
| 32 |
The options that the user specified for the state update. |
| 33 |
default_options : dict |
| 34 |
The default option values for this state updater (each admissible option |
| 35 |
needs to be present in this dictionary). To specify that a state updater |
| 36 |
does not take any options, provide an empty dictionary as the argument. |
| 37 |
|
| 38 |
Returns |
| 39 |
------- |
| 40 |
options : dict |
| 41 |
The final dictionary with all the options either at their default or at |
| 42 |
the user-specified value. |
| 43 |
|
| 44 |
Raises |
| 45 |
------ |
| 46 |
KeyError |
| 47 |
If the user specifies an option that is not understood by this state |
| 48 |
updater. |
| 49 |
|
| 50 |
Examples |
| 51 |
-------- |
| 52 |
>>> options = extract_method_options({'a': True}, default_options={'b': False, 'c': False}) # doctest: +IGNORE_EXCEPTION_DETAIL |
| 53 |
Traceback (most recent call last): |
| 54 |
... |
| 55 |
KeyError: 'method_options specifies "a", but this is not an option for this state updater. Avalaible options are: "b", "c".' |
| 56 |
>>> options = extract_method_options({'a': True}, default_options={}) # doctest: +IGNORE_EXCEPTION_DETAIL |
| 57 |
Traceback (most recent call last): |
| 58 |
... |
| 59 |
KeyError: 'method_options specifies "a", but this is not an option for this state updater. This state updater does not accept any options.' |
| 60 |
>>> options = extract_method_options({'a': True}, default_options={'a': False, 'b': False}) |
| 61 |
>>> sorted(options.items()) |
| 62 |
[('a', True), ('b', False)] |
| 63 |
""" |
| 64 |
if method_options is None: |
| 65 |
method_options = {} |
| 66 |
for key in method_options: |
| 67 |
if key not in default_options: |
| 68 |
if len(default_options): |
| 69 |
keys = sorted(default_options.keys()) |
| 70 |
options = ( |
| 71 |
"Available options are: " |
| 72 |
+ ", ".join(f"'{key}'" for key in keys) |
| 73 |
+ "." |
| 74 |
) |
| 75 |
else: |
| 76 |
options = "This state updater does not accept any options." |
| 77 |
raise KeyError( |
| 78 |
f"method_options specifies '{key}', but this " |
| 79 |
"is not an option for this state updater. " |
| 80 |
f"{options}" |
| 81 |
) |
| 82 |
filled_options = dict(default_options) |
| 83 |
filled_options.update(method_options) |
| 84 |
return filled_options |
| 85 |
|
| 86 |
|
| 87 |
class StateUpdateMethod(metaclass=ABCMeta): |
| 88 |
stateupdaters = dict() |
| 89 |
|
| 90 |
@abstractmethod |
| 91 |
def __call__(self, equations, variables=None, method_options=None): |
| 92 |
""" |
| 93 |
Generate abstract code from equations. The method also gets the |
| 94 |
the variables because some state updaters have to check whether |
| 95 |
variable names reflect other state variables (which can change from |
| 96 |
timestep to timestep) or are external values (which stay constant during |
| 97 |
a run) For convenience, this arguments are optional -- this allows to |
| 98 |
directly see what code a state updater generates for a set of equations |
| 99 |
by simply writing ``euler(eqs)``, for example. |
| 100 |
|
| 101 |
Parameters |
| 102 |
---------- |
| 103 |
equations : `Equations` |
| 104 |
The model equations. |
| 105 |
variables : dict, optional |
| 106 |
The `Variable` objects for the model variables. |
| 107 |
method_options : dict, optional |
| 108 |
Additional options specific to the state updater. |
| 109 |
Returns |
| 110 |
------- |
| 111 |
code : str |
| 112 |
The abstract code performing a state update step. |
| 113 |
""" |
| 114 |
pass |
| 115 |
|
| 116 |
@staticmethod |
| 117 |
def register(name, stateupdater): |
| 118 |
""" |
| 119 |
Register a state updater. Registered state updaters can be referred to |
| 120 |
via their name. |
| 121 |
|
| 122 |
Parameters |
| 123 |
---------- |
| 124 |
name : str |
| 125 |
A short name for the state updater (e.g. `'euler'`) |
| 126 |
stateupdater : `StateUpdaterMethod` |
| 127 |
The state updater object, e.g. an `ExplicitStateUpdater`. |
| 128 |
""" |
| 129 |
|
| 130 |
# only deal with lower case names -- we don't want to have 'Euler' and |
| 131 |
# 'euler', for example |
| 132 |
name = name.lower() |
| 133 |
if name in StateUpdateMethod.stateupdaters: |
| 134 |
raise ValueError( |
| 135 |
f"A stateupdater with the name '{name}' has already been registered" |
| 136 |
) |
| 137 |
|
| 138 |
if not isinstance(stateupdater, StateUpdateMethod): |
| 139 |
raise ValueError( |
| 140 |
f"Given stateupdater of type {type(stateupdater)} does " |
| 141 |
"not seem to be a valid stateupdater." |
| 142 |
) |
| 143 |
|
| 144 |
StateUpdateMethod.stateupdaters[name] = stateupdater |
| 145 |
|
| 146 |
@staticmethod |
| 147 |
@cached |
| 148 |
def apply_stateupdater( |
| 149 |
equations, variables, method, method_options=None, group_name=None |
| 150 |
): |
| 151 |
""" |
| 152 |
apply_stateupdater(equations, variables, method, method_options=None, group_name=None) |
| 153 |
|
| 154 |
Applies a given state updater to equations. If a `method` is given, the |
| 155 |
state updater with the given name is used or if is a callable, then it |
| 156 |
is used directly. If a `method` is a list of names, all the |
| 157 |
methods will be tried until one that doesn't raise an |
| 158 |
`UnsupportedEquationsException` is found. |
| 159 |
|
| 160 |
Parameters |
| 161 |
---------- |
| 162 |
equations : `Equations` |
| 163 |
The model equations. |
| 164 |
variables : `dict` |
| 165 |
The dictionary of `Variable` objects, describing the internal |
| 166 |
model variables. |
| 167 |
method : {callable, str, list of str} |
| 168 |
A callable usable as a state updater, the name of a registered |
| 169 |
state updater or a list of names of state updaters. |
| 170 |
|
| 171 |
Returns |
| 172 |
------- |
| 173 |
abstract_code : str |
| 174 |
The code integrating the given equations. |
| 175 |
""" |
| 176 |
if isinstance(method, Iterable) and not isinstance(method, str): |
| 177 |
the_method = None |
| 178 |
start_time = time.time() |
| 179 |
for one_method in method: |
| 180 |
try: |
| 181 |
one_method_start_time = time.time() |
| 182 |
code = StateUpdateMethod.apply_stateupdater( |
| 183 |
equations, variables, one_method, group_name=group_name |
| 184 |
) |
| 185 |
the_method = one_method |
| 186 |
one_method_time = time.time() - one_method_start_time |
| 187 |
break |
| 188 |
except UnsupportedEquationsException: |
| 189 |
pass |
| 190 |
except TypeError: |
| 191 |
raise TypeError( |
| 192 |
"Each element in the list of methods has " |
| 193 |
"to be a string or a callable, got " |
| 194 |
f"{type(one_method)}." |
| 195 |
) from None |
| 196 |
total_time = time.time() - start_time |
| 197 |
if the_method is None: |
| 198 |
raise ValueError( |
| 199 |
"No stateupdater that is suitable for the " |
| 200 |
"given equations has been found." |
| 201 |
) |
| 202 |
|
| 203 |
# If only one method was tried |
| 204 |
if method[0] == the_method: |
| 205 |
timing = f"took {one_method_time:.2f}s" |
| 206 |
else: |
| 207 |
timing = ( |
| 208 |
f"took {one_method_time:.2f}s, trying other methods took " |
| 209 |
f"{total_time - one_method_time:.2f}s" |
| 210 |
) |
| 211 |
|
| 212 |
if group_name is not None: |
| 213 |
msg_text = ( |
| 214 |
"No numerical integration method specified for group " |
| 215 |
f"'{group_name}', using method '{the_method}' ({timing})." |
| 216 |
) |
| 217 |
else: |
| 218 |
msg_text = ( |
| 219 |
"No numerical integration method specified, " |
| 220 |
f"using method '{the_method}' ({timing})." |
| 221 |
) |
| 222 |
logger.info(msg_text, "method_choice") |
| 223 |
else: |
| 224 |
if callable(method): |
| 225 |
# if this is a standard state updater, i.e. if it has a |
| 226 |
# can_integrate method, check this method and raise a warning if it |
| 227 |
# claims not to be applicable. |
| 228 |
stateupdater = method |
| 229 |
method = getattr( |
| 230 |
stateupdater, "__name__", repr(stateupdater) |
| 231 |
) # For logging, get a nicer name |
| 232 |
elif isinstance(method, str): |
| 233 |
method = method.lower() # normalize name to lower case |
| 234 |
stateupdater = StateUpdateMethod.stateupdaters.get(method, None) |
| 235 |
if stateupdater is None: |
| 236 |
raise ValueError( |
| 237 |
"No state updater with the name '{method}' is known." |
| 238 |
) |
| 239 |
else: |
| 240 |
raise TypeError( |
| 241 |
"method argument has to be a string, a " |
| 242 |
"callable, or an iterable of such objects. " |
| 243 |
f"Got {type(method)}" |
| 244 |
) |
| 245 |
start_time = time.time() |
| 246 |
code = stateupdater(equations, variables, method_options) |
| 247 |
method_time = time.time() - start_time |
| 248 |
timing = "took %.2fs" % method_time |
| 249 |
if group_name is not None: |
| 250 |
logger.debug( |
| 251 |
f"Group {group_name}: using numerical integration " |
| 252 |
f"method {method} ({timing})", |
| 253 |
"method_choice", |
| 254 |
) |
| 255 |
else: |
| 256 |
logger.debug( |
| 257 |
f"Using numerical integration method: {method} f({{timing}})", |
| 258 |
"method_choice", |
| 259 |
) |
| 260 |
|
| 261 |
return code |