brainx-skill 1.0.11 → 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 (27) hide show
  1. package/package.json +1 -1
  2. package/skills/braincell/SKILL.md +1 -15
  3. package/skills/braincell/references/mixions-for-adaptation.md +26 -3
  4. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +113 -53
  5. package/skills/brainevent/SKILL.md +0 -1
  6. package/skills/brainevent/references/synaptic-plasticity.md +74 -230
  7. package/skills/brainmass/SKILL.md +10 -5
  8. package/skills/brainmass/references/batch-transform-acceleration.md +44 -3
  9. package/skills/brainmass/references/modellibrary.md +11 -0
  10. package/skills/brainmass/references/simulator-input-monitor-api.md +98 -0
  11. package/skills/brainpy-state/SKILL.md +14 -6
  12. package/skills/brainpy-state/references/array-creation.md +2 -2
  13. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +52 -1
  14. package/skills/brainpy-state/references/braintools/connectivity.md +206 -0
  15. package/skills/brainpy-state/references/braintools/input-current.md +199 -0
  16. package/skills/brainpy-state/references/component-selection.md +20 -5
  17. package/skills/brainpy-state/references/projection-patterns.md +2 -0
  18. package/skills/brainpy-state/references/scripts/sound_localization.py +240 -0
  19. package/skills/brainstate/SKILL.md +11 -15
  20. package/skills/brainstate/agents/openai.yaml +4 -0
  21. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +8 -0
  22. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +1 -1
  23. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +57 -7
  24. package/skills/brainstate/references/collective_model_operations.md +26 -27
  25. package/skills/brainx-general-guard/SKILL.md +62 -37
  26. package/skills/brainx-install/SKILL.md +21 -24
  27. package/skills/brainstate/references/braintools/optimizer.md +0 -179
@@ -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
+
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.
71
73
 
72
74
  ## Noise and stochastic run
73
75
 
74
- Noise belongs to the model, while `batch_size` asks `Simulator` to initialize and run independent State realizations in one time-major result.
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`
@@ -35,11 +35,12 @@ Align synaptic State to a neuron dimension instead of each connection, reduce th
35
35
 
36
36
  ### 1. Choose and run neuron dynamics
37
37
 
38
- A neuron call advances one `dt`, mutates its registered dynamical State, and exposes the current spike through `get_spike()`; initialize before every independent rollout and lower the complete time loop through `brainstate.transform`.
38
+ A neuron call advances one `dt`, mutates its registered dynamical State, and exposes the current spike through `get_spike()`; initialize before every independent rollout, set `V_initializer` whenever startup voltage affects the result, and lower the complete time loop through `brainstate.transform`.
39
39
 
40
40
  | API | Description |
41
41
  |---|---|
42
- | `brainpy.state.LIFRef(...)` | Use for the canonical point-neuron rollout when leak and refractory timing are required; each call integrates one `dt`, updates membrane/refractory State, and returns the current spike. |
42
+ | `brainpy.state.LIFRef(..., V_initializer=...)` | Use for the canonical point-neuron rollout when leak and refractory timing are required; each call integrates one `dt`, updates membrane/refractory State, and returns the current spike. `V_rest` sets the resting dynamics but does not set the initial membrane State, so pass an intentional initializer when startup spikes or transients matter. |
43
+ | `braintools.init.Constant(value)` | Use as `V_initializer` when every neuron must start at one known voltage; initialization creates membrane State at that value. Use a documented distribution instead when initial heterogeneity is part of the model. |
43
44
  | `brainstate.nn.init_all_states(model, batch_size=...)` | Use after construction and before a rollout; it allocates or resets dynamical State across the Module graph and adds a leading batch dimension when `batch_size` is given. |
44
45
  | `brainstate.environ.context(dt=..., t=...)` | Use around the rollout for `dt` and inside the step for `t`; dynamics read the active values and the context restores previous settings on exit. |
45
46
  | `brainstate.environ.get_dt()` | Use when constructing the time axis or a numerical update from the active simulation step; it returns `dt` and raises when no value is set. |
@@ -50,6 +51,7 @@ A neuron call advances one `dt`, mutates its registered dynamical State, and exp
50
51
  ```python
51
52
  import brainpy
52
53
  import brainstate
54
+ import braintools
53
55
  import brainunit as u
54
56
 
55
57
  with brainstate.environ.context(dt=0.1 * u.ms):
@@ -61,6 +63,7 @@ with brainstate.environ.context(dt=0.1 * u.ms):
61
63
  V_th=-50.0 * u.mV,
62
64
  V_reset=-60.0 * u.mV,
63
65
  tau_ref=5.0 * u.ms,
66
+ V_initializer=braintools.init.Constant(-60.0 * u.mV),
64
67
  )
65
68
  brainstate.nn.init_all_states(neuron)
66
69
  times = u.math.arange(
@@ -80,11 +83,11 @@ assert voltages.shape == (2000, 1)
80
83
  assert spikes.shape == (2000, 1)
81
84
  ```
82
85
 
83
- Open `references/array-creation.md` when constructing specialized unit-aware current ranges, grids, filled arrays, template-shaped arrays, or matrix patterns. Open `references/component-selection.md` when choosing among documented neuron, input, synapse, output, plasticity, or readout variants, for the decision boundary and complete category list. Open `references/braintools/brainstate-control-flow-patterns.md` when the rollout needs explicit carry, branching, or checkpointed control flow.
86
+ Open `references/braintools/input-current.md` when a direct current protocol needs timed sections, pulses, waveforms, stochastic processes, or composition. Generate the complete time-major protocol once under the rollout `dt` and pass it as an input to `for_loop`; do not rebuild named sections or pulses from time predicates inside the model step. Open `references/array-creation.md` when constructing specialized unit-aware current ranges, grids, filled arrays, template-shaped arrays, or matrix patterns. Open `references/component-selection.md` when choosing among documented neuron, input, synapse, output, plasticity, or readout variants, for the decision boundary and complete category list. Open `references/braintools/brainstate-control-flow-patterns.md` when the rollout needs explicit carry, branching, or checkpointed control flow.
84
87
 
85
88
  ### 2. Compose synapses and projections
86
89
 
87
- A projection deposits current into `post` before the postsynaptic neuron integrates the step, while its alignment determines which neuron dimension owns synaptic State and which kinetics remain exact.
90
+ A projection deposits current into `post` before the postsynaptic neuron integrates the step, while its alignment determines which neuron dimension owns synaptic State and which kinetics remain exact; when recurrent excitation, mutual inhibition, or spike-driven connectivity is a point-neuron mechanism, represent it with explicit projections instead of a hand-written population-rate feedback `State`, and route aggregate rate coupling to BrainMass.
88
91
 
89
92
  | API | Description |
90
93
  |---|---|
@@ -98,6 +101,7 @@ A projection deposits current into `post` before the postsynaptic neuron integra
98
101
  ```python
99
102
  import brainpy
100
103
  import brainstate
104
+ import braintools
101
105
  import brainunit as u
102
106
 
103
107
 
@@ -111,6 +115,7 @@ class TwoPop(brainstate.nn.Module):
111
115
  V_rest=-60.0 * u.mV,
112
116
  V_th=-50.0 * u.mV,
113
117
  V_reset=-60.0 * u.mV,
118
+ V_initializer=braintools.init.Constant(-60.0 * u.mV),
114
119
  )
115
120
  self.post = brainpy.state.LIFRef(
116
121
  n_post,
@@ -119,6 +124,7 @@ class TwoPop(brainstate.nn.Module):
119
124
  V_rest=-60.0 * u.mV,
120
125
  V_th=-50.0 * u.mV,
121
126
  V_reset=-60.0 * u.mV,
127
+ V_initializer=braintools.init.Constant(-60.0 * u.mV),
122
128
  )
123
129
  self.proj = brainpy.state.AlignPostProj(
124
130
  comm=brainstate.nn.EventFixedProb(
@@ -154,7 +160,7 @@ assert post_voltage.shape == (2000, 10)
154
160
  assert conductance.shape == (2000, 10)
155
161
  ```
156
162
 
157
- Open `references/projection-patterns.md` when selecting AlignPre versus either AlignPost API, adding short-term plasticity or delays, using direct/delta input, or composing electrical coupling. Open `skills/brainevent/references/scripts/coba_ei_teaching.py` when a BrainPy network should use BrainEvent for efficient event-driven communication; it keeps BrainPy neuron and synapse dynamics while replacing the communication step with `BinaryArray @ connectivity` over fixed-degree, CSR, or dense storage.
163
+ Open `references/braintools/connectivity.md` first when geometry, distance, degree, modules, or another named topology determines which neuron pairs connect; generate the topology before choosing its BrainEvent representation. Open `references/projection-patterns.md` before implementing recurrent excitation, mutual inhibition, or other spike-driven connectivity; it owns AlignPre versus AlignPost, communication, delays, direct/delta input, short-term plasticity, and electrical coupling. Open `skills/brainevent/references/scripts/coba_ei_teaching.py` when a BrainPy network should use BrainEvent for efficient event-driven communication; it keeps BrainPy neuron and synapse dynamics while replacing the communication step with `BinaryArray @ connectivity` over fixed-degree, CSR, or dense storage.
158
164
 
159
165
  ### 3. Train a spiking network
160
166
 
@@ -218,6 +224,8 @@ Open only the smallest reference that owns the decision.
218
224
  | Reference | Open when |
219
225
  |---|---|
220
226
  | `references/array-creation.md` | Constructing specialized unit-aware current ranges, grids, filled arrays, template-shaped arrays, or matrix patterns |
227
+ | `references/braintools/connectivity.md` | Selecting spatial, topological, biological E/I, kernel, or compartment-aware connection pairs and exporting a `ConnectionResult` to BrainEvent storage |
228
+ | `references/braintools/input-current.md` | Generating or composing direct unit-aware current sections, pulses, waveforms, or stochastic processes |
221
229
  | `references/component-selection.md` | Choosing a neuron, synapse, synaptic output, plasticity model, input generator, or readout from the documented native API families |
222
230
  | `references/projection-patterns.md` | Choosing projection alignment or API form, adding delays or short-term plasticity, using direct/delta projections, or adding gap junctions |
223
231
  | `references/nest-compatible/nest-workflow.md` | Using NEST/PyNEST model names, `Simulator`, devices, connection rules, spatial networks, parity, porting, or the bundled NEST-compatible full scripts |
@@ -227,12 +235,12 @@ Open only the smallest reference that owns the decision.
227
235
 
228
236
 
229
237
  ## Application script examples
230
-
231
238
  | Reference | Open when |
232
239
  |---|---|
233
240
  | `references/scripts/103_COBA_2005.py` | Needing a complete canonical E/I COBA network built from native BrainPy-State projections |
234
241
  | `references/scripts/106_COBA_HH_2007.py` | Reproducing a conductance-based E/I network with a custom Hodgkin-Huxley neuron |
235
242
  | `references/scripts/107_gamma_oscillation_1996.py` | Reproducing gamma oscillations with custom neuron and synapse dynamics |
236
243
  | `references/scripts/109_fast_global_oscillation.py` | Needing a complete `DeltaProj` network with delayed recurrent input |
244
+ | `references/scripts/sound_localization.py` | Needing a mapped delay-line coincidence network with heterogeneous integer event taps and BrainEvent fixed fan-out |
237
245
  | `references/scripts/201_surrogate_grad_lif_fashion_mnist.py` | Needing a complete real-data surrogate-gradient LIF training workflow |
238
246
  | `references/scripts/training-snn.py` | Needing a complete runnable surrogate-gradient SNN training workflow |
@@ -143,9 +143,9 @@ import jax.numpy as jnp
143
143
 
144
144
  ## Routing
145
145
 
146
- `array_split()` appears on the tutorial page, but it is a structural operation; route it to `skills/brainunit/references/array-mechanics.md`.
146
+ `array_split()` appears on the tutorial page, but it is a structural operation; route it to `array-mechanics.md`.
147
147
 
148
- Backend extraction and `as_numpy()` belong in `skills/brainunit/references/array-mechanics.md` because they cross an existing array boundary rather than create a scientific quantity from source values.
148
+ Backend extraction and `as_numpy()` belong in `array-mechanics.md` because they cross an existing array boundary rather than create a scientific quantity from source values.
149
149
 
150
150
  ## Cross-family gotchas
151
151
 
@@ -84,9 +84,60 @@ Keep the projection-before-post order. The delayed signal must be communicated b
84
84
 
85
85
  Do not validate a delay only from postsynaptic spike time. Membrane integration, thresholding, refractory State, and other inputs can shift or suppress the postsynaptic spike even when the transmission delay is correct.
86
86
 
87
+ ## Use a manual BrainState delay
88
+
89
+ Insert the current sample before retrieval so step 0 always means current and step `d` means exactly `d` completed updates earlier.
90
+
91
+ | API | Description |
92
+ |---|---|
93
+ | `brainstate.nn.Delay(target_info, max_time)` | Use when model logic needs an explicit reusable history buffer rather than a projection-owned delay; it allocates enough history for `max_time` under the initialization `dt`. |
94
+ | `delay.update(value)` | Insert the current sample once per step before any retrieval that should include the updated history. |
95
+ | `delay.retrieve_at_step(step)` | Retrieve an integer-offset sample; after the current update, step 0 is `value` and step `d` is the value from `d` updates earlier. |
96
+ | `delay.retrieve_at_time(time)` | Retrieve by a unit-bearing time when the model is defined in physical time; select the documented interpolation behavior rather than manually rounding an off-grid delay. |
97
+ | `delay.register_entry(name, vector_delays, indices)` and `delay.at(name)` | Use for one named heterogeneous tap per selected source element; register before State initialization, then retrieve the selected delayed values after each update. |
98
+
99
+ ```python
100
+ import brainstate
101
+ import brainunit as u
102
+ import jax
103
+ import jax.numpy as jnp
104
+
105
+ with brainstate.environ.context(dt=1.0 * u.ms):
106
+ delay = brainstate.nn.Delay(
107
+ jax.ShapeDtypeStruct((), jnp.float32),
108
+ 3.0 * u.ms,
109
+ )
110
+ brainstate.nn.init_all_states(delay)
111
+ impulse = jnp.array([1.0, 0.0, 0.0, 0.0, 0.0])
112
+
113
+ def step(value):
114
+ delay.update(value)
115
+ return delay.retrieve_at_step(jnp.asarray(3, dtype=jnp.int32))
116
+
117
+ delayed = brainstate.transform.for_loop(step, impulse)
118
+
119
+ assert jnp.array_equal(delayed, jnp.array([0.0, 0.0, 0.0, 1.0, 0.0]))
120
+ ```
121
+
122
+ If retrieval occurs before `update(value)`, the buffer still represents the previous completed step and the index for the same observed latency changes by one. Do not compensate with an unexplained `d - 1`; choose one call order, document it beside the step, and lock the convention with an impulse assertion before interpreting neural output.
123
+
124
+ Reinitialize the delay for every independent rollout. A silent input interval advances the buffer but does not establish an independent State lifecycle.
125
+
126
+ For grid-aligned binary spikes, retrieve exact integer steps or use named entries whose delays are integer multiples of `dt`. Linear time interpolation can produce fractional numeric values, which no longer satisfy binary-event semantics. Use continuous interpolation only when the modeled signal and off-grid timing require it.
127
+
128
+ When a unit-bearing event time feeds an integer delay bank, convert `time / dt` to one documented integer step before the rollout and generate the event on that grid. Do not rediscover its step inside the time loop with a half-open `abs(t - arrival) < dt / 2` window; exact half-step results can depend on floating representation.
129
+
130
+ ## Map delay State across independent conditions
131
+
132
+ Keep every writable part of a delay on one compatible mapped axis. A ring buffer whose history is per lane but whose mutable write pointer remains scalar cannot be shared across a mapped step, even when every lane advances in lockstep.
133
+
134
+ Prefer `brainstate.nn.Delay` when its complete mutable State can be initialized and mapped per condition. If its bookkeeping cannot satisfy the State-axis policy, use a small pointer-free `HiddenState` shift register only for a fixed integer delay bank; keep step 0 as the current event and prove at least one nonzero tap with an impulse assertion. Do not generalize this fallback to long histories because shifting the full buffer costs work proportional to the maximum delay.
135
+
136
+ Open `references/scripts/sound_localization.py` when building a mapped multi-tap coincidence detector, for the verified pointer-free fallback, semantic State filters, integer event taps, and impulse check.
137
+
87
138
  ## General BrainState boundary
88
139
 
89
- Open the official BrainState [Delay Protocol](https://brainx.chaobrain.com/brainstate/tutorials/brain_dynamics/02_synaptic_delays.html) when implementing `brainstate.nn.Delay`, `brainstate.nn.DelayAccess`, `brainstate.nn.StateWithDelay`, rotation versus concatenation buffers, named entries, manual `update(value)`, `retrieve_at_step`, `retrieve_at_time`, or linear-versus-round interpolation. Those mechanisms are more general than BrainPy projection delays and should not be reconstructed inside a projection unless the projection APIs cannot express the required history.
140
+ Open the official BrainState [Delay Protocol](https://brainx.chaobrain.com/brainstate/tutorials/brain_dynamics/02_synaptic_delays.html) when implementing `brainstate.nn.DelayAccess`, `brainstate.nn.StateWithDelay`, rotation versus concatenation buffers, named entries, multiple taps, or linear-versus-round interpolation. Those mechanisms are more general than BrainPy projection delays and should not be reconstructed inside a projection unless the projection APIs cannot express the required history.
90
141
 
91
142
  ## Official sources
92
143
 
@@ -0,0 +1,206 @@
1
+ # Braintools connectivity
2
+
3
+ Use this reference to choose and construct point-neuron or
4
+ multi-compartment connection patterns. It covers which pairs exist, their
5
+ indices, optional weights and delays, spatial structure, topology, and
6
+ compartment targeting. Use `braintools.init.DistanceModulated` only when an
7
+ existing connection's weight should be scaled by distance.
8
+
9
+ ## Choose a connectivity family
10
+
11
+ | Family | Use when | Representative choice |
12
+ |---|---|---|
13
+ | Basic point-neuron | Connection probability or deterministic pairing is enough | `Random`, `AllToAll`, or `OneToOne` |
14
+ | Spatial point-neuron | Positions or spatial neighborhoods determine connection probability | `DistanceDependent`, `Gaussian`, `Ring`, or `Grid2d` |
15
+ | Topological | Degree, clustering, modularity, hierarchy, or core/periphery structure matters | `SmallWorld`, `ScaleFree`, `ModularRandom`, or `HierarchicalRandom` |
16
+ | Biological E/I | Presynaptic sign must follow Dale's principle | `ExcitatoryInhibitory` |
17
+ | Kernel based | Receptive-field geometry should follow an image-like kernel | `GaussianKernel`, `GaborKernel`, or `DoGKernel` |
18
+ | Multi-compartment | Synapses must target soma, axon, or dendritic compartments | `CompartmentSpecific` or an anatomical targeting subclass |
19
+
20
+ ## Construction and results
21
+
22
+ Every connectivity object is a reusable pattern. Call it with population sizes
23
+ and any required positions or morphology metadata to obtain a
24
+ `ConnectionResult`.
25
+
26
+ | API | Description |
27
+ |---|---|
28
+ | `Connectivity(pre_size=None, post_size=None, seed=None)` | Subclass for a new general pattern. Implement `generate(...)`; use `weight_scale(factor)` or `delay_scale(factor)` to wrap a pattern. |
29
+ | `PointConnectivity` | Subclass for a new single-compartment pattern. |
30
+ | `MultiCompartmentConnectivity` | Subclass for a new morphology-aware pattern. |
31
+ | `ScaledConnectivity` | Returned when weights or delays are scaled. |
32
+ | `CompositeConnectivity` | Use when combining several connectivity patterns. |
33
+ | `ConnectionResult(pre_indices, post_indices, pre_size, post_size, ..., weights=None, delays=None, model_type='point', metadata=None)` | Inspect the generated edge list and optional annotations. `shape` is `(pre_size, post_size)` and `n_connections` is the number of edges. |
34
+ | `ConnectionResult.weight2dense()` / `weight2csr()` | Convert weights to a dense or CSR connectivity matrix. |
35
+ | `ConnectionResult.delay2matrix()` / `delay2csr()` | Convert delays to a dense or CSR connectivity matrix. |
36
+ | `ConnectionResult.get_distances()` | Compute distances for connected pairs when positions are available. |
37
+
38
+ ```python
39
+ import brainunit as u
40
+ from braintools.conn import ExcitatoryInhibitory
41
+
42
+ pattern = ExcitatoryInhibitory(
43
+ exc_ratio=0.8,
44
+ exc_prob=0.1,
45
+ inh_prob=0.2,
46
+ exc_weight=1.0 * u.nS,
47
+ inh_weight=-0.8 * u.nS,
48
+ )
49
+ result = pattern(pre_size=1000, post_size=1000)
50
+
51
+ assert result.shape == (1000, 1000)
52
+ assert result.pre_indices.shape == result.post_indices.shape
53
+ assert result.weights.shape[0] == result.n_connections
54
+ ```
55
+
56
+ **Invariant:** a `ConnectionResult` edge is identified by matching entries in
57
+ `pre_indices` and `post_indices`. Keep any weights and delays aligned with that
58
+ edge order when converting or filtering.
59
+
60
+ ## Basic and spatial point-neuron patterns
61
+
62
+ | API | Description |
63
+ |---|---|
64
+ | `Random(prob, allow_self_connections=False, weight=None, delay=None, **kwargs)` | Use for independent fixed-probability edges. Supply initializer objects or values for optional weights and delays. |
65
+ | `FixedProb(...)` | Use only as the alias for `Random`. |
66
+ | `AllToAll(...)` | Connect every allowed presynaptic/postsynaptic pair. |
67
+ | `OneToOne(...)` | Connect neuron `i` to neuron `i`; use only when the population indexing is aligned. |
68
+ | `DistanceDependent(distance_profile, weight=None, delay=None, allow_self_connections=False, **kwargs)` | Use when a `braintools.init.DistanceProfile` should determine connection probability from positions or precomputed distances. |
69
+ | `Gaussian(...)` | Use for Gaussian distance-dependent connection probability. |
70
+ | `Exponential(...)` | Use for exponentially decaying connection probability. |
71
+ | `Ring(...)` | Use for neurons arranged on a circular topology. |
72
+ | `Grid2d(connectivity='von_neumann', weight=None, delay=None, periodic=False, **kwargs)` | Use for immediate four-neighbor (`'von_neumann'`) or eight-neighbor (`'moore'`) connections on matching two-dimensional pre/post grids. Set `periodic=True` only for wraparound boundaries. |
73
+ | `RadialPatches(...)` | Use for several localized spatial connection patches. |
74
+ | `ClusteredRandom(...)` | Use for random connectivity enhanced within spatial clusters. |
75
+
76
+ ```python
77
+ import brainunit as u
78
+ import numpy as np
79
+ from braintools.conn import DistanceDependent
80
+ from braintools.init import GaussianProfile, LogNormal
81
+
82
+ positions = np.random.default_rng(0).uniform(0, 1000, (500, 2)) * u.um
83
+ pattern = DistanceDependent(
84
+ GaussianProfile(sigma=100 * u.um, max_distance=300 * u.um),
85
+ weight=LogNormal(mean=1.0 * u.nS, std=0.5 * u.nS),
86
+ )
87
+ result = pattern(500, 500, positions, positions)
88
+ ```
89
+
90
+ `DistanceDependent` consumes the profile's connection probability and samples
91
+ which pairs exist. In contrast, `braintools.init.DistanceModulated` multiplies
92
+ every supplied base weight by a profile value and never removes an edge.
93
+
94
+ ## Export a `ConnectionResult` to BrainEvent CSR
95
+
96
+ Choose topology with BrainTools before choosing BrainEvent storage. Convert the
97
+ result's coordinate edge list to CSR when binary presynaptic events should drive
98
+ event-based communication.
99
+
100
+ | API | Description |
101
+ |---|---|
102
+ | `brainevent.coo2csr(row_ids, col_ids, *, shape)` | Convert `pre_indices` and `post_indices` to row-compressed structure; it returns `(indptr, indices, order)`, where `order` is the required edge-value permutation. |
103
+ | `brainevent.CSR((data, indices, indptr), shape=...)` | Store the reordered weights with presynaptic rows and postsynaptic columns for `BinaryArray @ CSR`. |
104
+ | `brainevent.BinaryArray(spikes) @ connectivity` | Communicate active presynaptic events and return one accumulated value per postsynaptic index. |
105
+
106
+ ```python
107
+ import brainevent
108
+ import brainunit as u
109
+ from braintools.conn import Grid2d
110
+ from braintools.init import Constant
111
+
112
+ pattern = Grid2d(
113
+ connectivity="von_neumann",
114
+ weight=Constant(1.0 * u.nS),
115
+ periodic=False,
116
+ )
117
+ result = pattern(pre_size=(10, 10), post_size=(10, 10))
118
+
119
+ indptr, indices, order = brainevent.coo2csr(
120
+ result.pre_indices,
121
+ result.post_indices,
122
+ shape=result.shape,
123
+ )
124
+ connectivity = brainevent.CSR(
125
+ (result.weights[order], indices, indptr),
126
+ shape=result.shape,
127
+ )
128
+ postsynaptic_input = brainevent.BinaryArray(
129
+ u.math.zeros(result.shape[0], dtype=bool)
130
+ ) @ connectivity
131
+
132
+ assert postsynaptic_input.shape == (result.shape[1],)
133
+ ```
134
+
135
+ Keep `result.weights[order]`: `coo2csr()` sorts edges by row and returns the
136
+ matching value permutation separately. If the topology has no generated
137
+ weights, supply an intentional scalar or edge-aligned weight array before
138
+ constructing `CSR`.
139
+
140
+ Open `skills/brainevent/references/sparse-formats.md` when choosing among CSR,
141
+ CSC, dense, generated, or fixed-degree event representations after topology is
142
+ defined.
143
+
144
+ ## Topological and biological patterns
145
+
146
+ | API | Description |
147
+ |---|---|
148
+ | `SmallWorld(...)` | Use for Watts-Strogatz small-world structure. |
149
+ | `ScaleFree(...)` | Use for Barabasi-Albert preferential attachment. |
150
+ | `Regular(...)` | Use when each neuron should have the same degree. |
151
+ | `ModularRandom(...)` | Use for random within-module and between-module probabilities. |
152
+ | `ModularGeneral(...)` | Use when intra- and inter-module structure each need their own `Connectivity` object. |
153
+ | `HierarchicalRandom(...)` | Use for multilevel modules with asymmetric feedforward and feedback connectivity. |
154
+ | `CorePeripheryRandom(...)` | Use for a dense core and sparse periphery. |
155
+ | `ExcitatoryInhibitory(exc_ratio=0.8, exc_prob=0.1, inh_prob=0.2, exc_weight=None, inh_weight=None, exc_delay=None, inh_delay=None, **kwargs)` | Use for separate excitatory and inhibitory presynaptic populations whose outgoing signs follow Dale's principle. |
156
+
157
+ ## Kernel-based patterns
158
+
159
+ Use kernel patterns when source and target neurons occupy image-like spatial
160
+ grids and a local receptive-field operator defines edges.
161
+
162
+ | API | Description |
163
+ |---|---|
164
+ | `Conv2dKernel(...)` | Use a general convolutional kernel. |
165
+ | `GaussianKernel(...)` | Use a Gaussian receptive field. |
166
+ | `GaborKernel(...)` | Use an orientation-selective Gabor field. |
167
+ | `DoGKernel(...)` | Use a difference-of-Gaussians center-surround field. |
168
+ | `MexicanHat(...)` | Use a Laplacian-of-Gaussian field. |
169
+ | `SobelKernel(...)` | Use a Sobel orientation/edge kernel. |
170
+ | `LaplacianKernel(...)` | Use a Laplacian edge kernel. |
171
+ | `CustomKernel(...)` | Supply a user-defined kernel function. |
172
+
173
+ ## Multi-compartment patterns
174
+
175
+ Use `SOMA`, `BASAL_DENDRITE`, `APICAL_DENDRITE`, and `AXON` as the documented
176
+ compartment identifiers. Choose the narrowest pattern that expresses the
177
+ anatomical constraint.
178
+
179
+ | Family | API | Description |
180
+ |---|---|---|
181
+ | General | `CompartmentSpecific(...)` | Define source and target compartment rules directly. |
182
+ | General | `AllToAllCompartments(...)` | Connect all allowed compartment pairs. |
183
+ | General | `CustomCompartment(...)` | Supply a custom compartment-selection function. |
184
+ | Anatomical | `SomaToDendrite(...)` | Target dendrites from somatic sources. |
185
+ | Anatomical | `AxonToSoma(...)` | Target soma from axons. |
186
+ | Anatomical | `DendriteToSoma(...)` | Target soma from dendrites. |
187
+ | Anatomical | `AxonToDendrite(target_dendrites=None, **kwargs)` | Target selected dendritic compartments from axons. |
188
+ | Anatomical | `DendriteToDendrite(...)` | Connect dendritic compartments. |
189
+ | Morphology | `ProximalTargeting(...)` | Prefer proximal dendritic compartments. |
190
+ | Morphology | `DistalTargeting(...)` | Prefer distal dendritic compartments. |
191
+ | Morphology | `BranchSpecific(...)` | Restrict targets to specified branches. |
192
+ | Morphology | `MorphologyDistance(...)` | Use morphology-aware distances. |
193
+ | Dendritic | `DendriticTree(...)` | Configure separate basal/apical probabilities. |
194
+ | Dendritic | `BasalDendriteTargeting(...)` | Restrict targets to basal dendrites. |
195
+ | Dendritic | `ApicalDendriteTargeting(...)` | Restrict targets to apical dendrites. |
196
+ | Dendritic | `DendriticIntegration(...)` | Express dendritic integration patterns. |
197
+ | Axonal | `AxonalProjection(...)` | Build topographic axonal projections. |
198
+ | Axonal | `AxonalBranching(...)` | Build branching axonal patterns. |
199
+ | Axonal | `AxonalArborization(...)` | Build axonal arborization patterns. |
200
+ | Axonal | `TopographicProjection(...)` | Preserve source/target topography. |
201
+ | Synaptic | `SynapticPlacement(...)` | Apply synapse-placement rules. |
202
+ | Synaptic | `SynapticClustering(...)` | Cluster synapses on target morphology. |
203
+
204
+ ## Official source
205
+
206
+ - `https://brainx.chaobrain.com/braintools/apis/conn.html`