brainx-skill 1.0.3 → 1.0.8

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.
Files changed (117) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +29 -64
  3. package/adapters/gemini.js +7 -0
  4. package/adapters/opencode.js +7 -0
  5. package/adapters/windsurf.js +7 -0
  6. package/{lib → installation/lib}/installer.js +8 -5
  7. package/manifest.json +7 -1
  8. package/package.json +25 -10
  9. package/skills/braincell/SKILL.md +182 -0
  10. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  11. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
  12. package/skills/braincell/references/channel-library.md +170 -0
  13. package/skills/braincell/references/ion-library.md +154 -0
  14. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  15. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  16. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  17. package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
  18. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  19. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  20. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  21. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
  22. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  23. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  24. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  25. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  26. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  27. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  28. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  29. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  30. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  31. package/skills/brainevent/SKILL.md +268 -0
  32. package/skills/brainevent/references/connectivity-variants.md +312 -0
  33. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  34. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  35. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  36. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  37. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  38. package/skills/brainevent/references/sparse-formats.md +182 -0
  39. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  40. package/skills/brainpy-state/SKILL.md +232 -0
  41. package/skills/brainpy-state/references/array-creation.md +158 -0
  42. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  43. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  44. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  45. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  46. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  47. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  48. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  49. package/skills/brainpy-state/references/component-selection.md +273 -0
  50. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  51. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  52. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  53. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  54. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  55. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  56. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  57. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  58. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  59. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  60. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  61. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  62. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  63. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  64. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  65. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  66. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  67. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  68. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  69. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  70. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  71. package/skills/brainstate/SKILL.md +399 -0
  72. package/skills/brainstate/agents/openai.yaml +4 -0
  73. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
  75. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
  76. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  77. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
  78. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
  79. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
  80. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
  81. package/skills/brainstate/references/collective_model_operations.md +195 -0
  82. package/skills/brainstate/references/extension_mechanisms.md +293 -0
  83. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
  84. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
  85. package/skills/brainstate/references/model-interop-and-migration.md +305 -0
  86. package/skills/brainstate/references/simulation-environment.md +117 -0
  87. package/skills/brainstate/references/size-inference-variations.md +279 -0
  88. package/skills/brainstate/references/state-graph-operations.md +216 -0
  89. package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
  90. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  91. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  92. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  93. package/skills/brainstate/scripts/resnet.py +130 -0
  94. package/skills/brainunit/SKILL.md +287 -0
  95. package/skills/brainunit/references/array-creation.md +158 -0
  96. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  97. package/skills/brainunit/references/array-mechanics.md +165 -0
  98. package/skills/brainunit/references/math-function-library.md +433 -0
  99. package/skills/brainunit/references/physical-constant-library.md +58 -0
  100. package/skills/brainunit/references/prefix-library.md +116 -0
  101. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  102. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  103. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  104. package/skills/brainx-general-guard/SKILL.md +153 -0
  105. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
  106. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
  107. package/skills/brainx-install/SKILL.md +2 -2
  108. package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
  109. /package/{bin → installation/bin}/brainx.js +0 -0
  110. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  111. /package/{lib → installation/lib}/bundle.js +0 -0
  112. /package/{lib → installation/lib}/cli.js +0 -0
  113. /package/{lib → installation/lib}/constants.js +0 -0
  114. /package/{lib → installation/lib}/hash.js +0 -0
  115. /package/{lib → installation/lib}/paths.js +0 -0
  116. /package/{lib → installation/lib}/prompts.js +0 -0
  117. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -0,0 +1,279 @@
1
+ # Size inference and composition
2
+
3
+ Use this reference to compose size-aware layers with `Sequential` and `.desc()`, or when stride, padding, dimensionality, pooling mode, or flatten axes make a layer's size behavior non-obvious.
4
+
5
+ ## Selection map
6
+
7
+ | Need | Use | Key constraint |
8
+ |---|---|---|
9
+ | Infer each next layer from the previous output | Give the first layer `in_size`, then use `.desc()` | Every descriptor must receive enough non-size constructor arguments to instantiate later. |
10
+ | Predict convolution output | Inspect `stride`, `padding`, dilation, rank, and channel layout | Use `stride`, not the obsolete `strides` spelling. |
11
+ | Reduce by local windows | `AvgPool*`, `MaxPool*`, or `LPPool*` | Kernel, stride, padding, and channel axis determine the result. |
12
+ | Produce a fixed spatial target | `AdaptiveAvgPool*` or `AdaptiveMaxPool*` | `target_size` determines the spatial output independently of input size. |
13
+ | Flatten a runtime batch | Set `start_axis` to preserve the batch axis | Runtime axes include batch; Module `in_size` metadata does not. |
14
+ | Flatten feature metadata for composition | Construct `Flatten(in_size=feature_size)` or use `.desc()` | Feature `in_size` excludes the batch dimension. |
15
+
16
+ ## Compose `ComplexNet` with `Sequential` and `.desc()`
17
+
18
+ Give the first layer an explicit `in_size`, then use `.desc()` wherever `Sequential` should instantiate a layer from the preceding `out_size`. Start the classifier from `self.features.out_size` so flattening and dense construction stay coupled to the feature extractor.
19
+
20
+ ```python
21
+ import brainstate
22
+ import brainstate.nn as nn
23
+
24
+
25
+ class ComplexNet(brainstate.nn.Module):
26
+ def __init__(self, in_size):
27
+ super().__init__()
28
+ self.features = nn.Sequential(
29
+ nn.Conv2d(
30
+ in_size,
31
+ out_channels=16,
32
+ kernel_size=3,
33
+ padding="SAME",
34
+ ),
35
+ nn.ReLU(),
36
+ nn.Conv2d.desc(
37
+ out_channels=32,
38
+ kernel_size=3,
39
+ stride=2,
40
+ padding="SAME",
41
+ ),
42
+ nn.ReLU(),
43
+ nn.Conv2d.desc(
44
+ out_channels=64,
45
+ kernel_size=3,
46
+ padding="SAME",
47
+ ),
48
+ nn.ReLU(),
49
+ nn.MaxPool2d.desc(
50
+ kernel_size=(2, 2),
51
+ stride=(2, 2),
52
+ channel_axis=-1,
53
+ ),
54
+ )
55
+ self.classifier = nn.Sequential(
56
+ nn.Flatten(in_size=self.features.out_size),
57
+ nn.Linear.desc(out_size=256),
58
+ nn.ReLU(),
59
+ nn.Linear.desc(out_size=10),
60
+ )
61
+
62
+ def update(self, x):
63
+ return self.classifier(self.features(x))
64
+
65
+
66
+ brainstate.random.seed(42)
67
+ net = ComplexNet(in_size=(32, 32, 3))
68
+ x_image = brainstate.random.randn(2, 32, 32, 3)
69
+ y_image = net(x_image)
70
+
71
+ assert net.features.out_size == (8, 8, 64)
72
+ assert net.classifier.layers[0].out_size == (4096,)
73
+ assert net.classifier.out_size == (10,)
74
+ assert y_image.shape == (2, 10)
75
+ ```
76
+
77
+ ## Convolution output-size behavior
78
+
79
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/03_common_layers.html
80
+
81
+ The tutorial's **Convolution Parameters** rules are:
82
+
83
+ - `stride` controls the step size; pass it with the `stride` keyword. The API no longer accepts `strides`.
84
+ - `'SAME'` preserves spatial dimensions when stride is 1; `'VALID'` performs no padding.
85
+ - Explicit tuples set different values per spatial dimension.
86
+
87
+ The following source pattern bundles those rules with the exact demonstrated 28-by-28, 3-by-3-kernel outcomes:
88
+
89
+ ```python
90
+ import brainstate
91
+
92
+ x = brainstate.random.randn(1, 28, 28, 3)
93
+
94
+ configs = [
95
+ {"stride": (1, 1), "padding": "SAME", "name": "Stride 1, SAME"},
96
+ {"stride": (2, 2), "padding": "SAME", "name": "Stride 2, SAME"},
97
+ {"stride": (1, 1), "padding": "VALID", "name": "Stride 1, VALID"},
98
+ ]
99
+
100
+ for config in configs:
101
+ brainstate.random.seed(0)
102
+ conv = brainstate.nn.Conv2d(
103
+ in_size=(28, 28, 3),
104
+ out_channels=16,
105
+ kernel_size=(3, 3),
106
+ stride=config["stride"],
107
+ padding=config["padding"],
108
+ )
109
+ y = conv(x)
110
+ print(f"{config['name']:20s}: out_size={conv.out_size}, runtime={y.shape}")
111
+ ```
112
+
113
+ Expected output:
114
+
115
+ ```text
116
+ Stride 1, SAME : out_size=(28, 28, 16), runtime=(1, 28, 28, 16)
117
+ Stride 2, SAME : out_size=(14, 14, 16), runtime=(1, 14, 14, 16)
118
+ Stride 1, VALID : out_size=(26, 26, 16), runtime=(1, 26, 26, 16)
119
+ ```
120
+
121
+ These are the tutorial's exact cases: `'SAME'` with stride 2 produces 14 by 14 from this 28-by-28 input, while `'VALID'` with stride 1 and a 3-by-3 kernel produces 26 by 26. Use `stride`, not `strides`.
122
+
123
+ ### Dimensionality and layout variations
124
+
125
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/03_common_layers.html
126
+
127
+ The tutorial demonstrates channels-last layouts for each convolution rank:
128
+
129
+ | Layer | Runtime input layout | Demonstrated input | Demonstrated output |
130
+ |---|---|---|---|
131
+ | `Conv1d` | `(batch, length, channels)` | `(4, 100, 3)` | `(4, 100, 16)` |
132
+ | `Conv2d` | `(batch, height, width, channels)` | `(8, 28, 28, 3)` | `(8, 28, 28, 32)` |
133
+ | `Conv3d` | `(batch, depth, height, width, channels)` | `(2, 16, 64, 64, 3)` | `(2, 16, 64, 64, 16)` |
134
+
135
+ Each case uses `'SAME'` padding and the default stride of 1:
136
+
137
+ ```python
138
+ import brainstate
139
+
140
+ brainstate.random.seed(0)
141
+
142
+ conv1d = brainstate.nn.Conv1d(
143
+ in_size=(100, 3),
144
+ out_channels=16,
145
+ kernel_size=3,
146
+ padding="SAME",
147
+ )
148
+ conv2d = brainstate.nn.Conv2d(
149
+ in_size=(28, 28, 3),
150
+ out_channels=32,
151
+ kernel_size=(3, 3),
152
+ stride=(1, 1),
153
+ padding="SAME",
154
+ )
155
+ conv3d = brainstate.nn.Conv3d(
156
+ in_size=(16, 64, 64, 3),
157
+ out_channels=16,
158
+ kernel_size=(3, 3, 3),
159
+ padding="SAME",
160
+ )
161
+
162
+ print(conv1d(brainstate.random.randn(4, 100, 3)).shape)
163
+ print(conv2d(brainstate.random.randn(8, 28, 28, 3)).shape)
164
+ print(conv3d(brainstate.random.randn(2, 16, 64, 64, 3)).shape)
165
+ ```
166
+
167
+ ## Pooling reductions and fixed targets
168
+
169
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/03_common_layers.html
170
+
171
+ Official source phrase: "Pooling layers downsample feature maps, reducing spatial dimensions." `MaxPool2d` takes the maximum value in each window; `AvgPool2d` takes the average. With a 2-by-2 kernel and stride 2, both demonstrated layers reduce 28 by 28 to 14 by 14 and retain all 16 channels:
172
+
173
+ ```python
174
+ import brainstate
175
+
176
+ x = brainstate.random.randn(4, 28, 28, 16)
177
+ maxpool = brainstate.nn.MaxPool2d(
178
+ kernel_size=(2, 2),
179
+ stride=(2, 2),
180
+ )
181
+ avgpool = brainstate.nn.AvgPool2d(
182
+ kernel_size=(2, 2),
183
+ stride=(2, 2),
184
+ )
185
+
186
+ print(maxpool(x).shape) # (4, 14, 14, 16)
187
+ print(avgpool(x).shape) # (4, 14, 14, 16)
188
+ ```
189
+
190
+ The printed layer representations in the tutorial show `padding=VALID` and `channel_axis=-1` for both constructors.
191
+
192
+ Use `AdaptiveAvgPool2d` when the required spatial result is fixed rather than tied to one input resolution. The tutorial's `target_size=(7, 7)` example maps all three inputs to 7 by 7:
193
+
194
+ ```python
195
+ adaptive_pool = brainstate.nn.AdaptiveAvgPool2d(target_size=(7, 7))
196
+
197
+ inputs = [
198
+ brainstate.random.randn(1, 28, 28, 16),
199
+ brainstate.random.randn(1, 56, 56, 16),
200
+ brainstate.random.randn(1, 224, 224, 16),
201
+ ]
202
+
203
+ for x in inputs:
204
+ y = adaptive_pool(x)
205
+ print(f"Input {x.shape[1:3]} -> Output {y.shape[1:3]}")
206
+ ```
207
+
208
+ Expected output:
209
+
210
+ ```text
211
+ Input (28, 28) -> Output (7, 7)
212
+ Input (56, 56) -> Output (7, 7)
213
+ Input (224, 224) -> Output (7, 7)
214
+ ```
215
+
216
+ ### Pooling with constructor-visible size metadata
217
+
218
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/03_common_layers.html
219
+
220
+ The standalone pooling examples omit `in_size` and demonstrate reduction through runtime shapes. In the tutorial's complete CNN, the final pool instead receives the preceding convolution's size so the following `Flatten` can be constructed from its result:
221
+
222
+ ```python
223
+ conv3 = brainstate.nn.Conv2d(
224
+ (8, 8, 64),
225
+ out_channels=128,
226
+ kernel_size=(3, 3),
227
+ padding="SAME",
228
+ )
229
+ pool3 = brainstate.nn.MaxPool2d(
230
+ kernel_size=(2, 2),
231
+ stride=(2, 2),
232
+ in_size=conv3.out_size,
233
+ )
234
+
235
+ print(conv3.out_size) # (8, 8, 128)
236
+ print(pool3.out_size) # (4, 4, 128)
237
+ ```
238
+
239
+ ## Flatten: runtime axes versus constructor inference
240
+
241
+ Source URL: https://brainx.chaobrain.com/brainstate/tutorials/core/03_common_layers.html
242
+
243
+ The standalone tutorial pattern flattens a batched tensor from `start_axis=1`, preserving its leading batch axis:
244
+
245
+ ```python
246
+ import brainstate
247
+
248
+ flatten_runtime = brainstate.nn.Flatten(start_axis=1)
249
+ x_conv = brainstate.random.randn(4, 7, 7, 64)
250
+ x_flat = flatten_runtime(x_conv)
251
+
252
+ print(x_conv.shape) # (4, 7, 7, 64)
253
+ print(x_flat.shape) # (4, 3136)
254
+ ```
255
+
256
+ The exact flattened feature count is `7 * 7 * 64 = 3136` per sample. The tutorial summary identifies `start_axis` and `end_axis` as the key `Flatten` parameters.
257
+
258
+ For constructor-aware composition, the complete CNN passes the final pool's result to `Flatten`. Its printed representation shows `start_axis=0`, `end_axis=-1`, and `out_size=(2048,)` for the feature shape `(4, 4, 128)`. Continue from the `conv3` / `pool3` construction above:
259
+
260
+ ```python
261
+ import jax.numpy as jnp
262
+
263
+ flatten = brainstate.nn.Flatten(in_size=pool3.out_size)
264
+ fc1 = brainstate.nn.Linear(4 * 4 * 128, (256,))
265
+
266
+ x = brainstate.random.randn(2, 8, 8, 64)
267
+ x = conv3(x)
268
+ x = jnp.maximum(0, x)
269
+ x = pool3(x)
270
+ x = flatten(x)
271
+ y = fc1(x)
272
+
273
+ print(flatten.in_size) # (4, 4, 128)
274
+ print(flatten.out_size) # (2048,)
275
+ print(x.shape) # (2, 2048)
276
+ print(y.shape) # (2, 256)
277
+ ```
278
+
279
+ This is the source's manual-composition variation: spatial feature shapes progress from `(8, 8, 128)` through `(4, 4, 128)` to `(2048,)`, and the first dense layer accepts 2048 features. Use it when explicit construction is clearer than descriptor-based composition.
@@ -0,0 +1,216 @@
1
+ # BrainState state-graph operations
2
+
3
+ Use this reference after the core `State`, `Module`, and transform rules in
4
+ `SKILL.md`. It covers the less-frequent graph operations needed to find,
5
+ extract, split, replace, or reconstruct state while retaining BrainState's
6
+ graph structure. All examples assume an existing graph node named `model`.
7
+
8
+ The graph engine flattens object graphs of `Node`s and `State`s into "a static
9
+ structure plus a dynamic state mapping, and back." A `GraphDef` is the static
10
+ structure. Graph nodes are hoisted into an index-keyed table, so sharing and
11
+ cycles are encoded by integer index rather than duplicated.
12
+
13
+ Source URL:
14
+ https://brainx.chaobrain.com/brainstate/apis/graph.html
15
+
16
+ ## Selection map
17
+
18
+ | Need | Use | Key constraint |
19
+ |---|---|---|
20
+ | Inspect graph paths and live objects | `iter_node()`, `iter_leaf()`, `nodes()`, or `states()` | Filters select by path and value without changing graph structure. |
21
+ | Extract State as a PyTree | `treefy_states()` | No `GraphDef` is returned, so this path alone cannot reconstruct the graph. |
22
+ | Partition State and reconstruct later | `treefy_split()` plus `treefy_merge()` | Preserve the returned `GraphDef` and every matching partition. |
23
+ | Produce the low-level graph representation | `flatten()` plus `unflatten()` | The pair preserves sharing and cycles through graph indices. |
24
+ | Update State values in an existing graph | `update_states()` | This replaces values, not graph nodes. |
25
+ | Remove matching State objects | `pop_states()` | This is destructive. |
26
+ | Move graph nodes through a larger PyTree | `graph_to_tree()` plus `tree_to_graph()` | Preserve each `NodeStates` wrapper. |
27
+
28
+ ## Find nodes, leaves, and states
29
+
30
+ Use traversal when the path is part of the decision. `iter_node()` yields
31
+ `(path, graph_node)` for every graph node; `iter_leaf()` yields `(path, value)`
32
+ for every leaf. The root node appears at path `()`.
33
+
34
+ ```python
35
+ for path, node in brainstate.graph.iter_node(model):
36
+ print(path, type(node).__name__)
37
+
38
+ for path, leaf in brainstate.graph.iter_leaf(model):
39
+ print(path, type(leaf).__name__)
40
+ ```
41
+
42
+ Use collection when the result should be a path-keyed mapping. `nodes()`
43
+ collects graph nodes as `FlattedDict` object(s); `states()` collects
44
+ `State` objects as `FlattedDict` object(s). Both accept optional filters.
45
+
46
+ ```python
47
+ all_nodes = brainstate.graph.nodes(model)
48
+ all_states = brainstate.graph.states(model)
49
+ param_states = brainstate.graph.states(model, brainstate.ParamState)
50
+ params, remaining = brainstate.graph.states(
51
+ model,
52
+ brainstate.ParamState,
53
+ ...,
54
+ )
55
+ ```
56
+
57
+ A predicate filter has the exact shape below. `path` is a tuple of hashable,
58
+ comparable keys and `value` is the value at that path.
59
+
60
+ ```python
61
+ def weight_path(path: tuple, value) -> bool:
62
+ return path[-1:] == ("weight",)
63
+
64
+ weight_states = brainstate.graph.states(model, weight_path)
65
+ ```
66
+
67
+ The filter DSL also accepts:
68
+
69
+ - `...` or `True`: match every value.
70
+ - `None` or `False`: match no values.
71
+ - A type: match instances of that type, or values whose `type` attribute is
72
+ that type.
73
+ - A string: match a value whose string `tag` attribute equals that string.
74
+ - A tuple or list of filters: match any enclosed filter.
75
+
76
+ Source URL:
77
+ https://brainx.chaobrain.com/brainstate/how_to/inspect_and_edit_state_graph.html
78
+
79
+ ## Extract state objects or state pytrees
80
+
81
+ Choose the extraction API by the representation required downstream:
82
+
83
+ - `states()` returns the graph's `State` objects, keyed by path.
84
+ - `treefy_states()` returns one or more treeified state mappings and no
85
+ `GraphDef`. It is the lightweight extraction for optimization or
86
+ checkpointing when reconstruction is not required.
87
+ - `pop_states()` removes and returns matching `State` objects. It is
88
+ destructive and deduplicates matches by identity.
89
+
90
+ ```python
91
+ # State objects keyed by their graph paths.
92
+ live_params = brainstate.graph.states(model, brainstate.ParamState)
93
+
94
+ # PyTree-compatible state data without carrying graph structure.
95
+ param_tree = brainstate.graph.treefy_states(model, brainstate.ParamState)
96
+ param_tree, other_tree = brainstate.graph.treefy_states(
97
+ model,
98
+ brainstate.ParamState,
99
+ ...,
100
+ )
101
+
102
+ # Destructive extraction: matching State instances are removed from model.
103
+ removed_params = brainstate.graph.pop_states(model, brainstate.ParamState)
104
+ ```
105
+
106
+ `treefy_states()` returns state trees keyed by state paths. Do not use it alone
107
+ when another process must rebuild the module; use `treefy_split()` and retain
108
+ the returned `GraphDef` instead.
109
+
110
+ Source URLs:
111
+ https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
112
+ https://brainx.chaobrain.com/brainstate/apis/graph.html
113
+
114
+ ## Split structure from state
115
+
116
+ `treefy_split()` returns `(graph_def, state_tree1, state_tree2, ...)`. Each
117
+ filter adds one state mapping in the same order; `...` is the catch-all used for
118
+ remaining states. Use this operation when reconstruction or explicit JAX state
119
+ threading requires both structure and dynamic values.
120
+
121
+ ```python
122
+ graph_def, params, other_states = brainstate.graph.treefy_split(
123
+ model,
124
+ brainstate.ParamState,
125
+ ...,
126
+ )
127
+ ```
128
+
129
+ When no partition is needed, the operation returns one state mapping:
130
+
131
+ ```python
132
+ graph_def, all_state = brainstate.graph.treefy_split(model)
133
+ ```
134
+
135
+ If only the static structure is needed, retrieve it directly:
136
+
137
+ ```python
138
+ graph_def = brainstate.graph.graphdef(model)
139
+ ```
140
+
141
+ Source URLs:
142
+ https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
143
+ https://brainx.chaobrain.com/brainstate/how_to/inspect_and_edit_state_graph.html
144
+
145
+ ## Replace state values in place
146
+
147
+ `update_states()` updates a graph node in place from one or more state mappings.
148
+ Extract the desired subset, produce a replacement mapping with the same paths,
149
+ then apply it. The documented JAX workflow maps arithmetic over the treeified
150
+ state data; the same representation can be written back with `update_states()`.
151
+
152
+ ```python
153
+ import jax
154
+ import jax.numpy as jnp
155
+
156
+ params = brainstate.graph.treefy_states(model, brainstate.ParamState)
157
+ replacement_params = jax.tree.map(jnp.zeros_like, params)
158
+ brainstate.graph.update_states(model, replacement_params)
159
+ ```
160
+
161
+ Multiple independently partitioned mappings may be applied together:
162
+
163
+ ```python
164
+ brainstate.graph.update_states(model, replacement_params, replacement_counts)
165
+ ```
166
+
167
+ This is state-value replacement, not structural replacement. `pop_states()`
168
+ removes matching states; `update_states()` updates states already located by
169
+ the supplied mapping. The assigned official pages do not document a generic
170
+ graph-node replacement API.
171
+
172
+ Source URLs:
173
+ https://brainx.chaobrain.com/brainstate/apis/graph.html
174
+ https://brainx.chaobrain.com/brainstate/how_to/inspect_and_edit_state_graph.html
175
+
176
+ ## Reconstruct the graph
177
+
178
+ Use `treefy_merge()` with the `GraphDef` and every state mapping returned by
179
+ the corresponding `treefy_split()` call. It reconstructs a new graph node;
180
+ the state mappings must be supplied in the compatible partitioning.
181
+
182
+ ```python
183
+ rebuilt_model = brainstate.graph.treefy_merge(
184
+ graph_def,
185
+ params,
186
+ other_states,
187
+ )
188
+ ```
189
+
190
+ For the lower-level, unpartitioned representation, `flatten()` returns a
191
+ `(GraphDef, NestedDict)` pair and `unflatten()` reconstructs from that pair.
192
+ The decoder materializes states, creates node shells, then fills them, so graph
193
+ sharing and cycles resolve independently of fill order.
194
+
195
+ ```python
196
+ flat_graph_def, nested_state = brainstate.graph.flatten(model)
197
+ rebuilt_model = brainstate.graph.unflatten(flat_graph_def, nested_state)
198
+ ```
199
+
200
+ For graph nodes nested inside a larger pytree, `graph_to_tree()` converts the
201
+ container to a pure pytree and `tree_to_graph()` converts a pytree of
202
+ `NodeStates` back into graph nodes. `NodeStates` is the JAX pytree wrapper that
203
+ carries a `GraphDef` and one or more state mappings.
204
+
205
+ ```python
206
+ tree_form = brainstate.graph.graph_to_tree(container_with_graph_nodes)
207
+ restored_container = brainstate.graph.tree_to_graph(tree_form)
208
+ ```
209
+
210
+ Use `split_context` and `merge_context` only when splitting or merging multiple
211
+ graph nodes that share a reference index; those context managers preserve the
212
+ shared index across the related operations. For a deep copy of one graph,
213
+ `clone()` performs split/merge while preserving shared references.
214
+
215
+ Source URL:
216
+ https://brainx.chaobrain.com/brainstate/apis/graph.html