brainx-skill 1.0.8 → 1.0.9

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 (44) hide show
  1. package/README.md +1 -6
  2. package/manifest.json +3 -2
  3. package/package.json +2 -1
  4. package/skills/braincell/SKILL.md +1 -1
  5. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +107 -44
  6. package/skills/braincell/references/channel-library.md +0 -85
  7. package/skills/braincell/references/ion-library.md +0 -67
  8. package/skills/braincell/references/multicompartment/filter-function-library.md +0 -8
  9. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +204 -65
  10. package/skills/brainmass/SKILL.md +290 -0
  11. package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
  12. package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
  13. package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  14. package/skills/brainmass/references/braintools/cogtask.md +190 -0
  15. package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
  16. package/skills/brainmass/references/braintools/metric.md +157 -0
  17. package/skills/brainmass/references/braintools/optimizer.md +187 -0
  18. package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
  19. package/skills/brainmass/references/braintools/surrogate.md +151 -0
  20. package/skills/brainmass/references/coupling-network-api.md +148 -0
  21. package/skills/brainmass/references/datasets-api.md +72 -0
  22. package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
  23. package/skills/brainmass/references/forward-observation-api.md +131 -0
  24. package/skills/brainmass/references/horn-task-training.md +199 -0
  25. package/skills/brainmass/references/modellibrary.md +104 -0
  26. package/skills/brainmass/references/noiseprocesses.md +121 -0
  27. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
  28. package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
  29. package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
  30. package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
  31. package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
  32. package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
  33. package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
  34. package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
  35. package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
  36. package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
  37. package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
  38. package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
  39. package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
  40. package/skills/brainmass/references/visualization-analysis-api.md +130 -0
  41. package/skills/brainpy-state/SKILL.md +1 -1
  42. package/skills/brainx-general-guard/SKILL.md +43 -128
  43. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +0 -303
  44. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +0 -62
@@ -0,0 +1,187 @@
1
+ # Braintools parameter initializers
2
+
3
+ Use this reference to initialize parameters, weights, delays, and spatial
4
+ profiles with unit-aware, reusable strategies. It covers distribution choice,
5
+ variance scaling, orthogonal methods, composition, and distance-based weight
6
+ modulation.
7
+
8
+ For BrainMass, use these initializers for model State, fitted starting values,
9
+ HORN weights, or distance-modulated network parameters when the consuming API
10
+ accepts a Braintools initialization specification.
11
+
12
+ ## Choose an initializer
13
+
14
+ | Need | Use | Important constraint |
15
+ |---|---|---|
16
+ | Fixed value | `Constant` or `ZeroInit` | Preserve physical units in the value. |
17
+ | Bounded random values | `Uniform`, `TruncatedNormal`, or `Beta` | Choose bounds that match the parameter's domain. |
18
+ | Bell-shaped variability | `Normal` | Negative draws remain possible unless clipped. |
19
+ | Positive skew | `LogNormal`, `Gamma`, `Exponential`, or `Weibull` | Use only when the parameter domain and parameterization match the distribution. |
20
+ | Activation-aware matrix scale | Kaiming, Xavier, or LeCun variants | Match the initializer to the activation and fan mode. |
21
+ | Norm-preserving matrix | `Orthogonal` or `Identity` | Validate the required matrix or convolutional shape. |
22
+ | Heterogeneous population | `Mixture` or `Conditional` | Keep component units and output shapes compatible. |
23
+ | Spatial weight scaling | `DistanceModulated` | This scales existing weights; it does not sample connectivity. |
24
+
25
+ ## Resolve initialization specifications
26
+
27
+ An `Initialization` object is a shape-aware callable. Use `param()` at APIs that
28
+ accept an initializer, scalar, array, or quantity through one boundary.
29
+
30
+ | API | Description |
31
+ |---|---|
32
+ | `Initialization` | Subclass when a new reusable initialization strategy is required. |
33
+ | `param(init, sizes, batch_size=None, allow_none=True, allow_scalar=True, **param_kwargs)` | Resolve an initializer or already concrete value into a parameter. It applies the requested shape policy and forwards keywords such as RNG or distances. |
34
+ | `Compose(*steps)` | Apply an initializer followed by one or more transformations. |
35
+
36
+ ```python
37
+ import brainunit as u
38
+ import numpy as np
39
+ from braintools.init import Normal, param
40
+
41
+ rng = np.random.default_rng(0)
42
+ initializer = Normal(mean=0.5 * u.nS, std=0.1 * u.nS)
43
+ weights = param(initializer, sizes=100, rng=rng)
44
+
45
+ assert weights.shape == (100,)
46
+ assert weights.unit == u.nS
47
+ ```
48
+
49
+ **Invariant:** pass an explicit RNG when reproducibility matters. Do not strip a
50
+ quantity's unit to make an initializer accept it.
51
+
52
+ ## Basic distributions
53
+
54
+ | API | Description |
55
+ |---|---|
56
+ | `Constant(value)` | Fill the requested shape with one value. |
57
+ | `ZeroInit(unit=None)` | Fill the requested shape with zero, optionally carrying a unit. |
58
+ | `Uniform(low, high, unit=None)` | Sample uniformly between lower and upper bounds. |
59
+ | `Normal(mean, std, unit=None)` | Sample a Gaussian distribution. |
60
+ | `LogNormal(mean, std, unit=None)` | Sample a positive log-normal distribution. |
61
+ | `TruncatedNormal(mean, std, low, high, unit=None)` | Sample a normal distribution within explicit bounds. |
62
+ | `Gamma(...)` | Sample a gamma distribution for positive skewed values. |
63
+ | `Exponential(...)` | Sample an exponential distribution. |
64
+ | `Beta(...)` | Sample a beta distribution rescaled to a requested range. |
65
+ | `Weibull(...)` | Sample a Weibull distribution. |
66
+
67
+ Use explicit `unit=` only when the distribution parameters themselves do not
68
+ already establish the required unit.
69
+
70
+ ## Variance scaling
71
+
72
+ Variance-scaling initializers derive scale from matrix fan dimensions. Use
73
+ `fan_in` to preserve forward variance, `fan_out` to preserve backward variance,
74
+ and `fan_avg` to balance both.
75
+
76
+ | API | Description |
77
+ |---|---|
78
+ | `VarianceScaling(...)` | Use for a custom scale, fan mode, and distribution combination. |
79
+ | `KaimingUniform(...)` | Use uniform Kaiming/He initialization for ReLU-family activations. |
80
+ | `KaimingNormal(scale=None, mode='fan_in', nonlinearity='relu', negative_slope=0.01, unit=None)` | Use normal Kaiming/He initialization and match `nonlinearity` plus `negative_slope` to the layer. |
81
+ | `XavierUniform(...)` | Use uniform Xavier/Glorot initialization for symmetric tanh/sigmoid-style activations. |
82
+ | `XavierNormal(...)` | Use normal Xavier/Glorot initialization. |
83
+ | `LecunUniform(...)` | Use uniform LeCun initialization for SELU-style self-normalizing layers. |
84
+ | `LecunNormal(...)` | Use normal LeCun initialization. |
85
+
86
+ ```python
87
+ from braintools.init import KaimingNormal, XavierUniform
88
+
89
+ relu_weights = KaimingNormal(mode="fan_in")((256, 784), rng=rng)
90
+ tanh_weights = XavierUniform()((256, 784), rng=rng)
91
+ ```
92
+
93
+ Confirm which axis the consuming layer treats as input before relying on fan
94
+ inference.
95
+
96
+ ## Orthogonal methods
97
+
98
+ | API | Description |
99
+ |---|---|
100
+ | `Orthogonal(scale=1.0, unit=None)` | Use QR-based orthogonal initialization for recurrent or deep matrix weights. It supports non-square matrices. |
101
+ | `DeltaOrthogonal(...)` | Use for convolutional kernels whose central spatial slice should be orthogonal. |
102
+ | `Identity(scale=1.0, unit=None)` | Use when the initial transformation should be an optionally scaled identity. |
103
+
104
+ ## Composite distributions
105
+
106
+ | API | Description |
107
+ |---|---|
108
+ | `Mixture(distributions, weights=None)` | Select among component distributions per parameter according to mixture weights. |
109
+ | `Conditional(condition_fn, true_dist, false_dist)` | Select one of two initializers from neuron indices or supplied properties. |
110
+ | `Scaled(initializer, scale_factor)` | Multiply another initializer's output. |
111
+ | `Clipped(initializer, min_val, max_val)` | Bound another initializer's output. |
112
+
113
+ ```python
114
+ from braintools.init import Conditional, Normal
115
+
116
+ initializer = Conditional(
117
+ condition_fn=lambda indices: indices < 800,
118
+ true_dist=Normal(0.5 * u.nS, 0.1 * u.nS),
119
+ false_dist=Normal(-0.3 * u.nS, 0.05 * u.nS),
120
+ )
121
+ weights = initializer(
122
+ 1000,
123
+ neuron_indices=np.arange(1000),
124
+ rng=rng,
125
+ )
126
+ ```
127
+
128
+ ## Distance-modulated weights
129
+
130
+ A `DistanceProfile` maps distances to both documented probability and
131
+ weight-scaling functions. `DistanceModulated` uses the scaling values only.
132
+
133
+ | API | Description |
134
+ |---|---|
135
+ | `DistanceModulated(base_dist, distance_profile)` | Return `base_weights * distance_profile(distances)` element-wise. Supply `distances` directly or `pre_positions` and `post_positions`. |
136
+ | `GaussianProfile(sigma, max_distance=None)` | Use a Gaussian distance profile. |
137
+ | `ExponentialProfile(decay_constant, max_distance=None)` | Use exponentially decaying distance dependence. |
138
+ | `LinearProfile(...)` | Use a linear distance profile. |
139
+ | `StepProfile(...)` | Use a hard distance threshold or step. |
140
+ | `PowerLawProfile(...)` | Use power-law distance dependence. |
141
+ | `MexicanHatProfile(...)` | Use a Ricker/Mexican-hat profile. |
142
+ | `DoGProfile(...)` | Use a difference-of-Gaussians profile. |
143
+ | `SigmoidProfile(...)` | Use a sigmoid transition with distance. |
144
+ | `BimodalProfile(...)` | Use two distance-dependent modes. |
145
+ | `LogisticProfile(...)` | Use logistic distance dependence. |
146
+ | `ComposedProfile(...)` | Combine two profiles arithmetically. |
147
+ | `ClipProfile(...)` / `profile.clip(...)` | Bound profile output. |
148
+ | `ApplyProfile(...)` / `profile.apply(func)` | Transform profile output with a function. |
149
+ | `PipeProfile(...)` / `profile \| func` | Chain profiles or transformations. |
150
+
151
+ ```python
152
+ from braintools.init import DistanceModulated, GaussianProfile, Normal
153
+
154
+ profile = GaussianProfile(sigma=100 * u.um)
155
+ initializer = DistanceModulated(
156
+ base_dist=Normal(1.0 * u.nS, 0.2 * u.nS),
157
+ distance_profile=profile,
158
+ ).clip(min_val=0.01 * u.nS)
159
+
160
+ distances = np.random.default_rng(1).uniform(0, 500, 1000) * u.um
161
+ weights = initializer(1000, distances=distances, rng=rng)
162
+ ```
163
+
164
+ **Invariant:** a zero profile value creates a present but silent zero-weight
165
+ synapse. Use `braintools.conn.DistanceDependent` when distance must decide
166
+ whether an edge exists.
167
+
168
+ ## Functional composition
169
+
170
+ All `Initialization` and `DistanceProfile` objects support arithmetic
171
+ composition. Initializers additionally support `.clip()`, `.add()`,
172
+ `.multiply()`, `.apply()`, and pipe composition with `|`.
173
+
174
+ Build and validate composition incrementally:
175
+
176
+ ```python
177
+ base = Normal(0.5 * u.nS, 0.1 * u.nS)
178
+ bounded = base.clip(0.0 * u.nS, 1.0 * u.nS)
179
+ final = bounded * 2.0 + 0.1 * u.nS
180
+ ```
181
+
182
+ Keep units compatible at every arithmetic step. Apply clipping through
183
+ composition; `DistanceModulated` does not accept a `min_weight` argument.
184
+
185
+ ## Official source
186
+
187
+ - `https://brainx.chaobrain.com/braintools/apis/init.html`
@@ -0,0 +1,151 @@
1
+ # Braintools surrogate gradients
2
+
3
+ Use this reference to select a functional or reusable surrogate-gradient spike
4
+ operator for differentiable spiking neural networks. A surrogate emits a hard
5
+ spike in the forward pass and supplies a smooth derivative in the backward
6
+ pass.
7
+
8
+ For BrainMass, open this reference only when a custom model or task path
9
+ introduces a hard threshold or spike operator. Canonical neural-mass,
10
+ `Fitter`, and HORN workflows are differentiable without surrogate gradients.
11
+
12
+ ## Choose an API style
13
+
14
+ | Style | Use when | Example |
15
+ |---|---|---|
16
+ | Class | A configured surrogate is stored on a neuron or layer and reused | `Sigmoid(alpha=4.0)` |
17
+ | Functional | One direct spike operation is clearer | `sigmoid(x, alpha=4.0)` |
18
+ | Custom class | The research method specifies a derivative absent from the library | Subclass `Surrogate` and implement `surrogate_grad`; optionally implement `surrogate_fun` for analysis. |
19
+
20
+ Corresponding class and functional forms have the same forward and backward
21
+ semantics.
22
+
23
+ ## Choose a gradient family
24
+
25
+ | Family | Use when | Main tuning behavior |
26
+ |---|---|---|
27
+ | Sigmoid, soft-sign, arctangent, or ERF | A smooth bounded derivative is preferred | `alpha` controls slope or concentration. |
28
+ | Piecewise quadratic or exponential | A local, inexpensive piecewise derivative is preferred | `alpha` controls scale or sharpness. |
29
+ | ReLU-based | A simple or tailed piecewise derivative is required | Width, leak, and scale control support and tails. |
30
+ | Gaussian | Gradient should be localized around threshold | `sigma` controls support; scale controls magnitude. |
31
+ | Advanced published form | Reproducing a specified SNN method | Preserve the documented parameters and formulation. |
32
+
33
+ Start with `Sigmoid`, `PiecewiseQuadratic`, or `ReluGrad`, confirm finite
34
+ nonzero gradients, then vary one family or parameter at a time.
35
+
36
+ ## Smooth bounded surrogates
37
+
38
+ | Functional API | Class API | Description |
39
+ |---|---|---|
40
+ | `sigmoid(x, alpha=4.0)` | `Sigmoid(alpha=4.0)` | Use a sigmoid-shaped backward derivative. |
41
+ | `soft_sign(x, alpha=...)` | `SoftSign(alpha=...)` | Use a soft-sign derivative with different tail decay. |
42
+ | `arctan(x, alpha=...)` | `Arctan(alpha=...)` | Use an arctangent-shaped smooth derivative. |
43
+ | `erf(x, alpha=...)` | `ERF(alpha=...)` | Use an error-function/Gaussian-CDF derivative. |
44
+
45
+ ## Piecewise and ReLU-based surrogates
46
+
47
+ | Functional API | Class API | Description |
48
+ |---|---|---|
49
+ | `piecewise_quadratic(x, alpha=1.0)` | `PiecewiseQuadratic(alpha=1.0)` | Use a triangle-like piecewise-quadratic derivative. |
50
+ | `piecewise_exp(x, alpha=1.0)` | `PiecewiseExp(alpha=1.0)` | Use a piecewise-exponential derivative. |
51
+ | `piecewise_leaky_relu(x, c=..., alpha=...)` | `PiecewiseLeakyRelu(c=..., alpha=...)` | Use a piecewise leaky-ReLU derivative. |
52
+ | `leaky_relu(x, alpha=..., beta=...)` | `LeakyRelu(alpha=..., beta=...)` | Use a leaky-ReLU-shaped derivative. |
53
+ | `log_tailed_relu(x, alpha=...)` | `LogTailedRelu(alpha=...)` | Use a ReLU-like center with logarithmic tails. |
54
+ | `relu_grad(x, alpha=0.3, width=1.0)` | `ReluGrad(alpha=0.3, width=1.0)` | Use a constant local derivative within a configured threshold width. |
55
+
56
+ ## Gaussian and inverse-square surrogates
57
+
58
+ | Functional API | Class API | Description |
59
+ |---|---|---|
60
+ | `gaussian_grad(x, sigma=0.5, alpha=0.5)` | `GaussianGrad(sigma=0.5, alpha=0.5)` | Use one Gaussian derivative peak around threshold. |
61
+ | `multi_gaussian_grad(x, h=0.15, s=6.0, sigma=0.5, scale=0.5)` | `MultiGaussianGrad(h=0.15, s=6.0, sigma=0.5, scale=0.5)` | Use the documented multi-Gaussian combination. |
62
+ | `inv_square_grad(x, alpha=...)` | `InvSquareGrad(alpha=...)` | Use an inverse-square derivative profile. |
63
+
64
+ ## Advanced surrogates
65
+
66
+ | Functional API | Class API | Description |
67
+ |---|---|---|
68
+ | `squarewave_fourier_series(x, ...)` | `SquarewaveFourierSeries(...)` | Use a truncated Fourier approximation to a square wave. |
69
+ | `s2nn(x, alpha=4.0, beta=1.0, epsilon=1e-8)` | `S2NN(alpha=4.0, beta=1.0, epsilon=1e-8)` | Use the S2NN formulation. |
70
+ | `q_pseudo_spike(x, alpha=2.0)` | `QPseudoSpike(alpha=2.0)` | Use the q-pseudo-spike formulation. |
71
+ | `slayer_grad(x, alpha=1.0)` | `SlayerGrad(alpha=1.0)` | Use the SLAYER surrogate formulation. |
72
+ | `nonzero_sign_log(x, alpha=...)` | `NonzeroSignLog(alpha=...)` | Use nonzero sign with logarithmic damping. |
73
+
74
+ ## Canonical neuron integration
75
+
76
+ Store the configured surrogate on the neuron and apply it to membrane state
77
+ relative to threshold.
78
+
79
+ ```python
80
+ import brainstate as bst
81
+ import jax.numpy as jnp
82
+ from braintools.surrogate import Sigmoid
83
+
84
+
85
+ class LIFLayer(bst.nn.Module):
86
+ def __init__(self, in_size, out_size):
87
+ super().__init__()
88
+ self.linear = bst.nn.Linear(in_size, out_size)
89
+ self.v = bst.State(jnp.zeros(out_size))
90
+ self.spike = Sigmoid(alpha=4.0)
91
+
92
+ def __call__(self, x):
93
+ self.v.value = 0.9 * self.v.value + self.linear(x)
94
+ spikes = self.spike(self.v.value - 1.0)
95
+ self.v.value = jnp.where(spikes > 0, 0.0, self.v.value)
96
+ return spikes
97
+ ```
98
+
99
+ **Invariant:** the forward value remains the discrete threshold event. The
100
+ surrogate changes only the derivative seen by automatic differentiation.
101
+
102
+ ## Validate the chosen surrogate
103
+
104
+ Inspect representative gradients before a training run:
105
+
106
+ ```python
107
+ import jax
108
+ import jax.numpy as jnp
109
+ from braintools.surrogate import Sigmoid
110
+
111
+ spike = Sigmoid(alpha=4.0)
112
+ x = jnp.linspace(-2.0, 2.0, 101)
113
+ gradient = jax.vmap(jax.grad(lambda value: spike(value)))(x)
114
+
115
+ assert jnp.all(jnp.isfinite(gradient))
116
+ assert jnp.any(gradient != 0)
117
+ ```
118
+
119
+ If learning fails, first verify reset timing, loss reduction, gradient target,
120
+ and temporal rollout. Do not change the surrogate, optimizer, and loss
121
+ simultaneously.
122
+
123
+ ## Custom surrogate
124
+
125
+ Subclass `Surrogate` only when the required derivative is not already
126
+ represented:
127
+
128
+ ```python
129
+ import jax.numpy as jnp
130
+ from braintools.surrogate import Surrogate
131
+
132
+
133
+ class TanhSurrogate(Surrogate):
134
+ def __init__(self, alpha=1.0):
135
+ super().__init__()
136
+ self.alpha = alpha
137
+
138
+ def surrogate_fun(self, x):
139
+ return 0.5 * jnp.tanh(self.alpha * x) + 0.5
140
+
141
+ def surrogate_grad(self, x):
142
+ tanh_x = jnp.tanh(self.alpha * x)
143
+ return 0.5 * self.alpha * (1.0 - tanh_x**2)
144
+ ```
145
+
146
+ Keep `surrogate_grad` pure, shape preserving, JAX traceable, and finite near
147
+ threshold.
148
+
149
+ ## Official source
150
+
151
+ - `https://brainx.chaobrain.com/braintools/apis/surrogate.html`
@@ -0,0 +1,148 @@
1
+ # Coupling and network API
2
+
3
+ Use this reference when configuring structural connectivity, delays, coupling families, self-connections, network-level noise, trainable coupling parameters, or direct coupling objects. Use `brainmass.Network` unless custom wiring requires lower-level prefetch and coupling composition.
4
+
5
+ ## Construct the network
6
+
7
+ `Network` reads one `N`-region node bank, computes its coupling current, and passes that current as the node's first positional input on every update.
8
+
9
+ | API | Description |
10
+ |---|---|
11
+ | `brainmass.Network(node, *, conn, distance=None, speed=None, coupling="diffusive", coupled_var, k=1.0, delay_init=..., self_connection=False, noise=None)` | Use for the high-level whole-brain path; it validates `coupled_var`, constructs delays and coupling, and exposes the wrapped dynamics as `.node`. |
12
+ | `Network.init_state(...)` | Use indirectly through `Simulator`; it initializes the node, coupling, delay history, and optional network noise. |
13
+ | `Network.update(*node_inputs)` | Use for one custom step; it computes coupling plus optional noise, forwards that as the first node input, and returns the node update result. |
14
+ | `brainmass.Simulator(network, dt=...)` | Use for the canonical execution path; monitor wrapped State through `network.node`. |
15
+
16
+ ```python
17
+ import brainmass
18
+ import brainstate
19
+ import brainunit as u
20
+
21
+ dt = 0.1 * u.ms
22
+ brainstate.environ.set(dt=dt)
23
+
24
+ connectome = brainmass.datasets.load_dataset("example_connectome")
25
+ n_region = connectome.weights.shape[0]
26
+ network = brainmass.Network(
27
+ brainmass.HopfStep(in_size=n_region, a=0.2, w=0.3),
28
+ conn=connectome.weights,
29
+ distance=connectome.distances,
30
+ speed=10.0 * u.mm / u.ms,
31
+ coupling="diffusive",
32
+ coupled_var="x",
33
+ k=0.5,
34
+ )
35
+ result = brainmass.Simulator(network, dt=dt).run(
36
+ 400.0 * u.ms,
37
+ monitors=lambda model: model.node.x.value,
38
+ transient=100.0 * u.ms,
39
+ )
40
+
41
+ assert result["output"].shape == (3000, n_region)
42
+ ```
43
+
44
+ **Invariant:** set global `dt` before constructing a delayed network and use the same value in `Simulator`. The delay buffer is sized at construction.
45
+
46
+ ## Preserve connectivity semantics
47
+
48
+ Use the convention `W[i, j] = source j -> target i`. Each row therefore contains the incoming weights for one target.
49
+
50
+ | Input | Behavior |
51
+ |---|---|
52
+ | Plain `(N, N)` connectivity array | `Network` zeroes the diagonal unless `self_connection=True`. |
53
+ | Directed array | Preserved; symmetry is not required. |
54
+ | `Param` or `LaplacianConnParam` connectivity | Passed through without diagonal rewriting; the caller owns its structure. |
55
+ | Missing `distance` or `speed` | Coupling is instantaneous with zero delays. |
56
+ | Unit-aware `distance` and `speed` | `distance / speed` produces unit-correct conduction delays. |
57
+ | Plain `distance` and `speed` | Their quotient is interpreted as milliseconds by the documented convention. |
58
+
59
+ Use structural connectivity for wiring. Functional connectivity is an output statistic, not a substitute for anatomical weights.
60
+
61
+ ## Choose a coupling
62
+
63
+ Choose where the interaction should be relative, absolute, or saturated.
64
+
65
+ | API | Description |
66
+ |---|---|
67
+ | `Network(..., coupling="diffusive")` / `DiffusiveCoupling(...)` | Use for `k * sum_j W[i,j] * (source_j - target_i)`; it vanishes at consensus and is the canonical synchronization path. |
68
+ | `Network(..., coupling="additive")` / `AdditiveCoupling(...)` | Use for direct weighted input `k * sum_j W[i,j] * source_j + b`; it does not vanish when nodes agree. |
69
+ | `Network(..., coupling="laplacian")` / `LaplacianConnParam(...)` | Use for additive application of a graph Laplacian, including normalized variants. |
70
+ | `Network(..., coupling="tanh")` / `HyperbolicTangentCoupling(...)` | Use for symmetric saturation of the summed input toward `+/-k`. |
71
+ | `Network(..., coupling="sigmoidal")` / `SigmoidalCoupling(...)` | Use for a bounded one-sided post-sum firing-rate transfer with configurable slope and midpoint. |
72
+ | `Network(..., coupling="sigmoidal_jansen_rit")` / `SigmoidalJansenRitCoupling(...)` | Use for the Jansen-Rit pre-synaptic transfer, where each source passes through the sigmoid before weighting and summation. |
73
+
74
+ The functional forms expose stateless kernels for custom composition:
75
+
76
+ | API | Description |
77
+ |---|---|
78
+ | `brainmass.diffusive_coupling(source, target, conn, k)` | Compute relative diffusive input from delayed source reads and each target's current value. |
79
+ | `brainmass.additive_coupling(source, conn, k, b=...)` | Compute a direct weighted source sum and optional bias. |
80
+ | `brainmass.sigmoidal_coupling(...)` | Apply the logistic nonlinearity after the network sum. |
81
+ | `brainmass.hyperbolic_tangent_coupling(...)` | Apply symmetric tanh saturation after the network sum. |
82
+ | `brainmass.sigmoidal_jansen_rit_coupling(...)` | Apply the Jansen-Rit sigmoid to each source before the weighted sum. |
83
+ | `brainmass.laplacian_connectivity(conn, normalize=...)` | Build unnormalized, symmetric-normalized, or random-walk graph Laplacians for explicit Laplacian workflows. |
84
+
85
+ Use the `Network` string selector for standard defaults. Construct a coupling class directly only when its shape parameters, prefetched sources, or trainable parameters need explicit control.
86
+
87
+ ## Configure delays and coupling parameters
88
+
89
+ `distance / speed` defines each edge delay. `Network` zeroes self-delay and stores enough history for the largest discretized delay.
90
+
91
+ | Parameter | Decision |
92
+ |---|---|
93
+ | `coupled_var` | Name the node State that supplies the delayed source and receives the coupling path; an unknown State raises `ValueError`. |
94
+ | `k` | Set the global coupling strength; pass `Param(..., fit=True)` only when it belongs in the fitting target. |
95
+ | `delay_init` | Set the history initializer when startup dynamics depend on pre-run delayed State. |
96
+ | `self_connection` | Keep `False` unless the structural matrix intentionally contains coupling-level recurrent edges distinct from local node dynamics. |
97
+ | `noise` | Add network-level noise to the coupling current; keep population-specific noise on the node. |
98
+
99
+ Start with normalized or otherwise scientifically calibrated weights and a modest `k`. Changing weight normalization changes the meaning of `k`.
100
+
101
+ ## Direct construction
102
+
103
+ Use direct construction only when a built-in `Network` cannot represent the source/target wiring. A diffusive coupling requires one delayed `(target, source)` read and one current target read.
104
+
105
+ ```python
106
+ import jax.numpy as jnp
107
+ import braintools
108
+
109
+ n_region = connectome.weights.shape[0]
110
+ nodes = brainmass.HopfStep(in_size=n_region, a=0.2, w=0.3)
111
+ delays = jnp.ones((n_region, n_region)) * (1.0 * u.ms)
112
+ indices = brainmass.delay_index(n_region)
113
+
114
+ source = nodes.prefetch_delay(
115
+ "x",
116
+ (delays, indices),
117
+ init=braintools.init.Constant(0.0),
118
+ )
119
+ target = nodes.prefetch("x")
120
+ coupling = brainmass.DiffusiveCoupling(
121
+ source,
122
+ target,
123
+ conn=connectome.weights,
124
+ k=0.5,
125
+ )
126
+ ```
127
+
128
+ Do not replace the delay prefetch protocol with a manually shifted Python container.
129
+
130
+ ## Application script
131
+
132
+ Open `scripts/resting-state-meg-whole-brain-pipeline.py` when the task needs the complete connectome-to-network-to-MEG-to-functional-connectivity workflow.
133
+
134
+ ## Diagnose network failures
135
+
136
+ - Exploding activity: lower `k`, verify weight normalization and units, or select an appropriate saturating coupling.
137
+ - No collective effect: inspect isolated rows, directionality, `coupled_var`, simulation duration, and `k`.
138
+ - Shape error in direct diffusive coupling: provide an `(N, N)` source read and an `(N,)` target read.
139
+ - Unexpected self-drive: inspect whether the input is a plain array, a `Param`, or a Laplacian wrapper and confirm ownership of diagonal handling.
140
+ - Missing or wrong delays: confirm global `dt`, distance units, speed units, and use of the same `dt` during simulation.
141
+ - Missing monitor State: traverse `lambda model: model.node.<state>.value`.
142
+
143
+ ## Official sources
144
+
145
+ - `https://brainx.chaobrain.com/brainmass/reference/coupling.html`
146
+ - `https://brainx.chaobrain.com/brainmass/tutorials/04_building_a_network.html`
147
+ - `https://brainx.chaobrain.com/brainmass/concepts/coupling_and_delays.html`
148
+ - `https://brainx.chaobrain.com/brainmass/howto/custom_coupling.html`
@@ -0,0 +1,72 @@
1
+ # BrainMass datasets
2
+
3
+ Use this reference when loading bundled BrainMass examples, inspecting typed connectome or signal containers, generating delayed-match task data, or registering a small local dataset loader.
4
+
5
+ ## Registry
6
+
7
+ | API | Description |
8
+ |---|---|
9
+ | `brainmass.datasets.list_datasets()` | List names and descriptions currently registered in the installed release. |
10
+ | `brainmass.datasets.load_dataset(name)` | Resolve a registered loader and return its typed or generated value; an unknown name raises instead of guessing a path. |
11
+ | `brainmass.datasets.register_dataset(name, loader, description=...)` | Register a callable under one name for the current process; the callable runs each time the dataset is loaded. |
12
+
13
+ ```python
14
+ import brainmass
15
+
16
+ available = brainmass.datasets.list_datasets()
17
+ connectome = brainmass.datasets.load_dataset("example_connectome")
18
+ signal = brainmass.datasets.load_dataset("example_signal")
19
+
20
+ assert connectome.weights.shape == connectome.distances.shape == (8, 8)
21
+ assert signal.signal.shape == (500, 8)
22
+ ```
23
+
24
+ Use the registry for small, deterministic tutorial or study-local loaders. It is not a remote dataset manager or a persistence format.
25
+
26
+ ## Typed containers
27
+
28
+ | API | Description |
29
+ |---|---|
30
+ | `brainmass.datasets.Connectome(weights, distances, labels)` | Hold square structural weights, unit-aware inter-region distances, and region labels used by `Network`. |
31
+ | `brainmass.datasets.Signal(signal, dt, labels, fc)` | Hold a time-major multi-region signal, its sampling step, labels, and precomputed functional connectivity. |
32
+ | `brainmass.datasets.delayed_match_task(n_samples=..., seq_len=..., n_symbols=..., seed=...)` | Generate reproducible delayed-match-to-sample inputs and binary targets for the HORN workflow. |
33
+
34
+ The built-in registry provides:
35
+
36
+ | Name | Result | Use |
37
+ |---|---|---|
38
+ | `example_connectome` | `Connectome` | Small symmetric eight-region weights, millimeter distances, and labels for network tutorials. |
39
+ | `example_signal` | `Signal` | Short eight-region target trajectory, sampling `dt`, labels, and FC for fitting and analysis. |
40
+ | `delayed_match_task` | `(inputs, targets)` | Synthetic task data generated from the requested size and seed. |
41
+
42
+ ```python
43
+ inputs, targets = brainmass.datasets.delayed_match_task(
44
+ n_samples=32,
45
+ seq_len=8,
46
+ n_symbols=2,
47
+ seed=0,
48
+ )
49
+
50
+ assert inputs.shape == (32, 8, 2)
51
+ assert targets.shape == (32,)
52
+ ```
53
+
54
+ Treat BrainMass signals as time-major and HORN task inputs as `(sample, time, feature)` until the training workflow explicitly transposes them.
55
+
56
+ ## Register a loader
57
+
58
+ ```python
59
+ brainmass.datasets.register_dataset(
60
+ "study_connectome",
61
+ lambda: connectome,
62
+ description="Validated connectome for the current study",
63
+ )
64
+ loaded = brainmass.datasets.load_dataset("study_connectome")
65
+ assert loaded is connectome
66
+ ```
67
+
68
+ Validate shape, symmetry or directionality, diagonal policy, units, labels, and sampling interval in the loader or immediately after loading. Registration alone does not validate scientific metadata.
69
+
70
+ ## Official source
71
+
72
+ - `https://brainx.chaobrain.com/brainmass/reference/datasets.html`