brainx-skill 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +9 -2
  2. package/adapters/gemini.js +7 -0
  3. package/adapters/opencode.js +7 -0
  4. package/adapters/windsurf.js +7 -0
  5. package/installation/lib/installer.js +4 -1
  6. package/manifest.json +5 -1
  7. package/package.json +7 -2
  8. package/skills/braincell/SKILL.md +182 -0
  9. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  10. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
  11. package/skills/braincell/references/channel-library.md +170 -0
  12. package/skills/braincell/references/ion-library.md +154 -0
  13. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  14. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  15. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  16. package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
  17. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  18. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  19. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  20. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
  21. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  22. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  23. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  24. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  25. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  26. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  27. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  28. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  29. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  30. package/skills/brainevent/SKILL.md +268 -0
  31. package/skills/brainevent/references/connectivity-variants.md +312 -0
  32. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  33. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  34. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  35. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  36. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  37. package/skills/brainevent/references/sparse-formats.md +182 -0
  38. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  39. package/skills/brainpy-state/SKILL.md +232 -0
  40. package/skills/brainpy-state/references/array-creation.md +158 -0
  41. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  42. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  43. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  44. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  45. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  46. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  47. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  48. package/skills/brainpy-state/references/component-selection.md +273 -0
  49. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  50. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  51. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  52. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  53. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  54. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  55. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  56. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  57. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  58. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  59. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  60. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  61. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  62. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  63. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  64. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  65. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  66. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  67. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  68. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  69. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  70. package/skills/brainstate/SKILL.md +1 -1
  71. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
  72. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
  73. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
  74. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
  75. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
  76. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
  77. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
  78. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
  79. package/skills/brainstate/references/collective_model_operations.md +9 -9
  80. package/skills/brainstate/references/extension_mechanisms.md +12 -1
  81. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
  82. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
  83. package/skills/brainstate/references/model-interop-and-migration.md +11 -1
  84. package/skills/brainstate/references/size-inference-variations.md +11 -0
  85. package/skills/brainstate/references/state-graph-operations.md +13 -15
  86. package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
  87. package/skills/brainx-general-guard/SKILL.md +153 -0
  88. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
  89. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
  90. package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
  91. package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
@@ -1,4 +1,4 @@
1
- # Brainstate state-graph operations
1
+ # BrainState state-graph operations
2
2
 
3
3
  Use this reference after the core `State`, `Module`, and transform rules in
4
4
  `SKILL.md`. It covers the less-frequent graph operations needed to find,
@@ -13,6 +13,18 @@ cycles are encoded by integer index rather than duplicated.
13
13
  Source URL:
14
14
  https://brainx.chaobrain.com/brainstate/apis/graph.html
15
15
 
16
+ ## Selection map
17
+
18
+ | Need | Use | Key constraint |
19
+ |---|---|---|
20
+ | Inspect graph paths and live objects | `iter_node()`, `iter_leaf()`, `nodes()`, or `states()` | Filters select by path and value without changing graph structure. |
21
+ | Extract State as a PyTree | `treefy_states()` | No `GraphDef` is returned, so this path alone cannot reconstruct the graph. |
22
+ | Partition State and reconstruct later | `treefy_split()` plus `treefy_merge()` | Preserve the returned `GraphDef` and every matching partition. |
23
+ | Produce the low-level graph representation | `flatten()` plus `unflatten()` | The pair preserves sharing and cycles through graph indices. |
24
+ | Update State values in an existing graph | `update_states()` | This replaces values, not graph nodes. |
25
+ | Remove matching State objects | `pop_states()` | This is destructive. |
26
+ | Move graph nodes through a larger PyTree | `graph_to_tree()` plus `tree_to_graph()` | Preserve each `NodeStates` wrapper. |
27
+
16
28
  ## Find nodes, leaves, and states
17
29
 
18
30
  Use traversal when the path is part of the decision. `iter_node()` yields
@@ -202,17 +214,3 @@ shared index across the related operations. For a deep copy of one graph,
202
214
 
203
215
  Source URL:
204
216
  https://brainx.chaobrain.com/brainstate/apis/graph.html
205
-
206
- ## Selection rules
207
-
208
- - Need paths plus graph objects: `iter_node()`, `iter_leaf()`, `nodes()`, or
209
- `states()`.
210
- - Need only a parameter/state PyTree: `treefy_states()`.
211
- - Need filtered state PyTrees and later reconstruction: `treefy_split()` plus
212
- `treefy_merge()`.
213
- - Need one low-level graph IR and nested state mapping: `flatten()` plus
214
- `unflatten()`.
215
- - Need to update an existing graph: `update_states()`.
216
- - Need destructive removal: `pop_states()`.
217
- - Need graph nodes to cross a larger pytree boundary: `graph_to_tree()` plus
218
- `tree_to_graph()`.
@@ -1,9 +1,20 @@
1
- # Brainstate state collections and utility toolkit
1
+ # BrainState state collections and utility toolkit
2
2
 
3
3
  Use this reference for the collection-focused parts of BrainState's Utility Toolkit: managing mappings, nested configuration, dictionary conversion, immutable structured PyTrees, declarative filters, and readable PyTree containers. These utilities organize data; the core `State` and `Module` programming model remains in the parent `SKILL.md`.
4
4
 
5
5
  Official page: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
6
6
 
7
+ ## Selection map
8
+
9
+ | Need | Use | Key constraint |
10
+ |---|---|---|
11
+ | Filter, split, or transform a mapping | `DictManager` | Operates on collection values; it does not preserve Module graph identity. |
12
+ | Access nested configuration by attribute | `DotDict` | Convert back with `to_dict()` at plain-dictionary boundaries. |
13
+ | Merge or convert dotted-key dictionaries | `merge_dicts`, `flatten_dict`, `unflatten_dict` | Dotted-string keys differ from tuple graph paths. |
14
+ | Keep an immutable structured mapping | `FrozenDict` and related PyTree utilities | Replace values functionally rather than mutating in place. |
15
+ | Build a reusable path/value predicate | `to_predicate`, `OfType`, `WithTag`, `Any`, or `All` | Filters receive both path and value. |
16
+ | Preserve readable nested or flat PyTree containers | `NestedDict`, `FlattedDict`, `PrettyList`, `flat_mapping`, `nest_mapping` | `flat_mapping` uses tuple paths, not dotted strings. |
17
+
7
18
  ## Managing collections with `DictManager`
8
19
 
9
20
  Source URL: https://brainx.chaobrain.com/brainstate/how_to/filter_and_organize_states.html
@@ -0,0 +1,153 @@
1
+ ---
2
+ name: brainx-general-guard
3
+ description: Prevents cross-cutting BrainX misuse and infrastructure mistakes, including wrong package selection, bypassed units, raw JAX transforms on stateful code, and unnecessary custom NumPy/JAX simulations. Use when a request needs BrainX domain routing, safety guardrails, common mistake correction, or confirmation that BrainX APIs should be used.
4
+ ---
5
+
6
+ # brainx-general-guard/
7
+
8
+ ## Concepts
9
+
10
+ • BrainState mental model
11
+ Three nouns carry the whole framework: State, Module, and Transform.
12
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/getting_started/thinking_in_brainstate.html
13
+
14
+ • State-aware transforms
15
+ BrainState transformations mirror JAX’s, but understand State; reads and writes are threaded through compiled functions automatically.
16
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/getting_started/thinking_in_brainstate.html
17
+
18
+ • BrainUnit / BrainCell unit guard
19
+ In braincell, every physical quantity carries an explicit unit; passing a bare number where a quantity is expected raises TypeError.
20
+ **Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/units.html
21
+
22
+ • BrainCell modeling guard
23
+ A mechanism is anything installed on a cell that affects dynamics; in braincell, mechanisms are declarative and describe what to install without touching JAX, time, or runtime state.
24
+ **Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/mechanisms.html
25
+
26
+ https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
27
+
28
+
29
+ ## Conditional reference routing
30
+
31
+ ```text
32
+ brainx-general-guard/
33
+ └── brainstate-randomness-reproducibility/
34
+ └── randomness-and-reproducibility.md
35
+ └── advanced-randomness.md
36
+ ```
37
+
38
+ Open `skills/brainx-install/SKILL.md` only for installation, setup, import errors, backend selection, CUDA/GPU/TPU, JAX device validation, version pinning, or package mismatch. Keep normal modeling tasks from loading install content.
39
+
40
+ Open `skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md` only when the task involves seed control, random trials, stochastic state, dropout/noise, random data, transformed randomness, or reproducibility.
41
+
42
+ Do not open `skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md` directly. The local randomness parent is its only inbound selection route.
43
+
44
+ Keep global BrainX guardrails active: do not invent APIs, prefer official examples, use BrainState transforms for BrainState state, use BrainUnit quantities for physical parameters, and prefer built-ins before custom implementation.
45
+
46
+ Domain routing guard
47
+
48
+ #### Explanation text
49
+
50
+ Route before coding: BrainState for State / Module / Transform, BrainCell for cells / mechanisms / channels / ions, BrainUnit for physical quantities and dimensional safety, BrainMass only when the official task is population / whole-brain mass modeling.
51
+
52
+ Use BrainState JIT for stateful modules
53
+
54
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
55
+
56
+ #### Script
57
+
58
+ ```python
59
+ import jax
60
+ import jax.numpy as jnp
61
+ import brainstate
62
+ class RunningMean(brainstate.nn.Module):
63
+ def __init__(self):
64
+ super().__init__()
65
+ self.sum = brainstate.HiddenState(jnp.array(0.0))
66
+ self.count = brainstate.HiddenState(jnp.array(0))
67
+ def __call__(self, batch: jax.Array) -> jax.Array:
68
+ self.sum.value += jnp.sum(batch)
69
+ self.count.value += batch.size
70
+ return self.sum.value / self.count.value
71
+ tracker = RunningMean()
72
+ @brainstate.transform.jit
73
+ def update_running_mean(batch: jax.Array) -> jax.Array:
74
+ return tracker(batch)
75
+ for step in range(3):
76
+ data = jnp.arange(4.0) + step
77
+ print(f'step {step}: mean={float(update_running_mean(data)):.2f}')
78
+ float(tracker.sum.value), int(tracker.count.value)
79
+ ```
80
+
81
+ #### Explanation text
82
+
83
+ brainstate.transform.jit understands State objects and automatically wires read/write traces into the compiled function; raw jax.jit requires explicitly splitting and merging module state.
84
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
85
+
86
+ Use BrainState loop transforms for stateful loops
87
+
88
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html
89
+
90
+ #### Script
91
+
92
+ ```python
93
+ # Example 2: Stateful for_loop
94
+ class Accumulator(brainstate.nn.Module):
95
+ """Simple accumulator that tracks total and count."""
96
+ def __init__(self):
97
+ super().__init__()
98
+ self.total = brainstate.ShortTermState(jnp.array(0.0))
99
+ self.count = brainstate.ShortTermState(jnp.array(0))
100
+ def process(self, x):
101
+ self.total.value = self.total.value + x
102
+ self.count.value = self.count.value + 1
103
+ return self.total.value / self.count.value # running average
104
+ acc = Accumulator()
105
+ data = jnp.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
106
+ running_averages = for_loop(acc.process, data)
107
+ print("Data:", data)
108
+ print("Running averages:", running_averages)
109
+ print(f"\n Final state: total={acc.total.value}, count={acc.count.value}")
110
+ print(f"Final average: {acc.total.value / acc.count.value}")
111
+ ```
112
+
113
+ #### Explanation text
114
+
115
+ Control-flow APIs in brainstate.transform provide JAX-compatible loops and conditionals while safely handling State objects; loop transformations compile to a single JAX primitive, reducing compilation overhead.
116
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html
117
+
118
+ Use units before biological simulation
119
+
120
+ **Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/units.html
121
+
122
+ #### Script
123
+
124
+ ```python
125
+ import numpy as np
126
+ import jax.numpy as jnp
127
+ import brainunit as u
128
+ v_rest = -65.0 * u.mV # scalar
129
+ dt = 0.1 * u.ms
130
+ lengths = np.array([10.5, 20.0]) * u.um # numpy array
131
+ coords = jnp.zeros((10, 3)) * u.um # JAX array
132
+ radii = [2.0, 3.0, 4.0] * u.um # list
133
+ ```
134
+
135
+ #### Explanation text
136
+
137
+ Silent unit mismatches are one of the most common and hardest-to-find bugs in neural modeling; BrainCell requires units everywhere and catches dimensional errors immediately.
138
+ **Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/units.html
139
+
140
+ ## Common mistakes -> Fix
141
+
142
+ • writing random NumPy simulation code -> route first to BrainState / BrainCell / BrainUnit.
143
+ • using raw jax.jit on stateful BrainState modules -> use brainstate.transform.jit; raw jax.jit requires manual state threading.
144
+ • Python for-loop around state updates when compiling/scanning -> use BrainState scan, for_loop, or control-flow transform.
145
+ • passing bare floats into BrainCell mechanisms -> attach brainunit units.
146
+ • treating BrainCell as generic ODE code -> use cells, ions, channels, mechanisms, and integrators.
147
+ • writing custom ion channel first -> check built-in braincell.channel list first.
148
+ • inventing APIs -> open the official example/source first; do not fabricate a standalone script when no official pattern exists.
149
+ • loading install guidance for ordinary modeling -> use `skills/brainx-install/SKILL.md` only after install/setup/backend/package evidence appears.
150
+
151
+ ## Script references
152
+
153
+ None. This guard has no standalone script reference; its compact guard examples remain inline.
@@ -0,0 +1,303 @@
1
+ # Advanced BrainState RNG reference
2
+
3
+ This is a nested child with exactly one selector: `skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md`. Do not route here directly from a skill, workspace router, index, transform reference, or dynamics reference. Keep the default path compact: seed once, call `brainstate.random`, and let BrainState manage keys automatically.
4
+
5
+ Official anchor phrase: `brainstate.random` provides "a comprehensive set of random number generation functions and utilities for neural network simulations and scientific computing." It includes standard random distributions, random state management with automatic key splitting, seed management utilities, and a NumPy-compatible API.
6
+
7
+ ## 1. Manual key management
8
+
9
+ Official boundary: "For advanced use cases, you can directly access and manipulate keys."
10
+
11
+ Use manual keys only when the task explicitly needs current-key inspection, exact RNG restoration, or parallel key splitting.
12
+
13
+ ```python
14
+ # Get current key
15
+ current_key = brainstate.random.get_key()
16
+ print(f"Current key: {current_key}")
17
+
18
+ # Split key for parallel operations
19
+ keys = brainstate.random.split_key(n=4)
20
+ print(f"\n Split into {len(keys)} keys:")
21
+ for i, key in enumerate(keys):
22
+ print(f" Key {i}: {key}")
23
+ ```
24
+
25
+ ```python
26
+ # Save and restore state
27
+ saved_key = brainstate.random.get_key()
28
+ v1 = brainstate.random.randn(3)
29
+ # Generate more numbers
30
+ v2 = brainstate.random.randn(3)
31
+
32
+ # Restore state
33
+ brainstate.random.set_key(saved_key)
34
+ v3 = brainstate.random.randn(3)
35
+
36
+ print(f"v1: {v1}")
37
+ print(f"v2: {v2}")
38
+ print(f"v3 (restored): {v3}")
39
+ print(f"\n v1 == v3? {jnp.allclose(v1, v3)}")
40
+ ```
41
+
42
+ Related API utilities:
43
+
44
+ - `get_key`: get the current global random key.
45
+ - `set_key`: set a new random key for the global random state.
46
+ - `get_key_data`: get the current global random key as raw `uint32[2]` data.
47
+ - `restore_key`: restore the default random key to its previous state.
48
+ - `split_key`: create new random key(s) from the current seed.
49
+ - `split_keys`: create multiple independent random keys from the current seed.
50
+ - `self_assign_multi_keys`: assign multiple keys to the global random state for parallel access.
51
+
52
+ ## 2. Custom `RandomState` instances / independent streams
53
+
54
+ Official boundary: "For advanced use cases, you can create custom `RandomState` instances with independent random streams."
55
+
56
+ ```python
57
+ # Create custom random generators
58
+ rng1 = brainstate.random.RandomState(42)
59
+ rng2 = brainstate.random.RandomState(123)
60
+
61
+ print("RNG 1:")
62
+ print(rng1)
63
+
64
+ # Generate independent random sequences
65
+ samples1 = rng1.randn(5)
66
+ samples2 = rng2.randn(5)
67
+ print(f"Samples from RNG1: {samples1}")
68
+ print(f"Samples from RNG2: {samples2}")
69
+ print(f"\n Are they different? {not jnp.allclose(samples1, samples2)}")
70
+
71
+ # Re-seed custom RNG
72
+ rng1.seed(999)
73
+ samples3 = rng1.randn(5)
74
+ print(f"\n After re-seeding RNG1 to 999: {samples3}")
75
+ ```
76
+
77
+ Best-practice examples from the RNG tutorial:
78
+
79
+ ```python
80
+ # For data augmentation
81
+ aug_rng = brainstate.random.RandomState(seed=123)
82
+
83
+ # For model initialization
84
+ init_rng = brainstate.random.RandomState(seed=456)
85
+ ```
86
+
87
+ ## 3. Checkpoint RNG save/restore
88
+
89
+ Use this only when exact continuation of a run matters.
90
+
91
+ ```python
92
+ # Save state
93
+ checkpoint = {
94
+ 'model': model.state_dict(),
95
+ 'rng_key': brainstate.random.get_key()
96
+ }
97
+
98
+ # Restore state
99
+ brainstate.random.set_key(checkpoint['rng_key'])
100
+ ```
101
+
102
+ ## 4. Temporary seed contexts and RNG cloning
103
+
104
+ Official API phrases:
105
+
106
+ - `seed_context`: "Context manager for temporary random seed changes with automatic restoration."
107
+ - `default_rng`: "Get the default random state or create a new one with specified seed."
108
+ - `clone_rng`: "Create a clone of the random state or a new random state."
109
+
110
+ The API page’s seed-management example shows a temporary seed context as:
111
+
112
+ ```python
113
+ >>> import brainstate.random as bsr
114
+ >>>
115
+ >>> # Set a global seed
116
+ >>> bsr.seed(42)
117
+ >>>
118
+ >>> # Get current seed/key
119
+ >>> key = bsr.get_key()
120
+ >>>
121
+ >>> # Split the key for parallel operations
122
+ >>> keys = bsr.split_key(n=4)
123
+ >>>
124
+ >>> # Use context manager for temporary seed
125
+ >>> with bsr.local_seed(123):
126
+ ... x = bsr.normal(0, 1, (5,)) # Uses seed 123
127
+ >>> y = bsr.normal(0, 1, (5,)) # Uses original seed
128
+ ```
129
+
130
+ ## 5. Full probability distribution catalog
131
+
132
+ The compact skill lists only everyday functions. Use this catalog when the user asks for specific distributions or API coverage.
133
+
134
+ ### Basic random sampling
135
+
136
+ - `rand`: random values in a given shape.
137
+ - `randn`: sample(s) from the standard normal distribution.
138
+ - `random`, `random_sample`, `ranf`, `sample`: random floats in `[0.0, 1.0)`.
139
+ - `randint`: random integers from low inclusive to high exclusive.
140
+ - `random_integers`: random integers between low and high inclusive.
141
+
142
+ ### Array-like generation: PyTorch compatibility
143
+
144
+ - `rand_like`: similar to `rand_like` in torch.
145
+ - `randint_like`: similar to `randint_like` in torch.
146
+ - `randn_like`: similar to `randn_like` in torch.
147
+
148
+ ### Array manipulation
149
+
150
+ - `choice`: generates a random sample from a given 1-D array.
151
+ - `permutation`: randomly permute a sequence, or return a permuted range.
152
+ - `shuffle`: return a randomly shuffled copy of an array along an axis.
153
+
154
+ ### Continuous distributions
155
+
156
+ - `beta`: draw samples from a Beta distribution.
157
+ - `exponential`, `standard_exponential`: draw samples from an exponential distribution.
158
+ - `gamma`, `standard_gamma`: draw samples from a Gamma distribution.
159
+ - `gumbel`: draw samples from a Gumbel distribution.
160
+ - `laplace`: draw samples from the Laplace or double exponential distribution.
161
+ - `logistic`: draw samples from a logistic distribution.
162
+ - `normal`: draw random samples from a normal/Gaussian distribution.
163
+ - `pareto`: draw samples from a Pareto II or Lomax distribution.
164
+ - `standard_cauchy`: draw samples from a standard Cauchy distribution.
165
+ - `standard_normal`: draw samples from a standard Normal distribution.
166
+ - `standard_t`: draw samples from a standard Student’s t distribution.
167
+ - `uniform`: draw samples from a uniform distribution.
168
+ - `truncated_normal`: sample truncated standard normal random values.
169
+ - `lognormal`, `power`, `rayleigh`, `triangular`, `vonmises`, `wald`, `weibull`, `weibull_min`, `maxwell`, `t`, `loggamma`.
170
+
171
+ ### Discrete distributions
172
+
173
+ - `bernoulli`: sample Bernoulli random values with given shape and mean.
174
+ - `binomial`: draw samples from a binomial distribution.
175
+ - `categorical`: sample random values from categorical distributions.
176
+ - `geometric`, `hypergeometric`, `logseries`, `multinomial`, `negative_binomial`, `poisson`, `zipf`.
177
+
178
+ ### Special distributions
179
+
180
+ - `chisquare`: draw samples from a chi-square distribution.
181
+ - `dirichlet`: draw samples from the Dirichlet distribution.
182
+ - `f`: draw samples from an F distribution.
183
+ - `multivariate_normal`: draw random samples from a multivariate normal distribution.
184
+ - `noncentral_chisquare`, `noncentral_f`, `orthogonal`.
185
+
186
+ ## 6. Distribution visualization
187
+
188
+ Official boundary: visualization belongs in reference/tutorial material. The RNG tutorial introduces it with: "Let’s visualize several distributions."
189
+
190
+ Use the official tutorial section for histogram examples rather than placing plotting code in the compact skill.
191
+
192
+ ## 7. Full practical examples from the RNG tutorial
193
+
194
+ ### Mini-batch sampling
195
+
196
+ ```python
197
+ def create_mini_batches(X, y, batch_size=32, shuffle=True):
198
+ """Create mini-batches for training."""
199
+ n_samples = len(X)
200
+
201
+ # Shuffle indices
202
+ if shuffle:
203
+ indices = brainstate.random.permutation(n_samples)
204
+ else:
205
+ indices = jnp.arange(n_samples)
206
+
207
+ # Create batches
208
+ batches = []
209
+ for start_idx in range(0, n_samples, batch_size):
210
+ end_idx = min(start_idx + batch_size, n_samples)
211
+ batch_indices = indices[start_idx:end_idx]
212
+ batches.append((X[batch_indices], y[batch_indices]))
213
+
214
+ return batches
215
+
216
+ # Generate dummy dataset
217
+ brainstate.random.seed(0)
218
+ X = brainstate.random.randn(100, 10) # 100 samples, 10 features
219
+ y = brainstate.random.randint(0, 2, 100) # Binary labels
220
+ # Create mini-batches
221
+ batches = create_mini_batches(X, y, batch_size=32)
222
+ print(f"Created {len(batches)} mini-batches")
223
+ print(f"First batch shape: X={batches[0][0].shape}, y={batches[0][1].shape}")
224
+ ```
225
+
226
+ ### Dropout layer
227
+
228
+ ```python
229
+ class Dropout(brainstate.nn.Module):
230
+ """Dropout layer with random masking."""
231
+
232
+ def __init__(self, drop_rate=0.5):
233
+ super().__init__()
234
+ self.drop_rate = drop_rate
235
+
236
+ def __call__(self, x):
237
+ fit = brainstate.environ.get('fit', False)
238
+ if not fit:
239
+ return x
240
+ # Generate random mask
241
+ keep_prob = 1.0 - self.drop_rate
242
+ mask = brainstate.random.bernoulli(keep_prob, x.shape)
243
+
244
+ # Apply dropout and scale
245
+ return x * mask / keep_prob
246
+
247
+ # Test dropout
248
+ brainstate.random.seed(42)
249
+ dropout = Dropout(drop_rate=0.3)
250
+
251
+ x = jnp.ones(10)
252
+ y = dropout(x)
253
+
254
+ print(f"Input: {x}")
255
+ print(f"Output: {y}")
256
+ print(f"Zeros: {jnp.sum(y == 0)}/10")
257
+ ```
258
+
259
+ ### Noisy neural network layer
260
+
261
+ ```python
262
+ class NoisyLayer(brainstate.nn.Module):
263
+ """Linear layer with Gaussian noise."""
264
+
265
+ def __init__(self, d_in, d_out, noise_std=0.1):
266
+ super().__init__()
267
+ self.noise_std = noise_std
268
+
269
+ # Parameters with noise
270
+ self.w = brainstate.ParamState(brainstate.random.randn(d_in, d_out) * 0.1)
271
+ self.b = brainstate.ParamState(jnp.zeros(d_out))
272
+ def __call__(self, x):
273
+ # Add weight noise
274
+ w_noisy = self.w.value + brainstate.random.normal(0, self.noise_std, self.w.value.shape)
275
+
276
+ # Forward pass
277
+ return x @ w_noisy + self.b.value
278
+
279
+ # Create and test
280
+ brainstate.random.seed(0)
281
+ layer = NoisyLayer(5, 3, noise_std=0.01)
282
+
283
+ x = jnp.ones(5)
284
+ y1 = layer(x)
285
+ y2 = layer(x) # Different due to noise
286
+ print(f"Output 1: {y1}")
287
+ print(f"Output 2: {y2}")
288
+ print(f"Difference: {y2 - y1}")
289
+ ```
290
+
291
+ ## 8. Reference routing for broader BrainState workflows
292
+
293
+ - Core tutorials: "define states, compose modules and layers, apply the essential transformations, and train a model."
294
+ - Transformations tutorials: "state-aware program transformations, from the essential `jit` / `grad` / `vmap` through advanced batching, error handling, debugging, and intermediate-representation tooling."
295
+ - Brain Dynamics tutorials: "neuron dynamics and numerical integration, synaptic delays, event-driven operators, and spiking neural networks."
296
+
297
+ ## Official BrainX sources
298
+
299
+ - https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
300
+ - https://brainx.chaobrain.com/brainstate/apis/random.html
301
+ - https://brainx.chaobrain.com/brainstate/tutorials/transformations/index.html
302
+ - https://brainx.chaobrain.com/brainstate/tutorials/core/index.html
303
+ - https://brainx.chaobrain.com/brainstate/tutorials/brain_dynamics/index.html
@@ -0,0 +1,62 @@
1
+ # BrainState Randomness and Reproducibility Parent Reference
2
+
3
+ Use this reference when BrainState code needs random numbers, reproducible examples/tests, stochastic masks/noise, seed control, random trials, stochastic state, dropout/noise, RNG under transforms, or a decision between the default BrainState RNG path and advanced key/stream APIs.
4
+
5
+ Usually reached from primary skills only when the task actually involves randomness. Do not load this for ordinary deterministic state, module, training, or BrainCell modeling tasks.
6
+
7
+ ## Parent-reference boundary
8
+
9
+ This is this skill's only first-layer randomness reference. `skills/brainx-general-guard/SKILL.md` routes here. `skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md` is its nested child and has no other selection route.
10
+
11
+ Use `brainstate.random` for BrainState RNG. Official anchor phrase: it "wraps JAX’s random number generation capabilities with a stateful interface that simplifies usage while maintaining reproducibility and performance."
12
+
13
+ ## Core rules
14
+
15
+ - Default path: use `brainstate.random`; BrainState uses automatic key management, so do not manually create/split `jax.random.PRNGKey` unless explicit key control is requested.
16
+ - Reproducibility: call `brainstate.random.seed(seed)` once at the beginning of scripts, notebooks, examples, tests, or reproducible experiments.
17
+ - Global state: all random functions in `brainstate.random` use a global `DEFAULT` instance of `RandomState`.
18
+ - Common functions only: `random`, `rand`, `randn`, `normal`, `uniform`, `randint`, `bernoulli`, `choice`, `permutation`, `shuffle`.
19
+ - Stochastic modules: generate masks/noise inside the stochastic call using `brainstate.random`.
20
+ - Train-only randomness: gate stochastic behavior with training/fit mode; for dropout-style code, use `brainstate.environ.get('fit', False)` and return the input unchanged when not fitting.
21
+
22
+ ## Canonical official workflow
23
+
24
+ ```python
25
+ import brainstate
26
+
27
+ brainstate.random.seed(0)
28
+ x = brainstate.random.normal(0, 1, (100,)) # Keys handled automatically
29
+ ```
30
+
31
+ ## Stochastic-module pattern
32
+
33
+ ```python
34
+ fit = brainstate.environ.get('fit', False)
35
+ if not fit:
36
+ return x
37
+
38
+ keep_prob = 1.0 - drop_rate
39
+ mask = brainstate.random.bernoulli(keep_prob, x.shape)
40
+ return x * mask / keep_prob
41
+ ```
42
+
43
+ For noisy stochastic behavior, generate noise at call time with `brainstate.random.normal(..., shape)`.
44
+
45
+ ## Open the nested child `skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md` for
46
+
47
+ - manual keys: `get_key`, `set_key`, `get_key_data`, `restore_key`, `split_key`, `split_keys`, `self_assign_multi_keys`
48
+ - custom `RandomState` instances or independent streams
49
+ - checkpoint RNG save/restore
50
+ - temporary seed contexts, `default_rng`, or `clone_rng`
51
+ - full probability distribution catalog
52
+ - PyTorch-compatible `rand_like`, `randint_like`, `randn_like`
53
+ - distribution visualization, mini-batch sampling, full dropout/noisy-layer examples
54
+ - RNG combined with transformations, parallelism, or brain-dynamics workflows
55
+
56
+ ## Mirror Source URLs
57
+
58
+ - https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
59
+ - https://brainx.chaobrain.com/brainstate/apis/random.html
60
+ - https://brainx.chaobrain.com/brainstate/tutorials/transformations/index.html
61
+ - https://brainx.chaobrain.com/brainstate/tutorials/core/index.html
62
+ - https://brainx.chaobrain.com/brainstate/tutorials/brain_dynamics/index.html