Debian Codegraph @

brian2/core/namespace.py

raw
1 """
2 Implementation of the namespace system, used to resolve the identifiers in
3 model equations of `NeuronGroup` and `Synapses`
4 """
5
6 import collections
7 import inspect
8 import itertools
9
10 from brian2.core.functions import DEFAULT_CONSTANTS, DEFAULT_FUNCTIONS
11 from brian2.units.fundamentalunits import (
12 additional_unit_register,
13 standard_unit_register,
14 )
15 from brian2.units.stdunits import stdunits
16 from brian2.utils.logger import get_logger
17
18 __all__ = [
19 "get_local_namespace",
20 "DEFAULT_FUNCTIONS",
21 "DEFAULT_UNITS",
22 "DEFAULT_CONSTANTS",
23 ]
24
25 logger = get_logger(__name__)
26
27
28 def get_local_namespace(level):
29 """
30 Get the surrounding namespace.
31
32 Parameters
33 ----------
34 level : int, optional
35 How far to go back to get the locals/globals. Each function/method
36 call should add ``1`` to this argument, functions/method with a
37 decorator have to add ``2``.
38
39 Returns
40 -------
41 namespace : dict
42 The locals and globals at the given depth of the stack frame.
43 """
44 # Get the locals and globals from the stack frame
45 frame = inspect.currentframe()
46 for _ in range(level + 1):
47 frame = frame.f_back
48 # We return the full stack here, even if it contains a lot of stuff we are
49 # not interested in -- it is cheaper to later raise an error when we find
50 # a specific object with an incorrect type instead of going through this big
51 # list now to check the types of all objects
52 return dict(itertools.chain(frame.f_globals.items(), frame.f_locals.items()))
53
54
55 def _get_default_unit_namespace():
56 """
57 Return the namespace that is used by default for looking up units when
58 defining equations. Contains all registered units and everything from
59 `brian2.units.stdunits` (ms, mV, nS, etc.).
60
61 Returns
62 -------
63 namespace : dict
64 The unit namespace
65 """
66 namespace = collections.OrderedDict(standard_unit_register.units)
67 namespace.update(stdunits)
68 # Include all "simple" units from additional_units, i.e. units like mliter
69 # but not "newton * metre"
70 namespace.update(
71 {
72 name: unit
73 for name, unit in additional_unit_register.units.items()
74 if not unit.iscompound
75 }
76 )
77 return namespace
78
79
80 DEFAULT_UNITS = _get_default_unit_namespace()