brainx-skill 1.0.10 → 1.0.12

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 (62) hide show
  1. package/README.md +6 -0
  2. package/adapters/antigravity.js +8 -0
  3. package/installation/lib/installer.js +60 -20
  4. package/installation/lib/paths.js +41 -3
  5. package/installation/lib/prompts.js +13 -7
  6. package/manifest.json +2 -1
  7. package/package.json +3 -2
  8. package/skills/braincell/SKILL.md +1 -1
  9. package/skills/braincell/references/mixions-for-adaptation.md +26 -3
  10. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +113 -53
  11. package/skills/brainevent/references/synaptic-plasticity.md +74 -230
  12. package/skills/brainmass/SKILL.md +11 -6
  13. package/skills/brainmass/references/batch-transform-acceleration.md +44 -3
  14. package/skills/brainmass/references/modellibrary.md +11 -0
  15. package/skills/brainmass/references/simulator-input-monitor-api.md +98 -0
  16. package/skills/brainpy-state/SKILL.md +20 -6
  17. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +52 -1
  18. package/skills/brainpy-state/references/brainPy(legacy)/analysis.md +150 -0
  19. package/skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +373 -0
  20. package/skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +150 -0
  21. package/skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +175 -0
  22. package/skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +286 -0
  23. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +111 -0
  24. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +163 -0
  25. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +113 -0
  26. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +136 -0
  27. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +222 -0
  28. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +123 -0
  29. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +107 -0
  30. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +185 -0
  31. package/skills/brainpy-state/references/brainPy(legacy)/integrators.md +181 -0
  32. package/skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +102 -0
  33. package/skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +147 -0
  34. package/skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +159 -0
  35. package/skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +127 -0
  36. package/skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +167 -0
  37. package/skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +107 -0
  38. package/skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +186 -0
  39. package/skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +104 -0
  40. package/skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +89 -0
  41. package/skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +253 -0
  42. package/skills/brainpy-state/references/braintools/connectivity.md +206 -0
  43. package/skills/brainpy-state/references/braintools/input-current.md +199 -0
  44. package/skills/brainpy-state/references/component-selection.md +20 -5
  45. package/skills/brainpy-state/references/projection-patterns.md +2 -0
  46. package/skills/brainpy-state/references/scripts/sound_localization.py +240 -0
  47. package/skills/brainstate/SKILL.md +1 -1
  48. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +8 -0
  49. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +57 -7
  50. package/skills/brainstate/references/collective_model_operations.md +26 -27
  51. package/skills/braintrace/SKILL.md +161 -0
  52. package/skills/braintrace/references/Drtrl.md +179 -0
  53. package/skills/braintrace/references/ETP operators.md +161 -0
  54. package/skills/braintrace/references/algorithm selection.md +120 -0
  55. package/skills/braintrace/references/batching.md +150 -0
  56. package/skills/braintrace/references/compiler_internal.md +162 -0
  57. package/skills/braintrace/references/custom ETP primitives.md +200 -0
  58. package/skills/braintrace/references/custom algorithms.md +206 -0
  59. package/skills/braintrace/references/customizing_primitive_transforms.md +191 -0
  60. package/skills/braintrace/references/pp_pprop workflow.md +196 -0
  61. package/skills/braintrace/references/pre-built-braintrace-layer.md +149 -0
  62. package/skills/brainx-general-guard/SKILL.md +64 -21
@@ -2,273 +2,106 @@
2
2
 
3
3
  Use this reference when binary pre- or postsynaptic events must modify stored synaptic weights. Plasticity is an overlay on the core `BinaryArray @ connectivity` workflow, not a prerequisite for ordinary event-driven communication.
4
4
 
5
- BrainEvent's event-driven plasticity operators touch only weights connected to neurons that fired, following the same event-sparsity principle as its matrix products.
5
+ BrainEvent's event-driven plasticity operators touch only weights connected to neurons that fired. Keep persistent weights and temporal traces in BrainState State so the complete online update can run inside State-aware transforms.
6
6
 
7
7
  ## Choose the update operator
8
8
 
9
9
  | Weight storage | Presynaptic event triggers update | Postsynaptic event triggers update | Use when |
10
10
  |---|---|---|---|
11
- | CSR | `update_csr_on_binary_pre()` | `update_csr_on_binary_post()` | Connectivity is sparse and fixed; only stored synapses should be visited |
12
- | Dense | `update_dense_on_binary_pre()` | `update_dense_on_binary_post()` | A small fully connected layer already uses a dense weight matrix |
11
+ | CSR | `update_csr_on_binary_pre()` | `update_csr_on_binary_post()` | Connectivity is sparse and fixed; only stored synapses should be visited. |
12
+ | Dense | `update_dense_on_binary_pre()` | `update_dense_on_binary_post()` | A small fully connected layer already uses a dense weight matrix. |
13
13
 
14
- Use the `*_on_binary_pre` direction when the source neuron firing triggers the rule. Use the `*_on_binary_post` direction when the target neuron firing triggers it.
14
+ Use the `*_on_binary_pre` direction when the source neuron firing triggers the rule. Use the `*_on_binary_post` direction when the target neuron firing triggers it. For a bidirectional STDP rule, apply both directions with the traces and signs defined by that rule; do not substitute one trigger direction for the other.
15
15
 
16
- ## Canonical CSR STDP overlay
16
+ ## Run online plasticity through State
17
17
 
18
- The official tutorial maintains exponentially decaying pre/post traces, applies a spike-triggered update to the CSR `data`, and rebuilds the CSR object while preserving its structural arrays.
18
+ Each timestep reads event arrays, advances trace State, and writes persistent weight State; lower that complete ordered update through `for_loop` and compile it with BrainState `jit`.
19
19
 
20
- ```python
21
- import brainevent
22
- import brainstate
23
- import jax.numpy as jnp
24
- import numpy as np
25
-
26
- n_pre = 100
27
- n_post = 50
28
- connection_probability = 0.1
29
-
30
- # Create explicit sparse weights and convert their COO indices to CSR.
31
- brainstate.random.seed(42)
32
- mask = brainstate.random.bernoulli(
33
- connection_probability,
34
- size=(n_pre, n_post),
35
- )
36
- weights_dense = (
37
- brainstate.random.uniform(0.0, 0.5, size=(n_pre, n_post))
38
- * mask
39
- )
40
- row, col = jnp.where(weights_dense != 0)
41
- data = weights_dense[row, col]
42
- indptr, indices, order = brainevent.coo2csr(
43
- row,
44
- col,
45
- shape=(n_pre, n_post),
46
- )
47
- csr_weights = brainevent.CSR(
48
- (data[order], indices, indptr),
49
- shape=(n_pre, n_post),
50
- )
51
-
52
- # Initialize traces and the official presynaptic-triggered STDP parameters.
53
- pre_trace = jnp.zeros(n_pre)
54
- post_trace = jnp.zeros(n_post)
55
- decay_pre = np.exp(-1.0 / 20.0)
56
- decay_post = np.exp(-1.0 / 20.0)
57
- A_plus = 0.005
58
- initial_mean = csr_weights.data.mean()
59
-
60
- brainstate.random.seed(100)
61
- for _ in range(500):
62
- pre_spike = brainstate.random.bernoulli(0.05, size=(n_pre,))
63
- post_spike = brainstate.random.bernoulli(0.05, size=(n_post,))
64
-
65
- pre_trace = (
66
- pre_trace * decay_pre
67
- + pre_spike.astype(jnp.float32)
68
- )
69
- post_trace = (
70
- post_trace * decay_post
71
- + post_spike.astype(jnp.float32)
72
- )
73
-
74
- new_data = brainevent.update_csr_on_binary_pre(
75
- weight=csr_weights.data,
76
- indices=csr_weights.indices,
77
- indptr=csr_weights.indptr,
78
- pre_spike=pre_spike,
79
- post_trace=post_trace * A_plus,
80
- w_min=0.0,
81
- w_max=1.0,
82
- shape=csr_weights.shape,
83
- )
84
- csr_weights = brainevent.CSR(
85
- (new_data, csr_weights.indices, csr_weights.indptr),
86
- shape=csr_weights.shape,
87
- )
88
-
89
- print("connections:", csr_weights.nse)
90
- print("initial mean weight:", initial_mean)
91
- print("final mean weight:", csr_weights.data.mean())
92
- print(
93
- "final range:",
94
- csr_weights.data.min(),
95
- csr_weights.data.max(),
96
- )
97
- ```
98
-
99
- This mirrors the official sparse-network construction and learning loop while using only the presynaptic CSR update API. Preserve `indices`, `indptr`, and `shape`; the operator updates weight values, not the sparse topology.
100
-
101
- For a bidirectional STDP rule, combine the corresponding pre- and post-triggered operators with the appropriate traces and signs from the learning rule. Do not silently substitute the pre-triggered operator for a post-triggered update.
102
-
103
- ## Application: adaptive two-layer spiking network
104
-
105
- The official self-learning practice stores two CSR layers, propagates binary events through both, maintains decaying traces, and applies presynaptic-triggered updates after each sample.
20
+ | API | Description |
21
+ |---|---|
22
+ | `brainstate.LongTermState(weight)` | Use for learned weights that must persist across trial resets and later rollouts; assign the update result through `.value`. |
23
+ | `brainstate.ShortTermState(trace)` | Use for decaying pre- or postsynaptic traces that belong to one sequence; reset them at every independent sequence boundary. |
24
+ | `update_csr_on_binary_pre(...)` | Use when active presynaptic rows update stored CSR data from a postsynaptic trace; it returns new data with the same shape and optionally clips it to `w_min` and `w_max`. |
25
+ | `brainstate.transform.for_loop(step, *events)` | Use for the ordered event sequence; it slices the leading time axis and preserves State effects between steps. |
26
+ | `brainstate.transform.jit(run)` | Use around the complete online sequence so State discovery and write-back remain transform-aware. |
106
27
 
107
28
  ```python
108
29
  import brainevent
109
30
  import brainstate
31
+ import brainunit as u
110
32
  import jax.numpy as jnp
111
- import numpy as np
112
-
113
-
114
- def dense_to_csr(weights):
115
- row, col = jnp.where(weights != 0)
116
- data = weights[row, col]
117
- indptr, indices, order = brainevent.coo2csr(
118
- row,
119
- col,
120
- shape=weights.shape,
121
- )
122
- return brainevent.CSR(
123
- (data[order], indices, indptr),
124
- shape=weights.shape,
125
- )
126
-
127
33
 
128
- class AdaptiveSpikingNetwork:
129
- def __init__(
130
- self,
131
- n_input,
132
- n_hidden,
133
- n_output,
134
- connection_probability=0.15,
135
- seed=0,
136
- ):
137
- self.n_input = n_input
138
- self.n_hidden = n_hidden
139
- self.n_output = n_output
140
34
 
141
- brainstate.random.seed(seed)
142
- mask1 = brainstate.random.bernoulli(
143
- connection_probability,
144
- size=(n_input, n_hidden),
35
+ class PlasticCSR(brainstate.nn.Module):
36
+ def __init__(self):
37
+ super().__init__()
38
+ self.shape = (3, 2)
39
+ self.indices = jnp.array([0, 1, 0, 1, 0, 1], dtype=jnp.int32)
40
+ self.indptr = jnp.array([0, 2, 4, 6], dtype=jnp.int32)
41
+ self.weight = brainstate.LongTermState(
42
+ jnp.full(6, 0.2, dtype=jnp.float32)
145
43
  )
146
- weights1 = (
147
- brainstate.random.uniform(
148
- 0.0,
149
- 0.3,
150
- size=(n_input, n_hidden),
151
- )
152
- * mask1
44
+ self.post_trace = brainstate.ShortTermState(
45
+ jnp.zeros(2, dtype=jnp.float32)
153
46
  )
154
- self.w1 = dense_to_csr(weights1)
155
47
 
156
- mask2 = brainstate.random.bernoulli(
157
- connection_probability,
158
- size=(n_hidden, n_output),
48
+ def update(self, pre_spike, post_spike):
49
+ decay = u.math.exp(-brainstate.environ.get_dt() / (20.0 * u.ms))
50
+ self.post_trace.value = (
51
+ self.post_trace.value * decay
52
+ + post_spike.astype(jnp.float32)
159
53
  )
160
- weights2 = (
161
- brainstate.random.uniform(
162
- 0.0,
163
- 0.3,
164
- size=(n_hidden, n_output),
165
- )
166
- * mask2
54
+ self.weight.value = brainevent.update_csr_on_binary_pre(
55
+ weight=self.weight.value,
56
+ indices=self.indices,
57
+ indptr=self.indptr,
58
+ pre_spike=pre_spike,
59
+ post_trace=self.post_trace.value * 0.01,
60
+ w_min=0.0,
61
+ w_max=1.0,
62
+ shape=self.shape,
167
63
  )
168
- self.w2 = dense_to_csr(weights2)
64
+ return self.weight.value
169
65
 
170
- self.input_trace = jnp.zeros(n_input)
171
- self.hidden_trace = jnp.zeros(n_hidden)
172
- self.output_trace = jnp.zeros(n_output)
173
- self.decay = np.exp(-1.0 / 20.0)
174
- self.learning_rate = 0.008
175
-
176
- def forward(self, input_spikes, learning=True):
177
- hidden_input = input_spikes @ self.w1
178
- hidden_spikes = brainevent.BinaryArray(hidden_input > 0.5)
179
- output_input = hidden_spikes @ self.w2
180
- output_spikes = brainevent.BinaryArray(output_input > 0.8)
181
-
182
- input_events = input_spikes.value
183
- hidden_events = hidden_spikes.value
184
- output_events = output_spikes.value
185
- self.input_trace = (
186
- self.input_trace * self.decay
187
- + input_events.astype(jnp.float32)
188
- )
189
- self.hidden_trace = (
190
- self.hidden_trace * self.decay
191
- + hidden_events.astype(jnp.float32)
192
- )
193
- self.output_trace = (
194
- self.output_trace * self.decay
195
- + output_events.astype(jnp.float32)
196
- )
197
66
 
198
- if learning:
199
- new_w1 = brainevent.update_csr_on_binary_pre(
200
- weight=self.w1.data,
201
- indices=self.w1.indices,
202
- indptr=self.w1.indptr,
203
- pre_spike=input_events,
204
- post_trace=self.hidden_trace * self.learning_rate,
205
- w_min=0.0,
206
- w_max=1.0,
207
- shape=self.w1.shape,
208
- )
209
- self.w1 = brainevent.CSR(
210
- (new_w1, self.w1.indices, self.w1.indptr),
211
- shape=self.w1.shape,
212
- )
67
+ pre_events = jnp.array(
68
+ [[False, False, False], [True, False, False], [False, True, False]]
69
+ )
70
+ post_events = jnp.array(
71
+ [[True, False], [False, False], [False, True]]
72
+ )
213
73
 
214
- new_w2 = brainevent.update_csr_on_binary_pre(
215
- weight=self.w2.data,
216
- indices=self.w2.indices,
217
- indptr=self.w2.indptr,
218
- pre_spike=hidden_events,
219
- post_trace=self.output_trace * self.learning_rate,
220
- w_min=0.0,
221
- w_max=1.0,
222
- shape=self.w2.shape,
223
- )
224
- self.w2 = brainevent.CSR(
225
- (new_w2, self.w2.indices, self.w2.indptr),
226
- shape=self.w2.shape,
227
- )
74
+ with brainstate.environ.context(dt=1.0 * u.ms):
75
+ rule = PlasticCSR()
228
76
 
229
- return output_input, hidden_spikes, output_spikes
77
+ @brainstate.transform.jit
78
+ def learn():
79
+ return brainstate.transform.for_loop(
80
+ rule.update,
81
+ pre_events,
82
+ post_events,
83
+ )
230
84
 
85
+ weight_history = learn()
231
86
 
232
- network = AdaptiveSpikingNetwork(
233
- n_input=200,
234
- n_hidden=100,
235
- n_output=10,
236
- connection_probability=0.12,
237
- seed=2024,
87
+ learned = brainevent.CSR(
88
+ (rule.weight.value, rule.indices, rule.indptr),
89
+ shape=rule.shape,
238
90
  )
239
- initial_w1 = network.w1.data.mean()
240
- initial_w2 = network.w2.data.mean()
241
- activity = []
91
+ drive = brainevent.BinaryArray(jnp.array([True, False, False])) @ learned
242
92
 
243
- brainstate.random.seed(0)
244
- for _ in range(50):
245
- epoch_output_count = 0
246
- for _ in range(20):
247
- input_spikes = brainevent.BinaryArray(
248
- brainstate.random.bernoulli(0.1, size=(200,))
249
- )
250
- output, _, output_spikes = network.forward(
251
- input_spikes,
252
- learning=True,
253
- )
254
- epoch_output_count += int(jnp.sum(output_spikes.value))
255
- activity.append(epoch_output_count / 20)
256
-
257
- assert output.shape == (10,)
258
- assert network.w1.data.mean() >= initial_w1
259
- assert network.w2.data.mean() >= initial_w2
260
- print("W1 mean:", initial_w1, "->", network.w1.data.mean())
261
- print("W2 mean:", initial_w2, "->", network.w2.data.mean())
262
- print("final output activity:", activity[-1])
93
+ assert weight_history.shape == (3, 6)
94
+ assert drive.shape == (2,)
263
95
  ```
264
96
 
265
- This adapts “Practice: Building a Self-Learning Neural Network,” replaces manual CSR row assembly with `coo2csr()`, and removes visualization-only history. It demonstrates the tutorial’s potentiation path; add the post-triggered operator when the learning rule also requires depression.
97
+ Preserve `indices`, `indptr`, and `shape`; the operator updates stored weight values, not sparse topology. When trials are independent except for learned weights, keep `weight` sequential but reset `post_trace`, neural State, delays, and other per-trial State at every trial boundary; a silent interval is not a reset. If mapped lanes learn independently, give each lane separate weight and trace State. Do not `vmap` sequential trials when trial N+1 must consume weights learned in trial N.
266
98
 
267
99
  ## Storage boundary
268
100
 
269
101
  - Prefer CSR plasticity for large sparse networks with fixed connectivity.
270
102
  - Prefer dense plasticity for small fully connected layers already represented densely.
271
103
  - Do not choose JITC when individual connection weights must be persistently updated; use stored CSR or dense weights.
104
+ - Keep dimensionless efficacy weights dimensionless until a named synaptic or current boundary scales them into a physical quantity.
272
105
 
273
106
  ## Exact API routing
274
107
 
@@ -279,6 +112,17 @@ Open the Matrix Operations API for exact signatures and associated primitives:
279
112
 
280
113
  API: https://brainx.chaobrain.com/brainevent/reference/apis/operations.html
281
114
 
115
+ Open the official Synaptic Plasticity tutorial when choosing trace equations, update signs, or a bidirectional learning rule. The BrainEvent operator applies the supplied update; it does not choose the scientific learning rule.
116
+
117
+ ## Common failures
118
+
119
+ - Storing learned weights or traces in ordinary attributes while a transformed timestep mutates them.
120
+ - Running timesteps in a Python loop instead of one State-aware transformed sequence.
121
+ - Resetting persistent learned weights together with per-sequence traces.
122
+ - Updating CSR data while changing or discarding `indices`, `indptr`, or `shape`.
123
+ - Using a presynaptic-triggered operator for a postsynaptic-triggered term.
124
+ - Interpreting a potentiation-only example as a complete STDP rule.
125
+
282
126
  ## Sources
283
127
 
284
128
  - Tutorial 5: Synaptic Plasticity Modeling - Foundation of Learning and Memory: https://brainx.chaobrain.com/brainevent/tutorials/data-structures/05_synaptic_plasticity.html
@@ -44,8 +44,8 @@ Every public regional model follows the same `*Step` contract, so choose by scie
44
44
  |---|---|
45
45
  | `brainmass.list_models()` | Use before choosing a model; it returns `ModelInfo` records with name, category, state-variable count, and use case. |
46
46
  | `brainmass.<Model>Step(in_size, **params)` | Use after selecting a model family; `in_size` sets the number of regions or parallel units and parameters broadcast to that shape. |
47
- | `brainmass.Simulator(model, dt=...)` | Use for the default, standard run path; it stores the model and integration step without changing the model equations. |
48
- | `Simulator.run(duration, ..., monitors=..., transient=...)` | Use to initialize State, execute the compiled loop, discard a warm-up interval, and return a dict of time-major trajectories plus unit-aware `ts`. |
47
+ | `brainmass.Simulator(model, dt=...)` | Use for the default run path; it stores the model and integration step without changing the model equations. |
48
+ | `Simulator.run(duration, *, inputs=None, monitors=None, transient=None, sample_every=None, batch_size=None, init_states=True, jit=True)` | Use to drive and observe the model through the standard runner; it initializes State by default, executes the complete State-aware loop with JIT by default, applies transient removal and post-update sampling, and returns time-major trajectories plus unit-aware `ts`. |
49
49
 
50
50
  ```python
51
51
  import brainmass
@@ -67,11 +67,13 @@ assert result["x"].shape == (1800, 1)
67
67
  assert result["ts"].shape == (1800,)
68
68
  ```
69
69
 
70
- Open `references/modellibrary.md` when choosing among model families, distinguishing similarly named Wong-Wang variants, comparing state cost, or locating a model's observable. Open `references/datasets-api.md` when the workflow needs bundled or registered input data.
70
+ Use `Simulator` before constructing an environment context or transformed loop yourself. Open `references/simulator-input-monitor-api.md` when supplying driven inputs, defining callable or named monitors, controlling initialization/JIT, sampling outputs, or separating model and trial axes. Open `references/batch-transform-acceleration.md` only when `Simulator` cannot express the workflow or a benchmark requires one stable explicit compilation boundary.
71
71
 
72
- ## Noise and stochastic run
72
+ Open `references/modellibrary.md` when choosing among model families, distinguishing similarly named Wong-Wang variants or decision rules, comparing state cost, or locating a model's observable. Open `references/datasets-api.md` when the workflow needs bundled or registered input data.
73
73
 
74
- Noise belongs to the model, while `batch_size` asks `Simulator` to initialize and run independent State realizations in one time-major result.
74
+ ## Noise and stochastic run
75
+
76
+ Noise belongs to the model. Use `in_size` for each realization's region or decision-unit shape and `batch_size` for independent State realizations; stochastic output is ordered `(time, batch, in_size...)`.
75
77
 
76
78
  | API | Description |
77
79
  |---|---|
@@ -106,7 +108,9 @@ assert trials["x"].shape == (1000, 8, 1)
106
108
 
107
109
  Seed again before a repeated run when exact replay matters.
108
110
 
109
- Open `references/noiseprocesses.md` when choosing white, OU, Brownian, or colored noise, using a noise process directly, or checking units and State behavior. Open `references/batch-transform-acceleration.md` when batching parameters, writing a custom transformed loop, or checkpointing a long differentiated rollout.
111
+ Do not flatten experimental conditions and stochastic trials into `in_size` unless a required external layout or numerical baseline demands it.
112
+
113
+ Open `references/noiseprocesses.md` when choosing white, OU, Brownian, or colored noise, using a noise process directly, or checking units and State behavior. Open `references/simulator-input-monitor-api.md` when batching stochastic trials or driving multiple conditions. Open `references/batch-transform-acceleration.md` when batching parameters, writing a custom transformed loop that `Simulator` cannot express, or checkpointing a long differentiated rollout.
110
114
 
111
115
  ## Build a delay-coupled network
112
116
 
@@ -256,6 +260,7 @@ Choose the workflow category first, then open only the smallest reference that o
256
260
  | Reference | Open when |
257
261
  |---|---|
258
262
  | `references/modellibrary.md` | Choosing a model family, observable, state cost, or similarly named variant. |
263
+ | `references/simulator-input-monitor-api.md` | Supplying model inputs, selecting monitor forms, sampling, controlling initialization/JIT, or separating model and trial axes. |
259
264
  | `references/noiseprocesses.md` | Selecting a noise spectrum, correlation structure, State behavior, units, or direct noise workflow. |
260
265
  | `references/datasets-api.md` | Loading, inspecting, generating, or registering BrainMass data containers. |
261
266
  | `references/coupling-network-api.md` | Selecting or configuring coupling, delays, connectivity conventions, direct coupling objects, or trainable network parameters. |
@@ -115,9 +115,49 @@ Keep the same body signature and result structure when switching. Validate both
115
115
 
116
116
  ## Benchmark correctly
117
117
 
118
- - Warm up the exact function and shape once before timing.
119
- - Call `jax.block_until_ready(result)` before stopping the timer because JAX dispatch is asynchronous.
120
- - Compare steady-state compiled runs separately from first-call compilation.
118
+ Define the step once, define the full rollout once, and transform that rollout once outside every timed call. The first call measures compilation plus execution; later compatible calls to the same callable measure steady execution.
119
+
120
+ ```python
121
+ import time
122
+
123
+ import brainmass
124
+ import brainstate
125
+ import brainunit as u
126
+ import jax
127
+ import jax.numpy as jnp
128
+
129
+ dt = 0.1 * u.ms
130
+ node = brainmass.HopfStep(in_size=64, a=0.25, w=0.3)
131
+ brainstate.nn.init_all_states(node)
132
+ steps = jnp.arange(300)
133
+
134
+ def step(index):
135
+ with brainstate.environ.context(i=index, t=index * dt):
136
+ node.update()
137
+ return node.x.value
138
+
139
+ def rollout():
140
+ with brainstate.environ.context(dt=dt):
141
+ return brainstate.transform.for_loop(step, steps)
142
+
143
+ run_once = brainstate.transform.jit(rollout)
144
+
145
+ start = time.perf_counter()
146
+ first_result = run_once()
147
+ jax.block_until_ready(first_result)
148
+ first_call_seconds = time.perf_counter() - start
149
+
150
+ steady_seconds = []
151
+ for _ in range(5):
152
+ start = time.perf_counter()
153
+ result = run_once()
154
+ jax.block_until_ready(result)
155
+ steady_seconds.append(time.perf_counter() - start)
156
+ ```
157
+
158
+ - Warm up the exact callable and shape once before reporting steady timing; report the first call separately when compilation cost matters.
159
+ - Block every timed result before stopping the timer because JAX dispatch is asynchronous.
160
+ - Restore the same initial State outside the timed region, or include the same reset inside every measured callable, when comparisons require identical starting conditions.
121
161
  - Batch enough work to occupy an accelerator; one small neural-mass node may run faster on CPU.
122
162
  - Keep `dt`, duration, shape, dtype, and monitor set identical across comparisons.
123
163
 
@@ -128,6 +168,7 @@ Keep the same body signature and result structure when switching. Validate both
128
168
  - `scan` used when no explicit carry exists.
129
169
  - A model constructed outside a parameter-mapped function and mutated across mapped values.
130
170
  - Variable-shape or Python-object results returned from transformed loop bodies.
171
+ - A step or rollout function reconstructed inside each timed repetition.
131
172
  - JAX timing measured without warmup or `block_until_ready`.
132
173
  - Checkpointing enabled before memory pressure is established.
133
174
 
@@ -74,6 +74,17 @@ assert result["output"].shape == (3000, 8)
74
74
 
75
75
  Use `JansenRitTR` only when its internal substep-to-TR behavior is explicitly required. Instantiate concrete model classes rather than shared bases such as `XY_Oscillator` or `WilsonCowanThreePopBase`.
76
76
 
77
+ ## Choose Wong-Wang decision semantics
78
+
79
+ Choose the decision rule from the scientific definition; thresholded firing-rate decisions and final gating dominance are not equivalent.
80
+
81
+ | API | Description |
82
+ |---|---|
83
+ | `WongWangStep.get_decision(threshold=15 * u.Hz)` | Use when a firing-rate threshold defines commitment; it returns `1`, `-1`, or `0` for population 1, population 2, or undecided. |
84
+ | `(model.S1.value - model.S2.value) > 0` | Use when final gating dominance intentionally forces every trial into a binary choice; keep it as explicit model-analysis logic. |
85
+
86
+ Do not replace one rule with the other without updating probability denominators, uncertainty calculations, and handling of undecided trials.
87
+
77
88
  ## Application scripts
78
89
 
79
90
  Open only the script that matches the selected model or scientific regime.
@@ -0,0 +1,98 @@
1
+ # Simulator input and monitor API
2
+
3
+ Use this reference when a BrainMass run needs driven inputs, custom observables, sampling, independent trials, or explicit initialization and JIT controls; use `batch-transform-acceleration.md` only when this runner cannot express the workflow.
4
+
5
+ ## Use the standard runner
6
+
7
+ `Simulator` owns the normal initialization, environment, transformed time loop, monitoring, transient, and sampling lifecycle.
8
+
9
+ | API | Description |
10
+ |---|---|
11
+ | `brainmass.Simulator(model, dt=...)` | Use to bind a model or `Network` to an integration step for the standard run path. |
12
+ | `Simulator.run(duration, *, inputs=None, monitors=None, transient=None, sample_every=None, batch_size=None, init_states=True, jit=True)` | Use to execute a duration and return a dict of time-major monitored values plus unit-aware `ts`. It initializes State and JIT-compiles by default. |
13
+
14
+ Do not manually derive the number of steps, initialize State, scope `dt`, build a transformed loop, downsample, or reconstruct timestamps when these controls express the run.
15
+
16
+ ## Supply model inputs
17
+
18
+ Choose the input form from how `model.update()` receives its arguments.
19
+
20
+ | `inputs` form | Behavior |
21
+ |---|---|
22
+ | `None` | Call `model.update()` without arguments. |
23
+ | Array shaped `(n_steps, ...)` | Slice the leading time axis and pass each row as one update argument. |
24
+ | Callable `(i, t)` returning one value | Evaluate it each step and pass the result as one update argument. |
25
+ | Callable `(i, t)` returning a tuple | Evaluate it each step and splat the tuple into positional update arguments. |
26
+
27
+ Use a callable for a constant vector drive. Passing that vector directly makes `Simulator` interpret its leading axis as time.
28
+
29
+ ## Select monitors
30
+
31
+ Monitors record values after each model update.
32
+
33
+ | `monitors` form | Result |
34
+ |---|---|
35
+ | `None` | Store the return from `model.update()` under `"output"`. |
36
+ | List of State names | Store each named State under its own key. |
37
+ | Callable accepting the model | Store the returned observable under `"output"`. |
38
+ | Dict from output names to State names or callables | Store each selected State or derived observable under its dict key. |
39
+
40
+ `transient` discards a leading duration or step count. `sample_every=k` keeps every `k`th post-update sample and applies the same selection to `ts`.
41
+
42
+ ## Run driven conditions as independent trials
43
+
44
+ Keep the scientific condition axis in `in_size` and the stochastic realization axis in `batch_size`.
45
+
46
+ ```python
47
+ import brainmass
48
+ import brainstate
49
+ import brainunit as u
50
+ import jax.numpy as jnp
51
+
52
+ brainstate.random.seed(7)
53
+ evidence = jnp.asarray([-0.2, 0.0, 0.2])
54
+ model = brainmass.WongWangStep(
55
+ in_size=evidence.size,
56
+ noise_s1=brainmass.GaussianNoise(evidence.size, sigma=0.02 * u.nA),
57
+ noise_s2=brainmass.GaussianNoise(evidence.size, sigma=0.02 * u.nA),
58
+ )
59
+ result = brainmass.Simulator(model, dt=0.1 * u.ms).run(
60
+ 2.0 * u.ms,
61
+ inputs=lambda _i, _t: evidence,
62
+ monitors={"decision_variable": lambda m: m.S1.value - m.S2.value},
63
+ sample_every=5,
64
+ batch_size=4,
65
+ )
66
+
67
+ assert result["decision_variable"].shape == (4, 4, 3)
68
+ assert model.S1.value.shape == (4, 3)
69
+ assert u.math.allclose(
70
+ result["ts"],
71
+ jnp.asarray([0.1, 0.6, 1.1, 1.6]) * u.ms,
72
+ )
73
+ ```
74
+
75
+ The result layout is `(sampled_time, trial, evidence)`. Transpose or remove units only at an explicit analysis or serialization boundary.
76
+
77
+ ## Override lifecycle controls only deliberately
78
+
79
+ | Control | Use when |
80
+ |---|---|
81
+ | `init_states=False` | Continuing intentionally from existing model State; otherwise keep the default reset. |
82
+ | `jit=False` | Debugging transformed execution or isolating compilation behavior; otherwise keep JIT enabled. |
83
+ | `batch_size=N` | Initializing and running `N` independent model and noise State realizations. |
84
+
85
+ Use a custom BrainState rollout only when required inputs, monitors, State effects, explicit carry, checkpointing, or a stable benchmark boundary cannot be represented here.
86
+
87
+ ## Common failures
88
+
89
+ - Passing a constant condition vector as an array and unintentionally treating it as time-major input.
90
+ - Flattening conditions and trials into `in_size` even though `batch_size` represents independent realizations.
91
+ - Reconstructing time from `dt` instead of using the sampled, unit-aware `ts` result.
92
+ - Disabling initialization or JIT without a continuation, debugging, or benchmarking requirement.
93
+ - Rebuilding the runner with `environ.context()` and `for_loop` for a workflow already covered by `Simulator.run()`.
94
+
95
+ ## Official sources
96
+
97
+ - `https://brainx.chaobrain.com/brainmass/reference/orchestration.html`
98
+ - `https://brainx.chaobrain.com/brainmass/reference/generated/brainmass.Simulator.html`