brainstate 0.2.1__py2.py3-none-any.whl → 0.2.2__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- brainstate/__init__.py +167 -169
- brainstate/_compatible_import.py +340 -340
- brainstate/_compatible_import_test.py +681 -681
- brainstate/_deprecation.py +210 -210
- brainstate/_deprecation_test.py +2297 -2319
- brainstate/_error.py +45 -45
- brainstate/_state.py +2157 -1652
- brainstate/_state_test.py +1129 -52
- brainstate/_utils.py +47 -47
- brainstate/environ.py +1495 -1495
- brainstate/environ_test.py +1223 -1223
- brainstate/graph/__init__.py +22 -22
- brainstate/graph/_node.py +240 -240
- brainstate/graph/_node_test.py +589 -589
- brainstate/graph/_operation.py +1620 -1624
- brainstate/graph/_operation_test.py +1147 -1147
- brainstate/mixin.py +1447 -1433
- brainstate/mixin_test.py +1017 -1017
- brainstate/nn/__init__.py +146 -137
- brainstate/nn/_activations.py +1100 -1100
- brainstate/nn/_activations_test.py +354 -354
- brainstate/nn/_collective_ops.py +635 -633
- brainstate/nn/_collective_ops_test.py +774 -774
- brainstate/nn/_common.py +226 -226
- brainstate/nn/_common_test.py +134 -154
- brainstate/nn/_conv.py +2010 -2010
- brainstate/nn/_conv_test.py +849 -849
- brainstate/nn/_delay.py +575 -575
- brainstate/nn/_delay_test.py +243 -243
- brainstate/nn/_dropout.py +618 -618
- brainstate/nn/_dropout_test.py +480 -477
- brainstate/nn/_dynamics.py +870 -1267
- brainstate/nn/_dynamics_test.py +53 -67
- brainstate/nn/_elementwise.py +1298 -1298
- brainstate/nn/_elementwise_test.py +829 -829
- brainstate/nn/_embedding.py +408 -408
- brainstate/nn/_embedding_test.py +156 -156
- brainstate/nn/_event_fixedprob.py +233 -233
- brainstate/nn/_event_fixedprob_test.py +115 -115
- brainstate/nn/_event_linear.py +83 -83
- brainstate/nn/_event_linear_test.py +121 -121
- brainstate/nn/_exp_euler.py +254 -254
- brainstate/nn/_exp_euler_test.py +377 -377
- brainstate/nn/_linear.py +744 -744
- brainstate/nn/_linear_test.py +475 -475
- brainstate/nn/_metrics.py +1070 -1070
- brainstate/nn/_metrics_test.py +611 -611
- brainstate/nn/_module.py +391 -384
- brainstate/nn/_module_test.py +40 -40
- brainstate/nn/_normalizations.py +1334 -1334
- brainstate/nn/_normalizations_test.py +699 -699
- brainstate/nn/_paddings.py +1020 -1020
- brainstate/nn/_paddings_test.py +722 -722
- brainstate/nn/_poolings.py +2239 -2239
- brainstate/nn/_poolings_test.py +952 -952
- brainstate/nn/_rnns.py +946 -946
- brainstate/nn/_rnns_test.py +592 -592
- brainstate/nn/_utils.py +216 -216
- brainstate/nn/_utils_test.py +401 -401
- brainstate/nn/init.py +809 -809
- brainstate/nn/init_test.py +180 -180
- brainstate/random/__init__.py +270 -270
- brainstate/random/{_rand_funs.py → _fun.py} +3938 -3938
- brainstate/random/{_rand_funs_test.py → _fun_test.py} +638 -640
- brainstate/random/_impl.py +672 -0
- brainstate/random/{_rand_seed.py → _seed.py} +675 -675
- brainstate/random/{_rand_seed_test.py → _seed_test.py} +48 -48
- brainstate/random/{_rand_state.py → _state.py} +1320 -1617
- brainstate/random/{_rand_state_test.py → _state_test.py} +551 -551
- brainstate/transform/__init__.py +56 -59
- brainstate/transform/_ad_checkpoint.py +176 -176
- brainstate/transform/_ad_checkpoint_test.py +49 -49
- brainstate/transform/_autograd.py +1025 -1025
- brainstate/transform/_autograd_test.py +1289 -1289
- brainstate/transform/_conditions.py +316 -316
- brainstate/transform/_conditions_test.py +220 -220
- brainstate/transform/_error_if.py +94 -94
- brainstate/transform/_error_if_test.py +52 -52
- brainstate/transform/_find_state.py +200 -0
- brainstate/transform/_find_state_test.py +84 -0
- brainstate/transform/_jit.py +399 -399
- brainstate/transform/_jit_test.py +143 -143
- brainstate/transform/_loop_collect_return.py +675 -675
- brainstate/transform/_loop_collect_return_test.py +58 -58
- brainstate/transform/_loop_no_collection.py +283 -283
- brainstate/transform/_loop_no_collection_test.py +50 -50
- brainstate/transform/_make_jaxpr.py +2176 -2016
- brainstate/transform/_make_jaxpr_test.py +1634 -1510
- brainstate/transform/_mapping.py +607 -529
- brainstate/transform/_mapping_test.py +104 -194
- brainstate/transform/_progress_bar.py +255 -255
- brainstate/transform/_unvmap.py +256 -256
- brainstate/transform/_util.py +286 -286
- brainstate/typing.py +837 -837
- brainstate/typing_test.py +780 -780
- brainstate/util/__init__.py +27 -27
- brainstate/util/_others.py +1024 -1024
- brainstate/util/_others_test.py +962 -962
- brainstate/util/_pretty_pytree.py +1301 -1301
- brainstate/util/_pretty_pytree_test.py +675 -675
- brainstate/util/_pretty_repr.py +462 -462
- brainstate/util/_pretty_repr_test.py +696 -696
- brainstate/util/filter.py +945 -945
- brainstate/util/filter_test.py +911 -911
- brainstate/util/struct.py +910 -910
- brainstate/util/struct_test.py +602 -602
- {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/METADATA +108 -108
- brainstate-0.2.2.dist-info/RECORD +111 -0
- {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/licenses/LICENSE +202 -202
- brainstate/transform/_eval_shape.py +0 -145
- brainstate/transform/_eval_shape_test.py +0 -38
- brainstate/transform/_random.py +0 -171
- brainstate-0.2.1.dist-info/RECORD +0 -111
- {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/WHEEL +0 -0
- {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/top_level.txt +0 -0
brainstate/_state_test.py
CHANGED
@@ -1,52 +1,1129 @@
|
|
1
|
-
# Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
|
2
|
-
#
|
3
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
-
# you may not use this file except in compliance with the License.
|
5
|
-
# You may obtain a copy of the License at
|
6
|
-
#
|
7
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
-
#
|
9
|
-
# Unless required by applicable law or agreed to in writing, software
|
10
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
-
# See the License for the specific language governing permissions and
|
13
|
-
# limitations under the License.
|
14
|
-
# ==============================================================================
|
15
|
-
|
16
|
-
|
17
|
-
import unittest
|
18
|
-
|
19
|
-
import jax
|
20
|
-
|
21
|
-
import
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
def
|
31
|
-
state
|
32
|
-
|
33
|
-
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
|
43
|
-
|
44
|
-
|
45
|
-
state
|
46
|
-
|
47
|
-
|
48
|
-
|
49
|
-
|
50
|
-
|
51
|
-
|
52
|
-
|
1
|
+
# Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
|
16
|
+
|
17
|
+
import unittest
|
18
|
+
|
19
|
+
import jax
|
20
|
+
import jax.numpy as jnp
|
21
|
+
import numpy as np
|
22
|
+
import brainunit as u
|
23
|
+
|
24
|
+
import brainstate as bst
|
25
|
+
|
26
|
+
|
27
|
+
class TestBasicState(unittest.TestCase):
|
28
|
+
"""Test the basic State class functionality."""
|
29
|
+
|
30
|
+
def test_state_initialization(self):
|
31
|
+
"""Test basic state initialization."""
|
32
|
+
value = jnp.array([1.0, 2.0, 3.0])
|
33
|
+
state = bst.State(value, name='test_state')
|
34
|
+
|
35
|
+
self.assertEqual(state.name, 'test_state')
|
36
|
+
np.testing.assert_array_equal(state.value, value)
|
37
|
+
self.assertIsNotNone(state.source_info)
|
38
|
+
|
39
|
+
def test_state_without_name(self):
|
40
|
+
"""Test state initialization without a name."""
|
41
|
+
state = bst.State(jnp.zeros(5))
|
42
|
+
self.assertIsNone(state.name)
|
43
|
+
|
44
|
+
def test_state_value_setter(self):
|
45
|
+
"""Test setting state values."""
|
46
|
+
state = bst.State(jnp.zeros(3))
|
47
|
+
new_value = jnp.array([1.0, 2.0, 3.0])
|
48
|
+
state.value = new_value
|
49
|
+
np.testing.assert_array_equal(state.value, new_value)
|
50
|
+
|
51
|
+
def test_state_value_from_another_state_fails(self):
|
52
|
+
"""Test that setting value from another State raises an error."""
|
53
|
+
state1 = bst.State(jnp.zeros(3))
|
54
|
+
state2 = bst.State(jnp.ones(3))
|
55
|
+
|
56
|
+
with self.assertRaises(ValueError):
|
57
|
+
state1.value = state2
|
58
|
+
|
59
|
+
def test_state_numel(self):
|
60
|
+
"""Test numel calculation."""
|
61
|
+
state = bst.State(jnp.zeros((2, 3, 4)))
|
62
|
+
self.assertEqual(state.numel(), 24)
|
63
|
+
|
64
|
+
state2 = bst.State({'a': jnp.zeros(5), 'b': jnp.zeros((2, 3))})
|
65
|
+
self.assertEqual(state2.numel(), 11)
|
66
|
+
|
67
|
+
def test_state_copy(self):
|
68
|
+
"""Test state copying."""
|
69
|
+
state = bst.State(jnp.array([1.0, 2.0]), name='original')
|
70
|
+
state_copy = state.copy()
|
71
|
+
|
72
|
+
self.assertEqual(state_copy.name, 'original')
|
73
|
+
np.testing.assert_array_equal(state_copy.value, state.value)
|
74
|
+
self.assertIsNot(state_copy, state)
|
75
|
+
|
76
|
+
def test_state_replace(self):
|
77
|
+
"""Test state replace method."""
|
78
|
+
state = bst.State(jnp.array([1.0, 2.0]), name='test')
|
79
|
+
new_state = state.replace(value=jnp.array([3.0, 4.0]))
|
80
|
+
|
81
|
+
np.testing.assert_array_equal(new_state.value, jnp.array([3.0, 4.0]))
|
82
|
+
self.assertEqual(new_state.name, 'test')
|
83
|
+
|
84
|
+
def test_state_replace_with_name(self):
|
85
|
+
"""Test state replace with name update."""
|
86
|
+
state = bst.State(jnp.array([1.0, 2.0]), name='test')
|
87
|
+
new_state = state.replace(_name='new_name')
|
88
|
+
|
89
|
+
self.assertEqual(new_state.name, 'new_name')
|
90
|
+
np.testing.assert_array_equal(new_state.value, state.value)
|
91
|
+
|
92
|
+
def test_state_restore_value(self):
|
93
|
+
"""Test restoring state values."""
|
94
|
+
state = bst.State(jnp.zeros(3))
|
95
|
+
original = state.value.copy()
|
96
|
+
|
97
|
+
state.value = jnp.ones(3)
|
98
|
+
state.restore_value(original)
|
99
|
+
|
100
|
+
np.testing.assert_array_equal(state.value, original)
|
101
|
+
|
102
|
+
def test_state_hashable(self):
|
103
|
+
"""Test that states are hashable."""
|
104
|
+
state = bst.State(jnp.zeros(3))
|
105
|
+
hash_val = hash(state)
|
106
|
+
self.assertIsInstance(hash_val, int)
|
107
|
+
|
108
|
+
# Can be used in sets and dicts
|
109
|
+
state_set = {state}
|
110
|
+
self.assertIn(state, state_set)
|
111
|
+
|
112
|
+
def test_state_to_state_ref(self):
|
113
|
+
"""Test converting state to TreefyState reference."""
|
114
|
+
state = bst.State(jnp.array([1.0, 2.0]), name='test')
|
115
|
+
state_ref = state.to_state_ref()
|
116
|
+
|
117
|
+
self.assertIsInstance(state_ref, bst.TreefyState)
|
118
|
+
np.testing.assert_array_equal(state_ref.value, state.value)
|
119
|
+
self.assertEqual(state_ref.name, 'test')
|
120
|
+
|
121
|
+
def test_state_update_from_ref(self):
|
122
|
+
"""Test updating state from TreefyState reference."""
|
123
|
+
state = bst.State(jnp.zeros(3), name='test')
|
124
|
+
state_ref = bst.TreefyState(bst.State, jnp.ones(3), _name='test', _been_writen=True)
|
125
|
+
|
126
|
+
state.update_from_ref(state_ref)
|
127
|
+
np.testing.assert_array_equal(state.value, jnp.ones(3))
|
128
|
+
|
129
|
+
def test_state_stack_level(self):
|
130
|
+
"""Test state stack level management."""
|
131
|
+
state = bst.State(jnp.zeros(3))
|
132
|
+
initial_level = state.stack_level
|
133
|
+
|
134
|
+
state.increase_stack_level()
|
135
|
+
self.assertEqual(state.stack_level, initial_level + 1)
|
136
|
+
|
137
|
+
state.decrease_stack_level()
|
138
|
+
self.assertEqual(state.stack_level, initial_level)
|
139
|
+
|
140
|
+
# Should not go below 0
|
141
|
+
state.stack_level = 0
|
142
|
+
state.decrease_stack_level()
|
143
|
+
self.assertEqual(state.stack_level, 0)
|
144
|
+
|
145
|
+
|
146
|
+
class TestStateSourceInfo(unittest.TestCase):
|
147
|
+
"""Test state source information tracking."""
|
148
|
+
|
149
|
+
def test_state_source_info(self):
|
150
|
+
"""Test that source info is captured."""
|
151
|
+
state = bst.State(bst.random.randn(10))
|
152
|
+
self.assertIsNotNone(state.source_info)
|
153
|
+
|
154
|
+
def test_state_value_tree(self):
|
155
|
+
"""Test state value tree checking."""
|
156
|
+
state = bst.ShortTermState(jnp.zeros((2, 3)))
|
157
|
+
|
158
|
+
with bst.check_state_value_tree():
|
159
|
+
state.value = jnp.zeros((2, 3))
|
160
|
+
|
161
|
+
with self.assertRaises(ValueError):
|
162
|
+
state.value = (jnp.zeros((2, 3)), jnp.zeros((2, 3)))
|
163
|
+
|
164
|
+
|
165
|
+
class TestStateRepr(unittest.TestCase):
|
166
|
+
"""Test state string representation."""
|
167
|
+
|
168
|
+
def test_state_repr(self):
|
169
|
+
"""Test basic state representation."""
|
170
|
+
state = bst.State(bst.random.randn(10))
|
171
|
+
repr_str = repr(state)
|
172
|
+
self.assertIsInstance(repr_str, str)
|
173
|
+
|
174
|
+
def test_state_dict_repr(self):
|
175
|
+
"""Test state representation with dict value."""
|
176
|
+
state = bst.State({'a': bst.random.randn(10), 'b': bst.random.randn(10)})
|
177
|
+
repr_str = repr(state)
|
178
|
+
self.assertIsInstance(repr_str, str)
|
179
|
+
|
180
|
+
def test_state_list_repr(self):
|
181
|
+
"""Test state representation with list value."""
|
182
|
+
state = bst.State([bst.random.randn(10), bst.random.randn(10)])
|
183
|
+
repr_str = repr(state)
|
184
|
+
self.assertIsInstance(repr_str, str)
|
185
|
+
|
186
|
+
|
187
|
+
class TestShortTermState(unittest.TestCase):
|
188
|
+
"""Test ShortTermState functionality."""
|
189
|
+
|
190
|
+
def test_short_term_state_creation(self):
|
191
|
+
"""Test creating a short-term state."""
|
192
|
+
state = bst.ShortTermState(jnp.zeros(5), name='short_term')
|
193
|
+
self.assertIsInstance(state, bst.ShortTermState)
|
194
|
+
self.assertIsInstance(state, bst.State)
|
195
|
+
self.assertEqual(state.name, 'short_term')
|
196
|
+
|
197
|
+
def test_short_term_state_semantics(self):
|
198
|
+
"""Test that ShortTermState behaves like State."""
|
199
|
+
state = bst.ShortTermState(jnp.array([1.0, 2.0, 3.0]))
|
200
|
+
state.value = jnp.array([4.0, 5.0, 6.0])
|
201
|
+
np.testing.assert_array_equal(state.value, jnp.array([4.0, 5.0, 6.0]))
|
202
|
+
|
203
|
+
|
204
|
+
class TestLongTermState(unittest.TestCase):
|
205
|
+
"""Test LongTermState functionality."""
|
206
|
+
|
207
|
+
def test_long_term_state_creation(self):
|
208
|
+
"""Test creating a long-term state."""
|
209
|
+
state = bst.LongTermState(jnp.zeros(5), name='long_term')
|
210
|
+
self.assertIsInstance(state, bst.LongTermState)
|
211
|
+
self.assertIsInstance(state, bst.State)
|
212
|
+
self.assertEqual(state.name, 'long_term')
|
213
|
+
|
214
|
+
def test_long_term_state_semantics(self):
|
215
|
+
"""Test that LongTermState behaves like State."""
|
216
|
+
state = bst.LongTermState(jnp.array([1.0, 2.0, 3.0]))
|
217
|
+
state.value = jnp.array([4.0, 5.0, 6.0])
|
218
|
+
np.testing.assert_array_equal(state.value, jnp.array([4.0, 5.0, 6.0]))
|
219
|
+
|
220
|
+
|
221
|
+
class TestParamState(unittest.TestCase):
|
222
|
+
"""Test ParamState functionality."""
|
223
|
+
|
224
|
+
def test_param_state_creation(self):
|
225
|
+
"""Test creating a parameter state."""
|
226
|
+
state = bst.ParamState(jnp.zeros((3, 3)), name='weights')
|
227
|
+
self.assertIsInstance(state, bst.ParamState)
|
228
|
+
self.assertIsInstance(state, bst.LongTermState)
|
229
|
+
self.assertEqual(state.name, 'weights')
|
230
|
+
|
231
|
+
def test_param_state_typical_use(self):
|
232
|
+
"""Test typical parameter state usage."""
|
233
|
+
weights = bst.ParamState(jnp.ones((10, 5)), name='layer_weights')
|
234
|
+
bias = bst.ParamState(jnp.zeros(5), name='layer_bias')
|
235
|
+
|
236
|
+
self.assertEqual(weights.value.shape, (10, 5))
|
237
|
+
self.assertEqual(bias.value.shape, (5,))
|
238
|
+
|
239
|
+
|
240
|
+
class TestBatchState(unittest.TestCase):
|
241
|
+
"""Test BatchState functionality."""
|
242
|
+
|
243
|
+
def test_batch_state_creation(self):
|
244
|
+
"""Test creating a batch state."""
|
245
|
+
state = bst.BatchState(jnp.zeros((32, 10)), name='batch')
|
246
|
+
self.assertIsInstance(state, bst.BatchState)
|
247
|
+
self.assertIsInstance(state, bst.LongTermState)
|
248
|
+
|
249
|
+
def test_batch_state_semantics(self):
|
250
|
+
"""Test batch state typical usage."""
|
251
|
+
batch = bst.BatchState(jnp.array([[1, 2], [3, 4], [5, 6]]))
|
252
|
+
self.assertEqual(batch.value.shape, (3, 2))
|
253
|
+
|
254
|
+
|
255
|
+
class TestHiddenState(unittest.TestCase):
|
256
|
+
"""Test HiddenState functionality."""
|
257
|
+
|
258
|
+
def test_hidden_state_creation(self):
|
259
|
+
"""Test creating a hidden state."""
|
260
|
+
state = bst.HiddenState(jnp.zeros(10), name='hidden')
|
261
|
+
self.assertIsInstance(state, bst.HiddenState)
|
262
|
+
self.assertIsInstance(state, bst.ShortTermState)
|
263
|
+
|
264
|
+
def test_hidden_state_with_array(self):
|
265
|
+
"""Test HiddenState with numpy array."""
|
266
|
+
state = bst.HiddenState(np.zeros(5))
|
267
|
+
self.assertEqual(state.varshape, (5,))
|
268
|
+
self.assertEqual(state.num_state, 1)
|
269
|
+
|
270
|
+
def test_hidden_state_with_jax_array(self):
|
271
|
+
"""Test HiddenState with JAX array."""
|
272
|
+
state = bst.HiddenState(jnp.zeros((3, 4)))
|
273
|
+
self.assertEqual(state.varshape, (3, 4))
|
274
|
+
self.assertEqual(state.num_state, 1)
|
275
|
+
|
276
|
+
def test_hidden_state_with_quantity(self):
|
277
|
+
"""Test HiddenState with brainunit Quantity."""
|
278
|
+
state = bst.HiddenState(jnp.zeros(5) * u.mV)
|
279
|
+
self.assertEqual(state.varshape, (5,))
|
280
|
+
self.assertEqual(state.num_state, 1)
|
281
|
+
|
282
|
+
def test_hidden_state_invalid_type(self):
|
283
|
+
"""Test that invalid types raise TypeError."""
|
284
|
+
with self.assertRaises(TypeError):
|
285
|
+
bst.HiddenState([1, 2, 3]) # Python list not allowed
|
286
|
+
|
287
|
+
with self.assertRaises(TypeError):
|
288
|
+
bst.HiddenState({'a': 1}) # Dict not allowed
|
289
|
+
|
290
|
+
def test_hidden_state_varshape(self):
|
291
|
+
"""Test varshape property."""
|
292
|
+
state = bst.HiddenState(jnp.zeros((10, 20)))
|
293
|
+
self.assertEqual(state.varshape, (10, 20))
|
294
|
+
|
295
|
+
def test_hidden_state_num_state(self):
|
296
|
+
"""Test num_state property."""
|
297
|
+
state = bst.HiddenState(jnp.zeros(10))
|
298
|
+
self.assertEqual(state.num_state, 1)
|
299
|
+
|
300
|
+
|
301
|
+
class TestHiddenGroupState(unittest.TestCase):
|
302
|
+
"""Test HiddenGroupState functionality."""
|
303
|
+
|
304
|
+
def test_hidden_group_state_creation(self):
|
305
|
+
"""Test creating a hidden group state."""
|
306
|
+
value = np.random.randn(10, 10, 5)
|
307
|
+
state = bst.HiddenGroupState(value)
|
308
|
+
|
309
|
+
self.assertIsInstance(state, bst.HiddenGroupState)
|
310
|
+
self.assertEqual(state.num_state, 5)
|
311
|
+
self.assertEqual(state.varshape, (10, 10))
|
312
|
+
|
313
|
+
def test_hidden_group_state_with_quantity(self):
|
314
|
+
"""Test HiddenGroupState with Quantity."""
|
315
|
+
value = np.random.randn(10, 10, 5) * u.mV
|
316
|
+
state = bst.HiddenGroupState(value)
|
317
|
+
|
318
|
+
self.assertEqual(state.num_state, 5)
|
319
|
+
self.assertEqual(state.varshape, (10, 10))
|
320
|
+
|
321
|
+
def test_hidden_group_state_invalid_dimensions(self):
|
322
|
+
"""Test that 1D arrays raise ValueError."""
|
323
|
+
with self.assertRaises(ValueError):
|
324
|
+
bst.HiddenGroupState(np.zeros(5))
|
325
|
+
|
326
|
+
def test_hidden_group_state_get_value_by_index(self):
|
327
|
+
"""Test getting value by integer index."""
|
328
|
+
value = np.random.randn(10, 10, 3)
|
329
|
+
state = bst.HiddenGroupState(value)
|
330
|
+
|
331
|
+
first_state = state.get_value(0)
|
332
|
+
self.assertEqual(first_state.shape, (10, 10))
|
333
|
+
np.testing.assert_array_equal(first_state, value[..., 0])
|
334
|
+
|
335
|
+
def test_hidden_group_state_get_value_by_name(self):
|
336
|
+
"""Test getting value by string name."""
|
337
|
+
value = np.random.randn(10, 10, 3)
|
338
|
+
state = bst.HiddenGroupState(value)
|
339
|
+
|
340
|
+
first_state = state.get_value('0')
|
341
|
+
second_state = state.get_value('1')
|
342
|
+
|
343
|
+
np.testing.assert_array_equal(first_state, value[..., 0])
|
344
|
+
np.testing.assert_array_equal(second_state, value[..., 1])
|
345
|
+
|
346
|
+
def test_hidden_group_state_get_value_invalid_index(self):
|
347
|
+
"""Test that invalid indices raise errors."""
|
348
|
+
value = np.random.randn(10, 10, 3)
|
349
|
+
state = bst.HiddenGroupState(value)
|
350
|
+
|
351
|
+
with self.assertRaises(AssertionError):
|
352
|
+
state.get_value(5) # Out of range
|
353
|
+
|
354
|
+
with self.assertRaises(AssertionError):
|
355
|
+
state.get_value('invalid') # Invalid name
|
356
|
+
|
357
|
+
def test_hidden_group_state_set_value_dict(self):
|
358
|
+
"""Test setting values with dictionary."""
|
359
|
+
value = jnp.array(np.random.randn(10, 10, 3))
|
360
|
+
state = bst.HiddenGroupState(value)
|
361
|
+
|
362
|
+
new_val = jnp.ones((10, 10))
|
363
|
+
state.set_value({0: new_val})
|
364
|
+
|
365
|
+
np.testing.assert_array_equal(state.get_value(0), new_val)
|
366
|
+
|
367
|
+
def test_hidden_group_state_set_value_by_name(self):
|
368
|
+
"""Test setting values by name."""
|
369
|
+
value = jnp.array(np.random.randn(10, 10, 3))
|
370
|
+
state = bst.HiddenGroupState(value)
|
371
|
+
|
372
|
+
new_val = jnp.ones((10, 10))
|
373
|
+
state.set_value({'1': new_val})
|
374
|
+
|
375
|
+
np.testing.assert_array_equal(state.get_value(1), new_val)
|
376
|
+
|
377
|
+
def test_hidden_group_state_set_value_list(self):
|
378
|
+
"""Test setting values with list."""
|
379
|
+
value = jnp.array(np.random.randn(10, 10, 3))
|
380
|
+
state = bst.HiddenGroupState(value)
|
381
|
+
|
382
|
+
new_vals = [jnp.ones((10, 10)), jnp.zeros((10, 10))]
|
383
|
+
state.set_value(new_vals)
|
384
|
+
|
385
|
+
np.testing.assert_array_equal(state.get_value(0), new_vals[0])
|
386
|
+
np.testing.assert_array_equal(state.get_value(1), new_vals[1])
|
387
|
+
|
388
|
+
def test_hidden_group_state_set_value_wrong_shape(self):
|
389
|
+
"""Test that wrong shapes raise errors."""
|
390
|
+
value = np.random.randn(10, 10, 3)
|
391
|
+
state = bst.HiddenGroupState(value)
|
392
|
+
|
393
|
+
with self.assertRaises(AssertionError):
|
394
|
+
state.set_value({0: np.ones((5, 5))}) # Wrong shape
|
395
|
+
|
396
|
+
def test_hidden_group_state_name2index(self):
|
397
|
+
"""Test name2index mapping."""
|
398
|
+
value = np.random.randn(10, 10, 5)
|
399
|
+
state = bst.HiddenGroupState(value)
|
400
|
+
|
401
|
+
self.assertEqual(len(state.name2index), 5)
|
402
|
+
self.assertEqual(state.name2index['0'], 0)
|
403
|
+
self.assertEqual(state.name2index['4'], 4)
|
404
|
+
|
405
|
+
|
406
|
+
class TestHiddenTreeState(unittest.TestCase):
|
407
|
+
"""Test HiddenTreeState functionality."""
|
408
|
+
|
409
|
+
def test_hidden_tree_state_from_list(self):
|
410
|
+
"""Test creating HiddenTreeState from list."""
|
411
|
+
value = [
|
412
|
+
np.random.randn(10, 10) * u.mV,
|
413
|
+
np.random.randn(10, 10) * u.mA,
|
414
|
+
np.random.randn(10, 10) * u.mS
|
415
|
+
]
|
416
|
+
state = bst.HiddenTreeState(value)
|
417
|
+
|
418
|
+
self.assertEqual(state.num_state, 3)
|
419
|
+
self.assertEqual(state.varshape, (10, 10))
|
420
|
+
|
421
|
+
def test_hidden_tree_state_from_dict(self):
|
422
|
+
"""Test creating HiddenTreeState from dict."""
|
423
|
+
value = {
|
424
|
+
'v': np.random.randn(10, 10) * u.mV,
|
425
|
+
'i': np.random.randn(10, 10) * u.mA,
|
426
|
+
'g': np.random.randn(10, 10) * u.mS
|
427
|
+
}
|
428
|
+
state = bst.HiddenTreeState(value)
|
429
|
+
|
430
|
+
self.assertEqual(state.num_state, 3)
|
431
|
+
self.assertEqual(state.varshape, (10, 10))
|
432
|
+
self.assertIn('v', state.name2index)
|
433
|
+
self.assertIn('i', state.name2index)
|
434
|
+
self.assertIn('g', state.name2index)
|
435
|
+
|
436
|
+
def test_hidden_tree_state_get_value_by_name(self):
|
437
|
+
"""Test getting values by name."""
|
438
|
+
value = {
|
439
|
+
'v': np.random.randn(10, 10) * u.mV,
|
440
|
+
'i': np.random.randn(10, 10) * u.mA,
|
441
|
+
}
|
442
|
+
state = bst.HiddenTreeState(value)
|
443
|
+
|
444
|
+
v_val = state.get_value('v')
|
445
|
+
self.assertEqual(v_val.shape, (10, 10))
|
446
|
+
self.assertIsInstance(v_val, u.Quantity)
|
447
|
+
self.assertEqual(v_val.unit, u.mV)
|
448
|
+
|
449
|
+
def test_hidden_tree_state_get_value_by_index(self):
|
450
|
+
"""Test getting values by index."""
|
451
|
+
value = {
|
452
|
+
'v': np.random.randn(10, 10) * u.mV,
|
453
|
+
'i': np.random.randn(10, 10) * u.mA,
|
454
|
+
}
|
455
|
+
state = bst.HiddenTreeState(value)
|
456
|
+
|
457
|
+
val0 = state.get_value(0)
|
458
|
+
val1 = state.get_value(1)
|
459
|
+
|
460
|
+
self.assertEqual(val0.shape, (10, 10))
|
461
|
+
self.assertEqual(val1.shape, (10, 10))
|
462
|
+
|
463
|
+
def test_hidden_tree_state_set_value_dict(self):
|
464
|
+
"""Test setting values with dict."""
|
465
|
+
value = {
|
466
|
+
'v': np.random.randn(10, 10) * u.mV,
|
467
|
+
'i': np.random.randn(10, 10) * u.mA,
|
468
|
+
}
|
469
|
+
state = bst.HiddenTreeState(value)
|
470
|
+
|
471
|
+
new_v = np.ones((10, 10)) * u.mV
|
472
|
+
state.set_value({'v': new_v})
|
473
|
+
|
474
|
+
retrieved = state.get_value('v')
|
475
|
+
np.testing.assert_array_almost_equal(retrieved.mantissa, new_v.mantissa)
|
476
|
+
|
477
|
+
def test_hidden_tree_state_set_value_list(self):
|
478
|
+
"""Test setting values with list."""
|
479
|
+
value = [
|
480
|
+
np.random.randn(10, 10) * u.mV,
|
481
|
+
np.random.randn(10, 10) * u.mA,
|
482
|
+
]
|
483
|
+
state = bst.HiddenTreeState(value)
|
484
|
+
|
485
|
+
new_vals = [
|
486
|
+
np.ones((10, 10)) * u.mV,
|
487
|
+
np.zeros((10, 10)) * u.mA,
|
488
|
+
]
|
489
|
+
state.set_value(new_vals)
|
490
|
+
|
491
|
+
val0 = state.get_value(0)
|
492
|
+
np.testing.assert_array_almost_equal(val0.mantissa, new_vals[0].mantissa)
|
493
|
+
|
494
|
+
def test_hidden_tree_state_unit_preservation(self):
|
495
|
+
"""Test that units are preserved correctly."""
|
496
|
+
value = {
|
497
|
+
'v': np.ones((5, 5)) * u.mV,
|
498
|
+
'i': np.ones((5, 5)) * u.mA,
|
499
|
+
}
|
500
|
+
state = bst.HiddenTreeState(value)
|
501
|
+
|
502
|
+
v_val = state.get_value('v')
|
503
|
+
i_val = state.get_value('i')
|
504
|
+
|
505
|
+
self.assertEqual(v_val.unit, u.mV)
|
506
|
+
self.assertEqual(i_val.unit, u.mA)
|
507
|
+
|
508
|
+
def test_hidden_tree_state_dimensionless(self):
|
509
|
+
"""Test handling of dimensionless values."""
|
510
|
+
value = [
|
511
|
+
np.random.randn(10, 10),
|
512
|
+
np.random.randn(10, 10),
|
513
|
+
]
|
514
|
+
state = bst.HiddenTreeState(value)
|
515
|
+
|
516
|
+
val = state.get_value(0)
|
517
|
+
self.assertIsInstance(val, (np.ndarray, jax.Array))
|
518
|
+
|
519
|
+
def test_hidden_tree_state_different_shapes_error(self):
|
520
|
+
"""Test that different shapes raise ValueError."""
|
521
|
+
value = [
|
522
|
+
np.random.randn(10, 10) * u.mV,
|
523
|
+
np.random.randn(5, 5) * u.mA, # Different shape
|
524
|
+
]
|
525
|
+
|
526
|
+
with self.assertRaises(ValueError):
|
527
|
+
bst.HiddenTreeState(value)
|
528
|
+
|
529
|
+
def test_hidden_tree_state_invalid_type_error(self):
|
530
|
+
"""Test that invalid types raise TypeError."""
|
531
|
+
value = {
|
532
|
+
'v': [1, 2, 3], # Python list not allowed
|
533
|
+
'i': np.random.randn(10, 10) * u.mA,
|
534
|
+
}
|
535
|
+
|
536
|
+
with self.assertRaises(TypeError):
|
537
|
+
bst.HiddenTreeState(value)
|
538
|
+
|
539
|
+
def test_hidden_tree_state_name2unit_mapping(self):
|
540
|
+
"""Test name2unit mapping."""
|
541
|
+
value = {
|
542
|
+
'v': np.ones((5, 5)) * u.mV,
|
543
|
+
'i': np.ones((5, 5)) * u.mA,
|
544
|
+
'g': np.ones((5, 5)) * u.mS,
|
545
|
+
}
|
546
|
+
state = bst.HiddenTreeState(value)
|
547
|
+
|
548
|
+
self.assertEqual(state.name2unit['v'], u.mV)
|
549
|
+
self.assertEqual(state.name2unit['i'], u.mA)
|
550
|
+
self.assertEqual(state.name2unit['g'], u.mS)
|
551
|
+
|
552
|
+
def test_hidden_tree_state_index2unit_mapping(self):
|
553
|
+
"""Test index2unit mapping."""
|
554
|
+
value = [
|
555
|
+
np.ones((5, 5)) * u.mV,
|
556
|
+
np.ones((5, 5)) * u.mA,
|
557
|
+
]
|
558
|
+
state = bst.HiddenTreeState(value)
|
559
|
+
|
560
|
+
self.assertEqual(state.index2unit[0], u.mV)
|
561
|
+
self.assertEqual(state.index2unit[1], u.mA)
|
562
|
+
|
563
|
+
|
564
|
+
class TestFakeState(unittest.TestCase):
|
565
|
+
"""Test FakeState functionality."""
|
566
|
+
|
567
|
+
def test_fake_state_creation(self):
|
568
|
+
"""Test creating a fake state."""
|
569
|
+
state = bst.FakeState(42, name='fake')
|
570
|
+
self.assertEqual(state.value, 42)
|
571
|
+
self.assertEqual(state.name, 'fake')
|
572
|
+
|
573
|
+
def test_fake_state_value_setter(self):
|
574
|
+
"""Test setting fake state value."""
|
575
|
+
state = bst.FakeState(10)
|
576
|
+
state.value = 20
|
577
|
+
self.assertEqual(state.value, 20)
|
578
|
+
|
579
|
+
def test_fake_state_name_setter(self):
|
580
|
+
"""Test setting fake state name."""
|
581
|
+
state = bst.FakeState(10, name='old')
|
582
|
+
state.name = 'new'
|
583
|
+
self.assertEqual(state.name, 'new')
|
584
|
+
|
585
|
+
def test_fake_state_repr(self):
|
586
|
+
"""Test fake state representation."""
|
587
|
+
state = bst.FakeState([1, 2, 3])
|
588
|
+
repr_str = repr(state)
|
589
|
+
self.assertIn('FakedState', repr_str)
|
590
|
+
|
591
|
+
|
592
|
+
class TestStateDictManager(unittest.TestCase):
|
593
|
+
"""Test StateDictManager functionality."""
|
594
|
+
|
595
|
+
def test_dict_manager_creation(self):
|
596
|
+
"""Test creating a StateDictManager."""
|
597
|
+
manager = bst.StateDictManager()
|
598
|
+
self.assertIsInstance(manager, bst.StateDictManager)
|
599
|
+
|
600
|
+
def test_dict_manager_add_states(self):
|
601
|
+
"""Test adding states to manager."""
|
602
|
+
manager = bst.StateDictManager()
|
603
|
+
state1 = bst.State(jnp.zeros(5), name='state1')
|
604
|
+
state2 = bst.State(jnp.ones(5), name='state2')
|
605
|
+
|
606
|
+
manager['s1'] = state1
|
607
|
+
manager['s2'] = state2
|
608
|
+
|
609
|
+
self.assertEqual(len(manager), 2)
|
610
|
+
self.assertIn('s1', manager)
|
611
|
+
self.assertIn('s2', manager)
|
612
|
+
|
613
|
+
def test_dict_manager_assign_values(self):
|
614
|
+
"""Test assigning values through manager."""
|
615
|
+
manager = bst.StateDictManager()
|
616
|
+
state = bst.State(jnp.zeros(3), name='test')
|
617
|
+
manager['test'] = state
|
618
|
+
|
619
|
+
new_values = {'test': jnp.array([1.0, 2.0, 3.0])}
|
620
|
+
manager.assign_values(new_values)
|
621
|
+
|
622
|
+
np.testing.assert_array_equal(state.value, new_values['test'])
|
623
|
+
|
624
|
+
def test_dict_manager_collect_values(self):
|
625
|
+
"""Test collecting values from manager."""
|
626
|
+
manager = bst.StateDictManager()
|
627
|
+
state1 = bst.State(jnp.array([1.0, 2.0]), name='s1')
|
628
|
+
state2 = bst.State(jnp.array([3.0, 4.0]), name='s2')
|
629
|
+
|
630
|
+
manager['s1'] = state1
|
631
|
+
manager['s2'] = state2
|
632
|
+
|
633
|
+
values = manager.collect_values()
|
634
|
+
self.assertEqual(len(values), 2)
|
635
|
+
np.testing.assert_array_equal(values['s1'], state1.value)
|
636
|
+
np.testing.assert_array_equal(values['s2'], state2.value)
|
637
|
+
|
638
|
+
def test_dict_manager_split_values(self):
|
639
|
+
"""Test splitting values by type."""
|
640
|
+
manager = bst.StateDictManager()
|
641
|
+
short_state = bst.ShortTermState(jnp.zeros(3))
|
642
|
+
long_state = bst.LongTermState(jnp.ones(3))
|
643
|
+
|
644
|
+
manager['short'] = short_state
|
645
|
+
manager['long'] = long_state
|
646
|
+
|
647
|
+
short_vals, other_vals = manager.split_values(bst.ShortTermState)
|
648
|
+
self.assertEqual(len(short_vals), 1)
|
649
|
+
|
650
|
+
def test_dict_manager_to_dict_values(self):
|
651
|
+
"""Test converting to dict of values."""
|
652
|
+
manager = bst.StateDictManager()
|
653
|
+
state1 = bst.State(jnp.array([1.0]), name='s1')
|
654
|
+
state2 = bst.State(jnp.array([2.0]), name='s2')
|
655
|
+
|
656
|
+
manager['s1'] = state1
|
657
|
+
manager['s2'] = state2
|
658
|
+
|
659
|
+
dict_vals = manager.to_dict_values()
|
660
|
+
self.assertIsInstance(dict_vals, dict)
|
661
|
+
self.assertEqual(len(dict_vals), 2)
|
662
|
+
|
663
|
+
|
664
|
+
class TestStateTraceStack(unittest.TestCase):
|
665
|
+
"""Test StateTraceStack functionality."""
|
666
|
+
|
667
|
+
def test_trace_stack_creation(self):
|
668
|
+
"""Test creating a StateTraceStack."""
|
669
|
+
stack = bst.StateTraceStack(name='test_stack')
|
670
|
+
self.assertEqual(stack.name, 'test_stack')
|
671
|
+
self.assertEqual(len(stack.states), 0)
|
672
|
+
|
673
|
+
def test_trace_stack_read_value(self):
|
674
|
+
"""Test recording state reads."""
|
675
|
+
stack = bst.StateTraceStack()
|
676
|
+
state = bst.State(jnp.zeros(3))
|
677
|
+
|
678
|
+
with stack:
|
679
|
+
_ = state.value
|
680
|
+
|
681
|
+
self.assertEqual(len(stack.states), 1)
|
682
|
+
self.assertIn(state, stack.states)
|
683
|
+
self.assertFalse(stack.been_writen[0])
|
684
|
+
|
685
|
+
def test_trace_stack_write_value(self):
|
686
|
+
"""Test recording state writes."""
|
687
|
+
stack = bst.StateTraceStack()
|
688
|
+
state = bst.State(jnp.zeros(3))
|
689
|
+
|
690
|
+
with stack:
|
691
|
+
state.value = jnp.ones(3)
|
692
|
+
|
693
|
+
self.assertEqual(len(stack.states), 1)
|
694
|
+
self.assertTrue(stack.been_writen[0])
|
695
|
+
|
696
|
+
def test_trace_stack_get_state_values(self):
|
697
|
+
"""Test getting state values from stack."""
|
698
|
+
stack = bst.StateTraceStack()
|
699
|
+
state1 = bst.State(jnp.array([1.0, 2.0]))
|
700
|
+
state2 = bst.State(jnp.array([3.0, 4.0]))
|
701
|
+
|
702
|
+
with stack:
|
703
|
+
_ = state1.value
|
704
|
+
state2.value = jnp.array([5.0, 6.0])
|
705
|
+
|
706
|
+
values = stack.get_state_values()
|
707
|
+
self.assertEqual(len(values), 2)
|
708
|
+
|
709
|
+
def test_trace_stack_get_read_states(self):
|
710
|
+
"""Test getting read-only states."""
|
711
|
+
stack = bst.StateTraceStack()
|
712
|
+
read_state = bst.State(jnp.zeros(3))
|
713
|
+
write_state = bst.State(jnp.ones(3))
|
714
|
+
|
715
|
+
with stack:
|
716
|
+
_ = read_state.value
|
717
|
+
write_state.value = jnp.array([1.0, 2.0, 3.0])
|
718
|
+
|
719
|
+
read_states = stack.get_read_states()
|
720
|
+
self.assertEqual(len(read_states), 1)
|
721
|
+
self.assertIn(read_state, read_states)
|
722
|
+
self.assertNotIn(write_state, read_states)
|
723
|
+
|
724
|
+
def test_trace_stack_get_write_states(self):
|
725
|
+
"""Test getting written states."""
|
726
|
+
stack = bst.StateTraceStack()
|
727
|
+
read_state = bst.State(jnp.zeros(3))
|
728
|
+
write_state = bst.State(jnp.ones(3))
|
729
|
+
|
730
|
+
with stack:
|
731
|
+
_ = read_state.value
|
732
|
+
write_state.value = jnp.array([1.0, 2.0, 3.0])
|
733
|
+
|
734
|
+
write_states = stack.get_write_states()
|
735
|
+
self.assertEqual(len(write_states), 1)
|
736
|
+
self.assertIn(write_state, write_states)
|
737
|
+
self.assertNotIn(read_state, write_states)
|
738
|
+
|
739
|
+
def test_trace_stack_recovery_original_values(self):
|
740
|
+
"""Test recovering original values."""
|
741
|
+
stack = bst.StateTraceStack()
|
742
|
+
state = bst.State(jnp.zeros(3))
|
743
|
+
original = state.value.copy()
|
744
|
+
|
745
|
+
with stack:
|
746
|
+
state.value = jnp.ones(3)
|
747
|
+
|
748
|
+
stack.recovery_original_values()
|
749
|
+
np.testing.assert_array_equal(state.value, original)
|
750
|
+
|
751
|
+
def test_trace_stack_merge(self):
|
752
|
+
"""Test merging trace stacks."""
|
753
|
+
stack1 = bst.StateTraceStack()
|
754
|
+
stack2 = bst.StateTraceStack()
|
755
|
+
|
756
|
+
state1 = bst.State(jnp.zeros(3))
|
757
|
+
state2 = bst.State(jnp.ones(3))
|
758
|
+
|
759
|
+
with stack1:
|
760
|
+
_ = state1.value
|
761
|
+
|
762
|
+
with stack2:
|
763
|
+
state2.value = jnp.array([1.0, 2.0, 3.0])
|
764
|
+
|
765
|
+
merged = stack1.merge(stack2)
|
766
|
+
self.assertEqual(len(merged.states), 2)
|
767
|
+
|
768
|
+
def test_trace_stack_add_operator(self):
|
769
|
+
"""Test using + operator to merge stacks."""
|
770
|
+
stack1 = bst.StateTraceStack()
|
771
|
+
stack2 = bst.StateTraceStack()
|
772
|
+
|
773
|
+
state1 = bst.State(jnp.zeros(3))
|
774
|
+
state2 = bst.State(jnp.ones(3))
|
775
|
+
|
776
|
+
with stack1:
|
777
|
+
_ = state1.value
|
778
|
+
|
779
|
+
with stack2:
|
780
|
+
_ = state2.value
|
781
|
+
|
782
|
+
merged = stack1 + stack2
|
783
|
+
self.assertEqual(len(merged.states), 2)
|
784
|
+
|
785
|
+
def test_trace_stack_state_subset(self):
|
786
|
+
"""Test getting state subset by type."""
|
787
|
+
stack = bst.StateTraceStack()
|
788
|
+
short_state = bst.ShortTermState(jnp.zeros(3))
|
789
|
+
long_state = bst.LongTermState(jnp.ones(3))
|
790
|
+
|
791
|
+
with stack:
|
792
|
+
_ = short_state.value
|
793
|
+
_ = long_state.value
|
794
|
+
|
795
|
+
short_subset = stack.state_subset(bst.ShortTermState)
|
796
|
+
self.assertEqual(len(short_subset), 1)
|
797
|
+
self.assertIn(short_state, short_subset)
|
798
|
+
|
799
|
+
def test_trace_stack_assign_state_vals(self):
|
800
|
+
"""Test assigning state values."""
|
801
|
+
stack = bst.StateTraceStack()
|
802
|
+
state1 = bst.State(jnp.zeros(3))
|
803
|
+
state2 = bst.State(jnp.zeros(3))
|
804
|
+
|
805
|
+
with stack:
|
806
|
+
_ = state1.value
|
807
|
+
state2.value = jnp.ones(3)
|
808
|
+
|
809
|
+
new_vals = [jnp.array([1.0, 1.0, 1.0]), jnp.array([2.0, 2.0, 2.0])]
|
810
|
+
stack.assign_state_vals(new_vals)
|
811
|
+
|
812
|
+
np.testing.assert_array_equal(state2.value, new_vals[1])
|
813
|
+
|
814
|
+
|
815
|
+
class TestTreefyState(unittest.TestCase):
|
816
|
+
"""Test TreefyState functionality."""
|
817
|
+
|
818
|
+
def test_treefy_state_creation(self):
|
819
|
+
"""Test creating a TreefyState."""
|
820
|
+
ref = bst.TreefyState(bst.State, jnp.array([1.0, 2.0]), _name='test')
|
821
|
+
self.assertEqual(ref.name, 'test')
|
822
|
+
np.testing.assert_array_equal(ref.value, jnp.array([1.0, 2.0]))
|
823
|
+
|
824
|
+
def test_treefy_state_replace(self):
|
825
|
+
"""Test replacing TreefyState value."""
|
826
|
+
ref = bst.TreefyState(bst.State, jnp.zeros(3), _name='test')
|
827
|
+
new_ref = ref.replace(jnp.ones(3))
|
828
|
+
|
829
|
+
np.testing.assert_array_equal(new_ref.value, jnp.ones(3))
|
830
|
+
self.assertEqual(new_ref.name, 'test')
|
831
|
+
|
832
|
+
def test_treefy_state_to_state(self):
|
833
|
+
"""Test converting TreefyState to State."""
|
834
|
+
ref = bst.TreefyState(bst.State, jnp.array([1.0, 2.0]), _name='test')
|
835
|
+
state = ref.to_state()
|
836
|
+
|
837
|
+
self.assertIsInstance(state, bst.State)
|
838
|
+
np.testing.assert_array_equal(state.value, ref.value)
|
839
|
+
self.assertEqual(state.name, 'test')
|
840
|
+
|
841
|
+
def test_treefy_state_copy(self):
|
842
|
+
"""Test copying TreefyState."""
|
843
|
+
ref = bst.TreefyState(bst.State, jnp.array([1.0, 2.0]), _name='test')
|
844
|
+
ref_copy = ref.copy()
|
845
|
+
|
846
|
+
self.assertIsNot(ref, ref_copy)
|
847
|
+
np.testing.assert_array_equal(ref_copy.value, ref.value)
|
848
|
+
|
849
|
+
def test_treefy_state_get_metadata(self):
|
850
|
+
"""Test getting metadata from TreefyState."""
|
851
|
+
ref = bst.TreefyState(bst.State, jnp.zeros(3), _name='test', _been_writen=True)
|
852
|
+
metadata = ref.get_metadata()
|
853
|
+
|
854
|
+
self.assertIsInstance(metadata, dict)
|
855
|
+
self.assertEqual(metadata['_name'], 'test')
|
856
|
+
self.assertTrue(metadata['_been_writen'])
|
857
|
+
self.assertNotIn('type', metadata)
|
858
|
+
self.assertNotIn('value', metadata)
|
859
|
+
|
860
|
+
def test_treefy_state_pytree_operations(self):
|
861
|
+
"""Test that TreefyState works as a pytree."""
|
862
|
+
ref = bst.TreefyState(bst.State, jnp.array([1.0, 2.0]), _name='test')
|
863
|
+
|
864
|
+
# Test tree_map
|
865
|
+
mapped = jax.tree.map(lambda x: x * 2, ref)
|
866
|
+
np.testing.assert_array_equal(mapped.value, jnp.array([2.0, 4.0]))
|
867
|
+
|
868
|
+
# Test tree_leaves
|
869
|
+
leaves = jax.tree.leaves(ref)
|
870
|
+
self.assertEqual(len(leaves), 1)
|
871
|
+
|
872
|
+
|
873
|
+
class TestContextManagers(unittest.TestCase):
|
874
|
+
"""Test context managers and utility functions."""
|
875
|
+
|
876
|
+
def test_check_state_value_tree(self):
|
877
|
+
"""Test check_state_value_tree context manager."""
|
878
|
+
state = bst.State(jnp.zeros((2, 3)))
|
879
|
+
|
880
|
+
# Should not raise error
|
881
|
+
with bst.check_state_value_tree():
|
882
|
+
state.value = jnp.ones((2, 3))
|
883
|
+
|
884
|
+
# Should raise error on tree structure change
|
885
|
+
with bst.check_state_value_tree():
|
886
|
+
with self.assertRaises(ValueError):
|
887
|
+
state.value = {'a': jnp.zeros((2, 3))}
|
888
|
+
|
889
|
+
def test_check_state_value_tree_nested(self):
|
890
|
+
"""Test nested check_state_value_tree contexts."""
|
891
|
+
state = bst.State(jnp.zeros(3))
|
892
|
+
|
893
|
+
with bst.check_state_value_tree(True):
|
894
|
+
with bst.check_state_value_tree(False):
|
895
|
+
# Inner context disables checking
|
896
|
+
state.value = {'a': jnp.zeros(3)} # Should not raise
|
897
|
+
|
898
|
+
def test_maybe_state(self):
|
899
|
+
"""Test maybe_state utility function."""
|
900
|
+
state = bst.State(jnp.array([1.0, 2.0, 3.0]))
|
901
|
+
|
902
|
+
# Should extract value from State
|
903
|
+
result = bst.maybe_state(state)
|
904
|
+
np.testing.assert_array_equal(result, jnp.array([1.0, 2.0, 3.0]))
|
905
|
+
|
906
|
+
# Should return non-State values as-is
|
907
|
+
value = jnp.array([4.0, 5.0, 6.0])
|
908
|
+
result = bst.maybe_state(value)
|
909
|
+
np.testing.assert_array_equal(result, value)
|
910
|
+
|
911
|
+
def test_catch_new_states(self):
|
912
|
+
"""Test catch_new_states context manager."""
|
913
|
+
with bst.catch_new_states('test_tag') as catcher:
|
914
|
+
state1 = bst.State(jnp.zeros(3))
|
915
|
+
state2 = bst.State(jnp.ones(3))
|
916
|
+
|
917
|
+
self.assertEqual(len(catcher), 2)
|
918
|
+
self.assertEqual(state1.tag, 'test_tag')
|
919
|
+
self.assertEqual(state2.tag, 'test_tag')
|
920
|
+
|
921
|
+
def test_catch_new_states_get_states(self):
|
922
|
+
"""Test getting caught states."""
|
923
|
+
with bst.catch_new_states() as catcher:
|
924
|
+
state = bst.State(jnp.zeros(3))
|
925
|
+
|
926
|
+
states = catcher.get_states()
|
927
|
+
self.assertEqual(len(states), 1)
|
928
|
+
self.assertIn(state, states)
|
929
|
+
|
930
|
+
def test_catch_new_states_get_state_values(self):
|
931
|
+
"""Test getting caught state values."""
|
932
|
+
with bst.catch_new_states() as catcher:
|
933
|
+
state = bst.State(jnp.array([1.0, 2.0]))
|
934
|
+
|
935
|
+
values = catcher.get_state_values()
|
936
|
+
self.assertEqual(len(values), 1)
|
937
|
+
np.testing.assert_array_equal(values[0], jnp.array([1.0, 2.0]))
|
938
|
+
|
939
|
+
|
940
|
+
class TestStateCatcher(unittest.TestCase):
|
941
|
+
"""Test StateCatcher functionality via catch_new_states context manager."""
|
942
|
+
|
943
|
+
def test_catch_new_states_basic(self):
|
944
|
+
"""Test basic catch_new_states functionality."""
|
945
|
+
with bst.catch_new_states('test') as catcher:
|
946
|
+
state = bst.State(jnp.zeros(3))
|
947
|
+
|
948
|
+
self.assertEqual(len(catcher), 1)
|
949
|
+
self.assertEqual(state.tag, 'test')
|
950
|
+
|
951
|
+
def test_catch_multiple_states(self):
|
952
|
+
"""Test catching multiple states."""
|
953
|
+
with bst.catch_new_states('test') as catcher:
|
954
|
+
state1 = bst.State(jnp.zeros(3))
|
955
|
+
state2 = bst.State(jnp.ones(3))
|
956
|
+
state3 = bst.State(jnp.array([1.0, 2.0]))
|
957
|
+
|
958
|
+
self.assertEqual(len(catcher), 3)
|
959
|
+
self.assertIn(state1, catcher.get_states())
|
960
|
+
self.assertIn(state2, catcher.get_states())
|
961
|
+
self.assertIn(state3, catcher.get_states())
|
962
|
+
|
963
|
+
def test_catcher_iteration(self):
|
964
|
+
"""Test iterating over caught states."""
|
965
|
+
with bst.catch_new_states('test') as catcher:
|
966
|
+
states = [bst.State(jnp.zeros(i+1)) for i in range(3)]
|
967
|
+
|
968
|
+
collected = list(catcher)
|
969
|
+
self.assertEqual(len(collected), 3)
|
970
|
+
|
971
|
+
def test_catcher_indexing(self):
|
972
|
+
"""Test indexing into catcher."""
|
973
|
+
with bst.catch_new_states('test') as catcher:
|
974
|
+
state = bst.State(jnp.zeros(3))
|
975
|
+
|
976
|
+
self.assertIs(catcher[0], state)
|
977
|
+
|
978
|
+
def test_catcher_contains(self):
|
979
|
+
"""Test checking if state is in catcher."""
|
980
|
+
with bst.catch_new_states('test') as catcher:
|
981
|
+
state = bst.State(jnp.zeros(3))
|
982
|
+
|
983
|
+
self.assertIn(state, catcher)
|
984
|
+
|
985
|
+
def test_catcher_get_states(self):
|
986
|
+
"""Test getting list of caught states."""
|
987
|
+
with bst.catch_new_states('test') as catcher:
|
988
|
+
state1 = bst.State(jnp.zeros(3))
|
989
|
+
state2 = bst.State(jnp.ones(3))
|
990
|
+
|
991
|
+
states = catcher.get_states()
|
992
|
+
self.assertEqual(len(states), 2)
|
993
|
+
self.assertIn(state1, states)
|
994
|
+
self.assertIn(state2, states)
|
995
|
+
|
996
|
+
def test_catcher_get_state_values(self):
|
997
|
+
"""Test getting values of caught states."""
|
998
|
+
with bst.catch_new_states('test') as catcher:
|
999
|
+
state = bst.State(jnp.array([1.0, 2.0, 3.0]))
|
1000
|
+
|
1001
|
+
values = catcher.get_state_values()
|
1002
|
+
self.assertEqual(len(values), 1)
|
1003
|
+
np.testing.assert_array_equal(values[0], jnp.array([1.0, 2.0, 3.0]))
|
1004
|
+
|
1005
|
+
def test_nested_catch_contexts(self):
|
1006
|
+
"""Test nested catch_new_states contexts."""
|
1007
|
+
with bst.catch_new_states('outer') as outer_catcher:
|
1008
|
+
outer_state = bst.State(jnp.zeros(3))
|
1009
|
+
|
1010
|
+
with bst.catch_new_states('inner') as inner_catcher:
|
1011
|
+
inner_state = bst.State(jnp.ones(3))
|
1012
|
+
|
1013
|
+
# Inner catcher should have only inner state
|
1014
|
+
self.assertEqual(len(inner_catcher), 1)
|
1015
|
+
self.assertIn(inner_state, inner_catcher)
|
1016
|
+
|
1017
|
+
# Outer catcher should have both states
|
1018
|
+
self.assertEqual(len(outer_catcher), 2)
|
1019
|
+
self.assertIn(outer_state, outer_catcher)
|
1020
|
+
self.assertIn(inner_state, outer_catcher)
|
1021
|
+
|
1022
|
+
|
1023
|
+
class TestIntegrationScenarios(unittest.TestCase):
|
1024
|
+
"""Test integration scenarios combining multiple features."""
|
1025
|
+
|
1026
|
+
def test_neural_network_state_management(self):
|
1027
|
+
"""Test typical neural network state management scenario."""
|
1028
|
+
# Create network states
|
1029
|
+
weights = bst.ParamState(jnp.ones((10, 5)), name='weights')
|
1030
|
+
bias = bst.ParamState(jnp.zeros(5), name='bias')
|
1031
|
+
hidden = bst.HiddenState(jnp.zeros(5), name='hidden')
|
1032
|
+
|
1033
|
+
# Trace computation
|
1034
|
+
stack = bst.StateTraceStack(name='forward')
|
1035
|
+
with stack:
|
1036
|
+
# Simulate forward pass
|
1037
|
+
x = jnp.ones(10)
|
1038
|
+
h = jnp.dot(x, weights.value) + bias.value
|
1039
|
+
hidden.value = h
|
1040
|
+
|
1041
|
+
# Check that states were tracked
|
1042
|
+
self.assertIn(weights, stack.states)
|
1043
|
+
self.assertIn(bias, stack.states)
|
1044
|
+
self.assertIn(hidden, stack.states)
|
1045
|
+
|
1046
|
+
# Check read/write status
|
1047
|
+
write_states = stack.get_write_states()
|
1048
|
+
self.assertIn(hidden, write_states)
|
1049
|
+
|
1050
|
+
def test_recurrent_network_with_multiple_hidden_states(self):
|
1051
|
+
"""Test RNN with multiple hidden states using HiddenGroupState."""
|
1052
|
+
# Create group of hidden states (e.g., LSTM: h, c)
|
1053
|
+
hidden_group = bst.HiddenGroupState(jnp.array(np.random.randn(10, 10, 2)))
|
1054
|
+
|
1055
|
+
# Access individual hidden states
|
1056
|
+
h = hidden_group.get_value(0)
|
1057
|
+
c = hidden_group.get_value(1)
|
1058
|
+
|
1059
|
+
self.assertEqual(h.shape, (10, 10))
|
1060
|
+
self.assertEqual(c.shape, (10, 10))
|
1061
|
+
|
1062
|
+
# Update hidden states
|
1063
|
+
new_h = jnp.tanh(h)
|
1064
|
+
new_c = c * 0.9
|
1065
|
+
hidden_group.set_value({0: new_h, 1: new_c})
|
1066
|
+
|
1067
|
+
# Verify updates
|
1068
|
+
np.testing.assert_array_almost_equal(hidden_group.get_value(0), new_h)
|
1069
|
+
np.testing.assert_array_almost_equal(hidden_group.get_value(1), new_c)
|
1070
|
+
|
1071
|
+
def test_state_dict_manager_integration(self):
|
1072
|
+
"""Test managing multiple states with StateDictManager."""
|
1073
|
+
manager = bst.StateDictManager()
|
1074
|
+
|
1075
|
+
# Create and register states
|
1076
|
+
with bst.catch_new_states('network') as catcher:
|
1077
|
+
weights = bst.ParamState(jnp.ones((5, 3)), name='weights')
|
1078
|
+
bias = bst.ParamState(jnp.zeros(3), name='bias')
|
1079
|
+
hidden = bst.HiddenState(jnp.zeros(3), name='hidden')
|
1080
|
+
|
1081
|
+
# Add to manager
|
1082
|
+
for state in catcher.get_states():
|
1083
|
+
if state.name:
|
1084
|
+
manager[state.name] = state
|
1085
|
+
|
1086
|
+
# Collect all values
|
1087
|
+
values = manager.collect_values()
|
1088
|
+
self.assertEqual(len(values), 3)
|
1089
|
+
|
1090
|
+
# Split by type
|
1091
|
+
params, others = manager.split_values(bst.ParamState)
|
1092
|
+
self.assertEqual(len(params), 2)
|
1093
|
+
|
1094
|
+
def test_eligibility_trace_learning(self):
|
1095
|
+
"""Test eligibility trace-based learning with HiddenTreeState."""
|
1096
|
+
# Create multiple eligibility traces with different units
|
1097
|
+
traces = bst.HiddenTreeState({
|
1098
|
+
'v': np.random.randn(10, 10) * u.mV,
|
1099
|
+
'u': np.random.randn(10, 10) * u.mV,
|
1100
|
+
'g': np.random.randn(10, 10) * u.mS,
|
1101
|
+
})
|
1102
|
+
|
1103
|
+
# Verify structure
|
1104
|
+
self.assertEqual(traces.num_state, 3)
|
1105
|
+
self.assertEqual(traces.varshape, (10, 10))
|
1106
|
+
|
1107
|
+
# Update individual traces
|
1108
|
+
new_v = np.ones((10, 10)) * u.mV
|
1109
|
+
traces.set_value({'v': new_v})
|
1110
|
+
|
1111
|
+
retrieved_v = traces.get_value('v')
|
1112
|
+
np.testing.assert_array_almost_equal(retrieved_v.mantissa, new_v.mantissa)
|
1113
|
+
self.assertEqual(retrieved_v.unit, u.mV)
|
1114
|
+
|
1115
|
+
def test_jit_compilation_with_states(self):
|
1116
|
+
"""Test that states work with JAX JIT compilation."""
|
1117
|
+
state = bst.State(jnp.array([1.0, 2.0, 3.0]))
|
1118
|
+
|
1119
|
+
@jax.jit
|
1120
|
+
def update_state(x):
|
1121
|
+
state.value = state.value + x
|
1122
|
+
return state.value
|
1123
|
+
|
1124
|
+
result = update_state(jnp.array([1.0, 1.0, 1.0]))
|
1125
|
+
np.testing.assert_array_equal(result, jnp.array([2.0, 3.0, 4.0]))
|
1126
|
+
|
1127
|
+
|
1128
|
+
if __name__ == '__main__':
|
1129
|
+
unittest.main()
|