Debian Codegraph @

brian2/tests/test_namespaces.py

raw
1 import uuid
2
3 import numpy
4 import pytest
5 import sympy
6
7 from brian2.core.namespace import get_local_namespace
8 from brian2.core.variables import Constant
9 from brian2.groups.group import Group
10 from brian2.units import second, volt
11 from brian2.units.fundamentalunits import Unit
12 from brian2.units.stdunits import Hz, ms, mV
13 from brian2.units.unitsafefunctions import exp, log, sin
14 from brian2.utils.logger import catch_logs
15
16
17 # a simple Group for testing
18 class SimpleGroup(Group):
19 def __init__(self, variables, namespace=None):
20 self.variables = variables
21 # We use a unique name to get repeated warnings
22 Group.__init__(
23 self,
24 namespace=namespace,
25 name=f"simplegroup_{str(uuid.uuid4()).replace('-', '_')}",
26 )
27
28
29 def _assert_one_warning(l):
30 assert len(l) == 1, f"expected one warning got {len(l)}"
31 assert l[0][0] == "WARNING", f"expected a WARNING, got {l[0][0]} instead"
32
33
34 @pytest.mark.codegen_independent
35 def test_default_content():
36 """
37 Test that the default namespace contains standard units and functions.
38 """
39 group = Group()
40 # Units
41 assert group._resolve("second", {}).get_value_with_unit() == second
42 assert group._resolve("volt", {}).get_value_with_unit() == volt
43 assert group._resolve("ms", {}).get_value_with_unit() == ms
44 assert group._resolve("Hz", {}).get_value_with_unit() == Hz
45 assert group._resolve("mV", {}).get_value_with_unit() == mV
46
47 # Functions
48 assert group._resolve("sin", {}).pyfunc == sin
49 assert group._resolve("log", {}).pyfunc == log
50 assert group._resolve("exp", {}).pyfunc == exp
51
52 # Constants
53 assert group._resolve("e", {}).sympy_obj == sympy.E
54 assert group._resolve("e", {}).get_value() == numpy.e
55 assert group._resolve("pi", {}).sympy_obj == sympy.pi
56 assert group._resolve("pi", {}).get_value() == numpy.pi
57 assert group._resolve("inf", {}).sympy_obj == sympy.oo
58 assert group._resolve("inf", {}).get_value() == numpy.inf
59
60
61 @pytest.mark.codegen_independent
62 @pytest.mark.parametrize(
63 "variable",
64 [42, 42.0, True, numpy.int32(42), numpy.float32(42.0), numpy.bool_(True)],
65 )
66 def test_explicit_namespace(variable):
67 """Test resolution with an explicitly provided namespace"""
68 group = SimpleGroup(namespace={"variable": variable}, variables={})
69
70 # Explicitly provided
71 with catch_logs() as l:
72 assert group._resolve("variable", {}).get_value_with_unit() == variable
73 assert len(l) == 0
74
75
76 @pytest.mark.codegen_independent
77 def test_run_namespace():
78 # Value from an explicit run namespace
79 group = SimpleGroup(namespace={}, variables={})
80 with catch_logs() as l:
81 assert (
82 group._resolve(
83 "yet_another_var", run_namespace={"yet_another_var": 17}
84 ).get_value_with_unit()
85 == 17
86 )
87 assert len(l) == 0
88
89
90 @pytest.mark.codegen_independent
91 def test_errors():
92 # No explicit namespace
93 group = SimpleGroup(namespace=None, variables={})
94 with pytest.raises(KeyError):
95 group._resolve("nonexisting_variable", {})
96
97 # Empty explicit namespace
98 group = SimpleGroup(namespace={}, variables={})
99 with pytest.raises(KeyError):
100 group._resolve("nonexisting_variable", {})
101
102 # Illegal name
103 with pytest.raises(ValueError):
104 SimpleGroup(namespace={"_illegal": 3.0}, variables={})
105
106 # Invalid type
107 group = SimpleGroup(namespace={"str_variable": "not allowed"}, variables={})
108 with pytest.raises(KeyError):
109 group._resolve("str_variable", {})
110
111
112 @pytest.mark.codegen_independent
113 def test_resolution():
114 # implicit namespace
115 tau = 10 * ms
116 group = SimpleGroup(namespace=None, variables={})
117 namespace = get_local_namespace(level=0)
118 resolved = group.resolve_all(
119 ["tau", "ms"], namespace, user_identifiers=["tau", "ms"]
120 )
121 assert len(resolved) == 2
122 assert isinstance(resolved, dict)
123 assert resolved["tau"].get_value_with_unit() == tau
124 assert resolved["ms"].get_value_with_unit() == ms
125 del tau
126
127 # explicit namespace
128 group = SimpleGroup(namespace={"tau": 20 * ms}, variables={})
129 namespace = get_local_namespace(level=0)
130 resolved = group.resolve_all(["tau", "ms"], namespace, ["tau", "ms"])
131 assert len(resolved) == 2
132 assert resolved["tau"].get_value_with_unit() == 20 * ms
133
134
135 @pytest.mark.codegen_independent
136 def test_warning():
137 from brian2.core.functions import DEFAULT_FUNCTIONS
138 from brian2.units.stdunits import cm as brian_cm
139
140 # Name in external namespace clashes with unit/function name
141 exp = 23
142 cm = 42
143 group = SimpleGroup(namespace=None, variables={})
144 namespace = get_local_namespace(level=0)
145 with catch_logs() as l:
146 resolved = group.resolve_all(["exp"], namespace)["exp"]
147 assert resolved == DEFAULT_FUNCTIONS["exp"]
148 assert len(l) == 1, f"got warnings: {str(l)}"
149 assert l[0][1].endswith(".resolution_conflict")
150 with catch_logs() as l:
151 resolved = group.resolve_all(["cm"], namespace)["cm"]
152 assert resolved.get_value_with_unit() == brian_cm
153 assert len(l) == 1, f"got warnings: {str(l)}"
154 assert l[0][1].endswith(".resolution_conflict")
155
156
157 @pytest.mark.codegen_independent
158 def test_warning_internal_variables():
159 group1 = SimpleGroup(namespace=None, variables={"N": Constant("N", 5)})
160 group2 = SimpleGroup(namespace=None, variables={"N": Constant("N", 7)})
161 with catch_logs() as l:
162 group1.resolve_all(["N"], run_namespace={"N": 5}) # should not raise a warning
163 assert len(l) == 0, f"got warnings: {str(l)}"
164 with catch_logs() as l:
165 group2.resolve_all(["N"], run_namespace={"N": 5}) # should raise a warning
166 assert len(l) == 1, f"got warnings: {str(l)}"
167 assert l[0][1].endswith(".resolution_conflict")
168
169
170 if __name__ == "__main__":
171 test_default_content()
172 test_explicit_namespace(42)
173 test_run_namespace()
174 test_errors()
175 test_resolution()
176 test_warning()
177 test_warning_internal_variables()