brainx-skill 1.0.16 → 1.0.18

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.
@@ -3,7 +3,8 @@ https://brainx.chaobrain.com/brainmass/gallery/case_studies/resting_state_meg.ht
3
3
 
4
4
  Converted from the official notebook at upstream commit
5
5
  293eaeb8948474c645208b68c531b7cb5482d4fb. Notebook outputs are omitted and
6
- ``%matplotlib inline`` remains commented; code and Markdown cells are preserved.
6
+ ``%matplotlib inline`` remains commented. Local adaptations use BrainTools
7
+ initializers and Pearson diagnostics; this is not an exact upstream copy.
7
8
 
8
9
  Requires BrainTools 0.4.0 or newer for functional-connectivity analysis.
9
10
  """
@@ -13,7 +14,7 @@ Requires BrainTools 0.4.0 or newer for functional-connectivity analysis.
13
14
  # %matplotlib inline
14
15
  import brainmass
15
16
  import brainstate
16
- from braintools.analysis.population import functional_connectivity
17
+ import braintools
17
18
  import brainunit as u
18
19
  import jax
19
20
  import jax.numpy as jnp
@@ -152,7 +153,7 @@ M = 16 # number of MEG sensors
152
153
  # Synthetic geometric lead field: each region projects to sensors with a smooth,
153
154
  # distance-like falloff. A real lead field comes from a head model.
154
155
  rng = np.random.default_rng(1)
155
- L_raw = np.abs(rng.standard_normal((N, M))) + 0.1
156
+ L_raw = u.math.abs(braintools.init.Normal(0.0, 1.0)((N, M), rng=rng)) + 0.1
156
157
  L_raw = L_raw / L_raw.sum(axis=0, keepdims=True) # column-normalize
157
158
  L = jnp.asarray(L_raw) * (u.tesla / (u.nA * u.meter))
158
159
 
@@ -211,12 +212,21 @@ target_res = brainmass.Simulator(target_net, dt=0.1 * u.ms).run(
211
212
  target_activity = target_res['output']
212
213
 
213
214
  # --- Functional connectivity: simulated vs target ---
214
- fc_sim = functional_connectivity(u.get_magnitude(activity))
215
- fc_tar = functional_connectivity(u.get_magnitude(target_activity))
215
+ fc_sim = braintools.analysis.population.functional_connectivity(u.get_magnitude(activity))
216
+ fc_tar = braintools.analysis.population.functional_connectivity(u.get_magnitude(target_activity))
216
217
 
217
218
  # (1) Structure-function coupling: does the simulated FC reflect the connectome?
218
219
  triu = np.triu_indices(N, k=1)
219
- sc_fc_corr = float(np.corrcoef(fc_sim[triu], np.asarray(W)[triu])[0, 1])
220
+ edge_pairs = u.math.stack([fc_sim[triu], u.math.asarray(W)[triu]], axis=1)
221
+ valid_pairs = (
222
+ edge_pairs.shape[0] >= 2
223
+ and bool(u.math.all(u.math.isfinite(edge_pairs)))
224
+ and bool(u.math.all(u.math.any(edge_pairs != edge_pairs[0], axis=0)))
225
+ )
226
+ sc_fc_corr = (
227
+ float(braintools.analysis.population.functional_connectivity(edge_pairs)[0, 1])
228
+ if valid_pairs else float("nan")
229
+ )
220
230
  # (2) Simulated vs target FC.
221
231
  fc_match = float(brainmass.objectives.fc_corr()(activity, target_activity))
222
232
  print(f"structure-function coupling corr(FC, SC): {sc_fc_corr:.3f}")
@@ -16,6 +16,8 @@ Use this reference when plotting BrainMass results or computing sample-by-signal
16
16
 
17
17
  Every helper accepts `ax=` and returns the `matplotlib.axes.Axes` it drew on. Pass axes explicitly when composing figures.
18
18
 
19
+ Treat `imshow(..., extent=...)` bounds as cell edges, not sampled centers. For uniform centers `q_i=q_0+iΔ`, use edges `q_0−Δ/2` and `q_{N−1}+Δ/2`; align transpose, `origin`, and decoder overlays to those coordinates, including periodic wrapping. Verify array-index-to-plot-coordinate pairs numerically; successful export does not establish alignment. See the [official image-extent contract](https://matplotlib.org/stable/users/explain/artists/imshow_extent.html).
20
+
19
21
  ## Compute standard summaries
20
22
 
21
23
  The FC, FCD, and PSD examples require BrainTools 0.4.0 or newer and use
@@ -31,9 +33,40 @@ Strip units explicitly before a metric that operates on scale-free raw arrays. K
31
33
  | `brainmass.objectives.fc_corr()` | Score correlation between prediction and target FC without manually recomputing the comparison logic. |
32
34
  | `brainmass.objectives.fcd_distribution(fcd_matrix, ...)` | Estimate the off-diagonal FCD value distribution used by distributional FCD objectives. |
33
35
 
34
- For columnwise Pearson similarity over other observations, such as stimulus responses, evaluate this same API before writing a generic correlation implementation. This extends the documented time-series layout algebraically: verify the required centering, precision and reduction axis, and label the result by its actual observable rather than implying temporal or causal connectivity. A host-side data-generation boundary does not by itself exclude an applicable BrainTools metric.
36
+ ## Compute a two-signal diagnostic
37
+
38
+ Pearson correlation operates on aligned observation columns. Use the same API
39
+ for a noise-lag check or structure/function edge-pair comparison; name the
40
+ actual statistic rather than implying anatomical or causal connectivity.
41
+
42
+ | API | Description |
43
+ |---|---|
44
+ | `braintools.analysis.population.functional_connectivity(observations)[0, 1]` | Use for two unweighted aligned signals. Stack them as `(observations, 2)` and check that all values are finite and each column contains at least two distinct values. |
45
+
46
+ ```python
47
+ import braintools
48
+ import brainunit as u
49
+
50
+ noise = u.math.asarray([0.2, 0.1, 0.4, 0.3, 0.5, 0.2])
51
+ observations = u.math.stack([noise[:-1], noise[1:]], axis=1)
52
+ valid = (
53
+ observations.shape[0] >= 2
54
+ and bool(u.math.all(u.math.isfinite(observations)))
55
+ and bool(u.math.all(u.math.any(observations != observations[0], axis=0)))
56
+ )
57
+ lag1_correlation = (
58
+ float(braintools.analysis.population.functional_connectivity(observations)[0, 1])
59
+ if valid else float("nan")
60
+ )
61
+ ```
35
62
 
36
- Check finite inputs and positive column variances before correlation when undefined Pearson values must remain undefined. In BrainTools 0.4.0, a constant column returned zeros off the diagonal and one on the diagonal in a CPU probe. Reject invalid columns or preserve an explicit validity mask under the scientific missing-value policy. Verify parity on a small witness before substituting the API into a source-defined analysis. See the [official Pearson matrix contract](https://brainx.chaobrain.com/braintools/apis/generated/braintools.analysis.population.functional_connectivity.html) for shapes and NaN handling.
63
+ Check for constant columns by comparing values directly, since rounding in a
64
+ variance reduction can yield a positive result for identical values. Preserve
65
+ the validity flag because BrainTools 0.4.0 replaces NaNs with zero and sets
66
+ the diagonal to one. Check centering, precision and the observation axis
67
+ on a small witness before replacing a source-defined statistic. For weighted
68
+ or matrix-triangle correlation, open `references/braintools/metric.md` for the
69
+ dedicated APIs. See the [official Pearson contract](https://brainx.chaobrain.com/braintools/apis/generated/braintools.analysis.population.functional_connectivity.html).
37
70
 
38
71
  ## Canonical analysis workflow
39
72
 
@@ -81,6 +81,7 @@ Connect source to target with a connection rule plus a unitful synapse spec, and
81
81
  | `sim.connect(pre, post, *, rule=..., weight=..., delay=..., ...)` | Use to build a projection, attach a source device, or register a recorder tap; it returns projection handles for realized projections and `None` for recorder taps or current injectors. |
82
82
  | `brainspike.all_to_all` | Use when every source must connect to every target; this is the default generator fan-out rule. |
83
83
  | `brainspike.fixed_indegree(k)` | Use when every target must draw exactly `k` presynaptic edges; set `seed` for reproducible BrainSpike wiring and `comm="sparse"` for large event fan-in. |
84
+ | `brainspike.spatial.spatial_pairwise_bernoulli(p, mask=...)` | Use when positions and geometric cutoffs select edges; the Simulator constructs the spatial projection. |
84
85
  | `synapse=brainspike.<synapse_model>(...)` | Use when the edge is plastic or needs behavior beyond static weight and delay; keep rule parameters on the synapse spec. |
85
86
  | `sim.connect(generator, neuron)` | Use for current and spike sources; generators drive their targets. |
86
87
  | `sim.connect(neuron, spike_recorder)` | Use to tap emitted spikes. |
@@ -110,6 +111,8 @@ Do not interchange default and explicit synapse delay paths; open `references/ne
110
111
 
111
112
  Open `references/nest-compatible/synapse-and-connectivity.md` when selecting a static, special, STP, STDP, or voltage-based synapse; choosing a rule; or inspecting realized edges. Open `references/nest-compatible/devices.md` when selecting a generator, recorder, detector, or result-readback method.
112
113
 
114
+ Open `references/spatial-connectivity.md` before constructing spatial neighborhoods, importing geometric edge lists, or replacing them with a host neighbor-search library; it covers native masks, distance units and topology parity.
115
+
113
116
  ### Simulate and read results
114
117
 
115
118
  `simulate()` starts from freshly initialized State and returns one in-memory `SimulationResult` whose common time axis indexes spike and analog recordings.
@@ -1,6 +1,6 @@
1
1
  # Construct BrainSpike connectivity with Braintools
2
2
 
3
- Use a Braintools connector when geometry or topology selects neuron pairs beyond the native Simulator rules. Keep pair selection, edge ordering, physical weights/delays, and event representation as separate decisions.
3
+ Use a Braintools connector when geometry or topology selects neuron pairs beyond the native Simulator rules. For distance kernels and geometric masks, first open `references/spatial-connectivity.md` to check the BrainSpike spatial rule or explicit-distance path. Keep pair selection, edge ordering, physical weights/delays, and event representation as separate decisions.
4
4
 
5
5
  ## Choose the connection owner
6
6
 
@@ -0,0 +1,53 @@
1
+ # Build spatial connectivity
2
+
3
+ Use positions and a connection rule to select edges; keep topology separate from physical efficacy and from silencing an already connected neuron. These examples target BrainSpikes 0.2.0 in BrainX 2026.10.25.
4
+
5
+ ## Construct a masked Simulator projection
6
+
7
+ The spatial rule owns neighbor selection inside `Simulator.connect`; `p=1` retains every permitted pair within the mask.
8
+
9
+ | API | Description |
10
+ |---|---|
11
+ | `brainspike.spatial.grid(shape, extent=...)` | Create a regular layout; plain extent values use micrometres in this release. |
12
+ | `brainspike.spatial.spatial_pairwise_bernoulli(p, mask=..., allow_autapses=...)` | Select pairs by probability and geometry; use `p=1` for a deterministic neighborhood. |
13
+ | `brainspike.spatial.circular(radius)` | Restrict source-to-target distance; plain radius values use micrometres. |
14
+ | `sim.get_position(population)` | Read physical coordinates to verify the layout. |
15
+ | `sim.get_connections(pre, post)` | Read realized edges to verify direction, source/target indexing and self-edge policy. |
16
+
17
+ ```python
18
+ import brainspike
19
+ import brainstate
20
+ import brainunit as u
21
+
22
+ brainstate.environ.set(precision=64)
23
+ sim = brainspike.Simulator(dt=0.1*u.ms)
24
+ positions = brainspike.spatial.grid([3, 3], extent=[3.0, 3.0])
25
+ neurons = sim.create(brainspike.iaf_psc_alpha, positions=positions)
26
+ sim.connect(
27
+ neurons, neurons,
28
+ rule=brainspike.spatial.spatial_pairwise_bernoulli(
29
+ p=1.0, mask=brainspike.spatial.circular(1.01),
30
+ allow_autapses=False,
31
+ ),
32
+ weight=1.0*u.pA, delay=1.0*u.ms, seed=7,
33
+ )
34
+ coordinates = sim.get_position(neurons)
35
+ edges = sim.get_connections(neurons, neurons)
36
+ assert coordinates.shape == (9, 2)
37
+ assert len(edges) == 24
38
+ ```
39
+
40
+ Convert scientific lengths explicitly at this plain-number boundary, for example `float(radius.to_decimal(u.um))`. Keep weights and delays unit-bearing. Open `references/nest-compatible/scripts/spatial_gaussex.py` for probabilistic Gaussian kernels; their random graphs require distributional checks rather than identical edges from different RNG implementations.
41
+
42
+ ## Import a required explicit topology
43
+
44
+ Use `brainspike.spatial.pairwise_distance(pre_positions, post_positions)` when a native graph or a source-defined model requires explicit pairs. It returns a unit-aware `(pre, post)` distance matrix; apply the declared cutoff and self-edge policy, then preserve paired index order through `brainspike.explicit_edges` or a BrainEvent sparse representation. This dense distance path requires quadratic storage; do not scale it blindly to a large sheet.
45
+
46
+ Before using an external spatial index, check the Simulator mask path and the routed BrainTools connector. Record the actual missing capability or scale constraint. Compare a small deterministic witness for coordinate units, cutoff inclusivity, self-edges, direction and exact edge sets; reusing the same external topology builder in both witnesses does not validate the replacement.
47
+
48
+ Open `references/braintools/connectivity.md` for connector-generated pairs, distance-dependent sampling and edge-value ordering. Open `references/nest-compatible/network-building.md` for spatial APIs and connection inspection. Preserve a fixed graph when testing a silent patch unless rewiring is the declared intervention.
49
+
50
+ ## Official sources
51
+
52
+ - [Spatial network workflow](https://brainx.chaobrain.com/brainspike/nest-style/spatial.html)
53
+ - [Pairwise distance](https://brainx.chaobrain.com/brainspike/apis/generated/brainspike.spatial.pairwise_distance.html)