flysim-malecns: connectome-v1 release
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- CITATION.cff +70 -0
- LICENSE +44 -0
- LICENSE-CODE +32 -0
- README.md +258 -0
- data/connectome-v1/SHA256SUMS +7 -0
- data/connectome-v1/manifest.json +126 -0
- data/connectome-v1/matrix-full.tar.zst +3 -0
- data/connectome-v1/matrix-min10.tar.zst +3 -0
- data/connectome-v1/matrix-min2.tar.zst +3 -0
- data/connectome-v1/matrix-min3.tar.zst +3 -0
- data/connectome-v1/matrix-min5.tar.zst +3 -0
- data/connectome-v1/neurons.parquet +3 -0
- docs/connectome-artifact.md +113 -0
- docs/live-sim.md +141 -0
- figures/chains.png +3 -0
- figures/connectivity.png +3 -0
- figures/culling.png +3 -0
- figures/gate_calibration.png +3 -0
- figures/make_figures.py +434 -0
- figures/neurons.png +3 -0
- figures/speed.png +3 -0
- flysim/.python-version +1 -0
- flysim/LICENSE +32 -0
- flysim/pyproject.toml +65 -0
- flysim/scripts/brian_reference.py +193 -0
- flysim/scripts/connectome_paths.py +75 -0
- flysim/scripts/recalibrated_rule_validation.py +306 -0
- flysim/src/flysim/__init__.py +0 -0
- flysim/src/flysim/artifact.py +140 -0
- flysim/src/flysim/engine/__init__.py +18 -0
- flysim/src/flysim/engine/base.py +84 -0
- flysim/src/flysim/engine/cpu.py +176 -0
- flysim/src/flysim/engine/inputs.py +113 -0
- flysim/src/flysim/engine/kernel.py +447 -0
- flysim/src/flysim/engine/params.py +66 -0
- flysim/src/flysim/live/__init__.py +56 -0
- flysim/src/flysim/live/brain.py +119 -0
- flysim/src/flysim/live/cache.py +211 -0
- flysim/src/flysim/live/model.py +291 -0
- flysim/src/flysim/live/pool.py +314 -0
- flysim/src/flysim/live/service.py +280 -0
- flysim/src/flysim/pipeline/__init__.py +0 -0
- flysim/src/flysim/pipeline/connectome.py +356 -0
- flysim/src/flysim/validation/__init__.py +0 -0
- flysim/src/flysim/validation/cases.json +148 -0
- flysim/src/flysim/validation/chain_controls.json +1 -0
- flysim/src/flysim/validation/chains.py +568 -0
- flysim/src/flysim/validation/culling.py +250 -0
- flysim/src/flysim/validation/engine_check.py +246 -0
- flysim/src/flysim/validation/fafb.py +59 -0
CITATION.cff
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cff-version: 1.2.0
|
| 2 |
+
message: >-
|
| 3 |
+
If you use this dataset, please cite it as below, and also cite the MaleCNS
|
| 4 |
+
connectome (Berg et al. 2026) and the model (Shiu et al. 2024).
|
| 5 |
+
title: "flysim-malecns: a whole-CNS spiking model of the male Drosophila connectome"
|
| 6 |
+
type: dataset
|
| 7 |
+
authors:
|
| 8 |
+
- name: "The flysim-malecns authors"
|
| 9 |
+
version: "connectome-v1"
|
| 10 |
+
date-released: "2026-11-13"
|
| 11 |
+
url: "https://huggingface.co/datasets/nynefold/flysim-malecns"
|
| 12 |
+
repository: "https://huggingface.co/datasets/nynefold/flysim-malecns"
|
| 13 |
+
# DOI: add a "doi:" field here (and in the README's BibTeX) once one is minted after publication.
|
| 14 |
+
license: CC-BY-4.0
|
| 15 |
+
keywords:
|
| 16 |
+
- neuroscience
|
| 17 |
+
- connectomics
|
| 18 |
+
- drosophila
|
| 19 |
+
- spiking neural network
|
| 20 |
+
- leaky integrate-and-fire
|
| 21 |
+
- preregistration
|
| 22 |
+
references:
|
| 23 |
+
- type: article
|
| 24 |
+
title: "Sexual dimorphism in the complete Drosophila male central nervous system connectome"
|
| 25 |
+
authors:
|
| 26 |
+
- family-names: Berg
|
| 27 |
+
given-names: Stuart
|
| 28 |
+
- name: "et al."
|
| 29 |
+
journal: Cell
|
| 30 |
+
volume: 189
|
| 31 |
+
issue: 18
|
| 32 |
+
start: 5504
|
| 33 |
+
end: "5526.e15"
|
| 34 |
+
year: 2026
|
| 35 |
+
doi: 10.1016/j.cell.2026.08.015
|
| 36 |
+
- type: article
|
| 37 |
+
title: "Sexual dimorphism in the complete connectome of the Drosophila male central nervous system"
|
| 38 |
+
authors:
|
| 39 |
+
- family-names: Berg
|
| 40 |
+
given-names: Stuart
|
| 41 |
+
- name: "et al."
|
| 42 |
+
journal: bioRxiv
|
| 43 |
+
year: 2025
|
| 44 |
+
doi: 10.1101/2025.10.09.680999
|
| 45 |
+
- type: article
|
| 46 |
+
title: "A Drosophila computational brain model reveals sensorimotor processing"
|
| 47 |
+
authors:
|
| 48 |
+
- family-names: Shiu
|
| 49 |
+
given-names: Philip K.
|
| 50 |
+
- name: "et al."
|
| 51 |
+
journal: Nature
|
| 52 |
+
volume: 634
|
| 53 |
+
start: 210
|
| 54 |
+
end: 219
|
| 55 |
+
year: 2024
|
| 56 |
+
doi: 10.1038/s41586-024-07763-9
|
| 57 |
+
- type: article
|
| 58 |
+
title: "Brian 2, an intuitive and efficient neural simulator"
|
| 59 |
+
authors:
|
| 60 |
+
- family-names: Stimberg
|
| 61 |
+
given-names: Marcel
|
| 62 |
+
- family-names: Brette
|
| 63 |
+
given-names: Romain
|
| 64 |
+
- family-names: Goodman
|
| 65 |
+
given-names: Dan F. M.
|
| 66 |
+
journal: eLife
|
| 67 |
+
volume: 8
|
| 68 |
+
start: e47314
|
| 69 |
+
year: 2019
|
| 70 |
+
doi: 10.7554/eLife.47314
|
LICENSE
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Creative Commons Attribution 4.0 International (CC BY 4.0)
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 The flysim-malecns authors
|
| 4 |
+
|
| 5 |
+
Scope: everything in this repository except the code. That covers the data in
|
| 6 |
+
data/, the records in records/, the documents in docs/, the figures
|
| 7 |
+
(figures/*.png) and the dataset card (README.md). The code (flysim/,
|
| 8 |
+
workflows/, figures/make_figures.py) is under the MIT licence; see
|
| 9 |
+
LICENSE-CODE.
|
| 10 |
+
|
| 11 |
+
These files are licensed under the Creative Commons Attribution 4.0
|
| 12 |
+
International licence. You may share and adapt them for any purpose, including
|
| 13 |
+
commercially, provided you give appropriate credit, link to the licence, and
|
| 14 |
+
indicate if changes were made.
|
| 15 |
+
|
| 16 |
+
Full licence text: https://creativecommons.org/licenses/by/4.0/legalcode
|
| 17 |
+
Summary: https://creativecommons.org/licenses/by/4.0/
|
| 18 |
+
|
| 19 |
+
---------------------------------------------------------------------------
|
| 20 |
+
Attribution of the source data
|
| 21 |
+
|
| 22 |
+
The data in data/connectome-v1/ is derived from the MaleCNS v1.0 connectome
|
| 23 |
+
by the FlyEM project at Janelia Research Campus (HHMI) and collaborators,
|
| 24 |
+
released under CC BY 4.0 (https://male-cns.janelia.org/). The source tables,
|
| 25 |
+
with their URLs and SHA-256 hashes, are listed in data/connectome-v1/manifest.json.
|
| 26 |
+
Changes made: traced neurons only; edges signed by the presynaptic neuron's
|
| 27 |
+
predicted transmitter; edges from neurons without a fast transmitter omitted;
|
| 28 |
+
packed as a sparse CSC matrix; culled variants by synapse-count threshold.
|
| 29 |
+
See docs/connectome-artifact.md.
|
| 30 |
+
|
| 31 |
+
When you use the data, please cite:
|
| 32 |
+
|
| 33 |
+
Berg, S., Beckett, I. R., Costa, M., et al. Sexual dimorphism in the
|
| 34 |
+
complete Drosophila male central nervous system connectome. Cell 189(18),
|
| 35 |
+
5504-5526.e15 (2026). https://doi.org/10.1016/j.cell.2026.08.015
|
| 36 |
+
|
| 37 |
+
The weight-scale records (records/results/weight-scale*) contain per-cell-type
|
| 38 |
+
summary statistics (neuron counts and median input synapses) that were also
|
| 39 |
+
computed from FAFB / FlyWire tables, as distributed by Shiu et al.
|
| 40 |
+
(https://github.com/philshiu/Drosophila_brain_model) and by the FlyWire
|
| 41 |
+
annotations repository (https://github.com/flyconnectome/flywire_annotations).
|
| 42 |
+
Those sources have their own terms. Check them before reusing these statistics,
|
| 43 |
+
and cite them as well (Dorkenwald et al. 2024 and Schlegel et al. 2024, Nature).
|
| 44 |
+
See records/preregistration.md for the exact sources and commits.
|
LICENSE-CODE
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 The flysim-malecns authors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
| 23 |
+
---------------------------------------------------------------------------
|
| 24 |
+
Scope: this MIT licence covers the code in this repository: flysim/ (except
|
| 25 |
+
flysim/tests/fixtures/shiu/, see below), workflows/ and figures/make_figures.py.
|
| 26 |
+
|
| 27 |
+
flysim/tests/fixtures/shiu/ holds two notebooks vendored unchanged from Shiu et
|
| 28 |
+
al.'s Drosophila_brain_model repository; they keep their own MIT licence
|
| 29 |
+
(copyright the original authors), in flysim/tests/fixtures/shiu/LICENSE.
|
| 30 |
+
|
| 31 |
+
The data in data/ and the written records, documents and figures are under
|
| 32 |
+
CC BY 4.0; see LICENSE.
|
README.md
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-4.0
|
| 3 |
+
pretty_name: "flysim-malecns: a whole-CNS spiking model of the male Drosophila connectome"
|
| 4 |
+
language:
|
| 5 |
+
- en
|
| 6 |
+
tags:
|
| 7 |
+
- neuroscience
|
| 8 |
+
- connectomics
|
| 9 |
+
- drosophila
|
| 10 |
+
- spiking-neural-network
|
| 11 |
+
- connectome
|
| 12 |
+
- biology
|
| 13 |
+
size_categories:
|
| 14 |
+
- 100K<n<1M
|
| 15 |
+
configs:
|
| 16 |
+
- config_name: neurons
|
| 17 |
+
data_files:
|
| 18 |
+
- split: train
|
| 19 |
+
path: data/connectome-v1/neurons.parquet
|
| 20 |
+
default: true
|
| 21 |
+
---
|
| 22 |
+
|
| 23 |
+
# flysim-malecns: a whole-CNS spiking model of the male *Drosophila* connectome
|
| 24 |
+
|
| 25 |
+
This release contains a simulator-ready, hash-checked **signed sparse weight matrix of the complete male fruit-fly central nervous system** (MaleCNS v1.0: 165,122 traced neurons, 24.5 M edges, brain, optic lobes and ventral nerve cord). With it come a fast **leaky integrate-and-fire engine** that reimplements the Shiu et al. (Nature 2024) model, and the **pre-registered validation record** of that engine, failures included. With Brian2's own input trains, the engine reproduces Brian2 **spike for spike** over the whole FAFB brain. Its pre-registered engine check against Brian2 nevertheless recorded a **FAIL**, which a later null test traced to a badly calibrated rule. On MaleCNS, one of three visual-to-descending chains passes its pre-registered test (LC9 → DNp09). None of the culled (pruned) matrices behaves like the full one. The full brain runs at about 1.1 s of wall time per simulated second on one CPU core (provisional).
|
| 26 |
+
|
| 27 |
+
**Status: frozen release.** No further development is planned. Code is MIT; data, records, docs and figures are CC BY 4.0 (see [Licence](#licence)).
|
| 28 |
+
|
| 29 |
+

|
| 30 |
+
|
| 31 |
+
## Contents
|
| 32 |
+
|
| 33 |
+
| Path | What |
|
| 34 |
+
|---|---|
|
| 35 |
+
| `data/connectome-v1/` | `neurons.parquet`, `matrix-{full,min2,min3,min5,min10}.tar.zst`, `manifest.json`, `SHA256SUMS` (106 MB in total) |
|
| 36 |
+
| `flysim/` | The Python package: engine (`flysim.engine`), connectome pipeline (`flysim.pipeline`), artefact download and loader (`flysim.artifact`), validation harnesses (`flysim.validation`), streaming worker (`flysim.live`), tests, scripts. `pyproject.toml` + `uv.lock` |
|
| 37 |
+
| `records/` | The preregistration (`preregistration.md`), the validation log (`validation-log.md`), the results summary (`results-summary.md`), the structural pre-check (`connectome-precheck.md`) and the machine-written reports and per-trial summaries (`results/`). Written during development and edited for publication; see `records/PREFACE.md` |
|
| 38 |
+
| `docs/` | `connectome-artifact.md` (the data format and build rules) and `live-sim.md` (the streaming worker) |
|
| 39 |
+
| `workflows/` | The two GitHub Actions workflows that built the artefact and ran the Brian2 engine check, kept for reference |
|
| 40 |
+
| `figures/` | The figures of this card and `make_figures.py`, which makes them from the files above |
|
| 41 |
+
|
| 42 |
+
## Quick start
|
| 43 |
+
|
| 44 |
+
Download (the tag `connectome-v1` pins this release):
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
hf download nynefold/flysim-malecns --repo-type dataset --revision connectome-v1 --local-dir flysim-malecns
|
| 48 |
+
# or only the code plus one matrix: add --include "flysim/*" "data/connectome-v1/neurons.parquet" \
|
| 49 |
+
# "data/connectome-v1/manifest.json" "data/connectome-v1/SHA256SUMS" "data/connectome-v1/matrix-full.tar.zst"
|
| 50 |
+
cd flysim-malecns/flysim && uv sync
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
Or, from the package alone, fetch one variant with SHA-256 checks. Every file is checked against `SHA256SUMS`, whose own hash is pinned in the code:
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
uv run python -m flysim.artifact fetch --variant full --dest ../data # -> ../data/connectome-v1/
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Load the matrix and run one trial. This is trial 0 of the LC9 chain test at 100 Hz, and it reproduces the recorded result exactly. It takes about 3 s, including JIT compilation:
|
| 60 |
+
|
| 61 |
+
```python
|
| 62 |
+
from pathlib import Path
|
| 63 |
+
|
| 64 |
+
import numpy as np
|
| 65 |
+
import pyarrow.parquet as pq
|
| 66 |
+
from flysim.artifact import load
|
| 67 |
+
from flysim.engine import CpuEngine, ModelParams, SynapseMatrix, poisson_schedule, trial_rng
|
| 68 |
+
from flysim.engine.params import W_SYN_MALE
|
| 69 |
+
|
| 70 |
+
d = Path("../data/connectome-v1")
|
| 71 |
+
c = load(d, "full") # CSC: column j = presynaptic neuron j
|
| 72 |
+
print(c.n, len(c.weights)) # 165122 24539704
|
| 73 |
+
|
| 74 |
+
nrn = pq.read_table(d / "neurons.parquet", columns=["type", "somaSide"]).to_pandas()
|
| 75 |
+
lc9_r = np.flatnonzero((nrn.type == "LC9") & (nrn.somaSide == "R")).astype(np.int32)
|
| 76 |
+
dnp09 = np.flatnonzero(nrn.type == "DNp09")
|
| 77 |
+
|
| 78 |
+
params = ModelParams(w_syn=W_SYN_MALE) # 0.1571 mV per synapse on MaleCNS
|
| 79 |
+
eng = CpuEngine(np.float32) # default kernel: vec
|
| 80 |
+
eng.load(SynapseMatrix.from_connectome(c), params)
|
| 81 |
+
eng.reset() # every trial starts at rest
|
| 82 |
+
rng = trial_rng("chain-tests", "LC9/100Hz", 0) # seed key of chain-test trial 0
|
| 83 |
+
eng.schedule_inputs(poisson_schedule(rng, lc9_r, 100.0, 0, 3000, params.dt)) # 0-300 ms
|
| 84 |
+
eng.advance_to(6000) # 600 ms in 0.1 ms steps
|
| 85 |
+
steps, neurons = eng.spikes_since(0)
|
| 86 |
+
in_window = steps < 3000
|
| 87 |
+
print(int(in_window.sum()), "spikes in 0-300 ms;", # 11039, as in the record
|
| 88 |
+
int(np.isin(neurons[in_window], dnp09).sum()), "from DNp09") # 33
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
The matrix is plain NumPy. Outgoing edges of neuron `j` are `c.indices[c.indptr[j]:c.indptr[j+1]]` (postsynaptic rows), with signed synapse counts `c.weights[...]`. For SciPy: `scipy.sparse.csc_matrix((c.weights, c.indices, c.indptr), shape=(c.n, c.n))` gives `W[post, pre]`.
|
| 92 |
+
|
| 93 |
+
Tests: `uv run pytest -q` (117 tests, about 30 s). Tests on the real connectome use `../data/connectome-v1/`, or `FLYSIM_CONNECTOME` if set, and are skipped if neither has the data.
|
| 94 |
+
|
| 95 |
+
## The data
|
| 96 |
+
|
| 97 |
+
| File | Contents | Size |
|
| 98 |
+
|---|---|---:|
|
| 99 |
+
| `neurons.parquet` | One row per neuron, in matrix order (shown in the viewer) | 3.5 MB |
|
| 100 |
+
| `matrix-full.tar.zst` | All traced → traced edges from signed neurons | 40.7 MB |
|
| 101 |
+
| `matrix-min2.tar.zst` | Edges with ≥ 2 synapses (**failed equivalence**, study only) | 26.0 MB |
|
| 102 |
+
| `matrix-min3.tar.zst` | ≥ 3 (**failed equivalence**, study only) | 18.7 MB |
|
| 103 |
+
| `matrix-min5.tar.zst` | ≥ 5 (**failed equivalence**, study only) | 11.9 MB |
|
| 104 |
+
| `matrix-min10.tar.zst` | ≥ 10 (**failed equivalence**, study only) | 5.7 MB |
|
| 105 |
+
| `manifest.json` | Source URLs and SHA-256 of the input tables, rules, counts, per-array SHA-256 | — |
|
| 106 |
+
| `SHA256SUMS` | File hashes | — |
|
| 107 |
+
|
| 108 |
+
Each matrix archive holds three `.npy` arrays forming a CSC matrix, one column per presynaptic neuron: `indptr` (int64, n + 1), `indices` (int32, postsynaptic rows, ascending within each column) and `weights` (int16, `sign(pre) × synapse_count`). The layout suits event-driven simulation: a step walks only the outgoing edges of the neurons that just spiked. **No weight is trained or fitted.** The global weight scale `w_syn` is a model parameter applied by the engine.
|
| 109 |
+
|
| 110 |
+
`neurons.parquet` columns: `idx`, `bodyId`, `type`, `instance`, `superclass`, `class`, `somaSide`, `rootSide`, `transmitter`, `sign`, `x`, `y`, `z` (voxels of 8 nm, for display only), `pos_source` (0 none, 1 soma, 2 "to soma" location, 3 synapse-weighted mean of partner positions).
|
| 111 |
+
|
| 112 |
+
### Build rules
|
| 113 |
+
|
| 114 |
+
| Step | Rule |
|
| 115 |
+
|---|---|
|
| 116 |
+
| Source | MaleCNS v1.0 flat-connectome tables (annotations, neurotransmitters, weights at `minconf-0.5`), Janelia FlyEM, CC BY 4.0. URLs and SHA-256 in `manifest.json` |
|
| 117 |
+
| Neurons | `status == "Traced"`: 165,122. Never culled, so every variant shares one index |
|
| 118 |
+
| Order | By (superclass, type, bodyId), so cell types sit together |
|
| 119 |
+
| Sign | From the presynaptic `consensus_nt`: ACh +1; GABA, glutamate, histamine −1; anything else 0. Result: 103,718 neurons +1, 57,261 −1, 4,143 zero |
|
| 120 |
+
| Edges | Traced → traced: 25,563,197 edges, 124,025,046 synapses |
|
| 121 |
+
| Omitted | 1,023,493 edges (3.2 M synapses) from sign-0 neurons, which have no fast effect in the model. These neurons still receive input and can spike |
|
| 122 |
+
| Quantization | int16 is lossless (largest count 2,591) |
|
| 123 |
+
| Culling | A variant keeps edges with count ≥ its threshold. Neurons are never removed |
|
| 124 |
+
|
| 125 |
+
| Variant | Edges | Edges kept | Synapses kept | Excitatory / inhibitory edges | In memory |
|
| 126 |
+
|---|---:|---:|---:|---|---:|
|
| 127 |
+
| full | 24,539,704 | 100% | 100% | 14.74 M / 9.80 M | 148.6 MB |
|
| 128 |
+
| min2 | 14,793,713 | 60.3% | 91.9% | 8.98 M / 5.81 M | 90.1 MB |
|
| 129 |
+
| min3 | 10,228,000 | 41.7% | 84.4% | 6.27 M / 3.96 M | 62.7 MB |
|
| 130 |
+
| min5 | 6,093,442 | 24.8% | 72.8% | 3.78 M / 2.32 M | 37.9 MB |
|
| 131 |
+
| min10 | 2,696,623 | 11.0% | 54.6% | 1.69 M / 1.01 M | 17.5 MB |
|
| 132 |
+
|
| 133 |
+
`python -m flysim.pipeline.connectome fetch-raw RAW && ... build RAW OUT` rebuilds the artefact from the public tables. Its checks: a synthetic-data unit test (signs, exclusions, culling, positions, deterministic rebuild); on the real data, summed LC4 → DNp01 and LC9 → DNp09 synapses equal an independent count (6,362 and 1,977); 200 random edges match the raw table; and the CSC structure is checked over every edge. Details: `docs/connectome-artifact.md`.
|
| 134 |
+
|
| 135 |
+

|
| 136 |
+
|
| 137 |
+
## The model and engine
|
| 138 |
+
|
| 139 |
+
The model is Shiu et al.'s leaky integrate-and-fire network (their `model.py`), with the same parameters: rest/reset −52 mV, threshold −45 mV, τm 20 ms, τs 5 ms, refractory 2.2 ms, synaptic delay 1.8 ms, dt 0.1 ms, exact integration, no spontaneous activity. Stimulated neurons get independent Poisson trains (refractory period 0), and each input spike adds 0.275 mV × 250 = 68.75 mV to `v`, so they fire at the input rate. Synaptic input is `w_syn × W[post, pre]`. On MaleCNS, `w_syn` is the FAFB value 0.275 mV divided by the synapse-density ratio R (below). The input weight is not rescaled.
|
| 140 |
+
|
| 141 |
+
`flysim.engine.CpuEngine` is a numba kernel over the CSC matrix, with float32 state (float64 for diagnostics). It has three exact kernels: `plain` (the gated reference), `skip_rest` (visits only neurons off rest) and `vec` (the default: narrow refractory state, vectorized dense sweep). All three give bit-identical spikes and final state on all 1,520 chain-test trials. Seeds come from `SeedSequence(20261103)`, spawned per (experiment, condition, trial), so a trial is a pure function of its key. `flysim.live` runs blocks (one 600 ms chain-test trial each) in 10 ms chunks over a process pool, with a replay cache. It was written for an interactive viewer that is not part of this release; see `docs/live-sim.md`.
|
| 142 |
+
|
| 143 |
+
## Validation (pre-registered)
|
| 144 |
+
|
| 145 |
+
Every rule was committed in `records/preregistration.md` before the runs it judges. Every attempt, failure and decision is in `records/validation-log.md`, in order, under dated headings, and `records/results-summary.md` summarizes them. The machine-written reports in `records/results/` are re-created exactly by the code from the per-trial summaries next to them.
|
| 146 |
+
|
| 147 |
+
### Engine check against Brian2 on FAFB: recorded verdict **FAIL**
|
| 148 |
+
|
| 149 |
+
The pre-registered engine check compared our engine with Shiu et al.'s unmodified `model.py` under Brian2 2.5.1. It covered 17 conditions, with 60 Brian2 trials each, against our first 30 seeds. **Result: FAIL.** 63 of 68 condition checks passed, all 8 direction checks passed, and the cross-check against Shiu's shipped recording passed (validation log, *Engine check, all 17 conditions*, 2026-11-04). This is the recorded verdict, and it stands. We chose to continue with the FAIL on record, so every later result carries it.
|
| 150 |
+
|
| 151 |
+
The evidence that the failures are sampling noise, not an engine difference:
|
| 152 |
+
|
| 153 |
+
- **Replay identity** (validation log, *Engine check, first attempt*, 2026-11-04). Brian2's own Poisson trains, recovered from its output, were fed into our engine. In float64 it was **identical to Brian2 for every spike of every neuron over the full FAFB brain for 1,000 ms, in 30 of 30 trials** (about 17,000 spikes per trial). In the other direction, our trains fed into Brian2 through a `SpikeGeneratorGroup` gave float64 runs identical to ours in 10 of 10 trials. The production float32 build matched the readout's first spike in every trial.
|
| 154 |
+
- **Null test of the rule itself** (validation log, *Validation of the recalibrated rule*, 2026-11-04; exploratory, our engine only). A correct engine judged against itself fails the original pre-registered rule in **92%** of replicates (184/200). Two things cause it: many per-check tolerances are set at the 95th percentile of noise, and the fixed slack on the Jaccard and Spearman similarities is far narrower than their sampling spread when few neurons are active. A recalibrated rule, added to the pre-registration as a disclosed amendment, replaces these with exact permutation tests and a Bonferroni correction. It brings the false-fail rate to **4.5%** (9/200), and still fails **50/50** gates for each of two deliberately broken engines: a refractory-input bug, and all synaptic weights 5% too strong.
|
| 155 |
+
- **Exploratory run under the recalibrated rule**, on fresh seeds and a new Brian2 sample: **PASS**, with 68/68 condition checks, 8/8 direction checks and the cross-check. Under the original rule the same data fails 3 checks, but different ones from the gated run, as sampling noise predicts. This result is reported next to the FAIL, never instead of it.
|
| 156 |
+
- The engine has not changed behaviour since. The two faster kernels added later are bit-identical to the checked kernel on all 1,520 chain-test trials.
|
| 157 |
+
|
| 158 |
+

|
| 159 |
+
|
| 160 |
+
### Weight-scale transfer from FAFB to MaleCNS
|
| 161 |
+
|
| 162 |
+
R is the median, over 4,513 cell types matched between MaleCNS and FAFB v630, of the ratio of mean input synapses per neuron. **R = 1.7505**. This is inside the pre-registered sanity band [1.2, 2.6], so **`w_syn_male` = 0.275 / R = 0.1571 mV**. On FAFB v783, R would be 1.7455 (reported, not used). Record: `records/results/weight-scale.*`, with one row per type.
|
| 163 |
+
|
| 164 |
+
### Chain tests on MaleCNS
|
| 165 |
+
|
| 166 |
+
Poisson input goes into the right-side neurons of a visual population for 300 ms at 25–200 Hz, and descending-neuron readouts are measured. A chain passes if it meets five pre-registered criteria:
|
| 167 |
+
1. the intended readout fires at ≥ 2 Hz;
|
| 168 |
+
2. it fires above the 95th percentile of random-population controls;
|
| 169 |
+
3. its rate rises with the input rate;
|
| 170 |
+
4. the network is quiet after the stimulus;
|
| 171 |
+
5. the intended readout beats the other readouts.
|
| 172 |
+
|
| 173 |
+
| Chain | Result |
|
| 174 |
+
|---|---|
|
| 175 |
+
| LC9 → DNp09 (approach) | **PASS**: 55.3 Hz at 100 Hz input, every criterion met |
|
| 176 |
+
| LC4 → DNp01, giant fiber (escape) | **FAIL**: activity persists after the stimulus (pooled late/early spike ratio 0.0245, limit 0.01) |
|
| 177 |
+
| LC16 → MDN (back away) | **FAIL**: the readout is too weak (0.14 Hz at 100 Hz) and not specific. The pre-registered alternative stimulus (LC16 + LPLC1 + LPLC2) fails the post-stimulus criterion |
|
| 178 |
+
|
| 179 |
+
**Both post-stimulus failures come from the same self-sustaining loop of 49 VNC-side neurons** (19 ascending, 13 VNC motor, 12 VNC intrinsic, and others). Strong giant-fiber drive switches the loop on. It then keeps firing about 550 spikes per 200 ms to the end of the trial, with no readout taking part (validation log, *Chain tests on MaleCNS*, 2026-11-04). Shiu et al.'s FAFB model is brain-only, so it has no VNC that could latch like this.
|
| 180 |
+
|
| 181 |
+

|
| 182 |
+
|
| 183 |
+
### Pruning (culling) equivalence test: **all four culled variants FAIL**
|
| 184 |
+
|
| 185 |
+
Each culled matrix reran every chain-test condition with the same seeds. A variant passes only if every readout rate and latency stays within the noise floor of `full` and every chain keeps its verdict. Even `min2`, which keeps 91.9% of synapses, fails 11 of 97 checks. `min5` flips a verdict: it breaks the VNC loop, so LC4 → DNp01 turns into a PASS. **No culled variant is equivalent to `full`; the culled matrices are provided for study only.** As a diagnostic, not a result: LC9 → DNp09 at 100 Hz stays between 54.4 and 55.4 Hz on every variant.
|
| 186 |
+
|
| 187 |
+

|
| 188 |
+
|
| 189 |
+
### Speed benchmark: **provisional**
|
| 190 |
+
|
| 191 |
+
The pre-registered benchmark needs a target server, and none was set up. These numbers come from a shared 4-vCPU Xeon @ 2.80 GHz dev container, on one thread. The mean over the three chains at 100 Hz is **1.12 s of wall time per simulated second with the `vec` kernel, against 4.86 for `plain`** in a paired run. That is about 0.7 s for a 600 ms whole-CNS trial. The slowest repeat is 1.62 s per simulated second, and peak RSS is about 590 MB per process.
|
| 192 |
+
|
| 193 |
+

|
| 194 |
+
|
| 195 |
+
### Two reproduction traps
|
| 196 |
+
|
| 197 |
+
Both were found in a diagnostic run before the engine check (validation log, *Diagnostic against Shiu's shipped recordings*, 2026-11-03):
|
| 198 |
+
|
| 199 |
+
- **Brian2 drops input to refractory and just-spiked neurons.** `(unless refractory)` puts a conditional write on `v` and `g`, and that write also covers synaptic `on_pre` and `PoissonInput`. The thresholder clears `not_refractory` in the spiking step, even with a refractory period of 0. A reimplementation that only freezes integration, and lets `g` build up during refractoriness, fires up to about 2× faster downstream.
|
| 200 |
+
- **Shiu et al.'s shipped `sugarR.parquet` was run at 200 Hz**, not at the 150 Hz default of `model.py`: its stimulated neurons fire at 191–202 Hz. A comparison against it at 150 Hz fails for reasons unrelated to the engine. The pre-registration was amended before any Brian2 run to cross-check at 200 Hz.
|
| 201 |
+
|
| 202 |
+
## What this release adds
|
| 203 |
+
|
| 204 |
+
This release provides:
|
| 205 |
+
|
| 206 |
+
1. **Whole-brain replay identity**: given the same input trains, the engine matches Brian2 spike for spike over the full FAFB brain for 1 s, in both directions.
|
| 207 |
+
2. **A calibration result for engine-equivalence gates**: the obvious per-check rule fails a correct engine 92% of the time. An exact permutation rule with Bonferroni correction holds about 5%, and still catches a 5% weight error.
|
| 208 |
+
3. **A negative result on pruning**: no synapse-count threshold, even ≥ 2, keeps the network's readouts equivalent to the full matrix.
|
| 209 |
+
4. **The VNC loop**: in a whole-CNS model with Shiu et al.'s parameters, strong giant-fiber drive switches on a self-sustaining loop of 49 VNC-side neurons.
|
| 210 |
+
5. **A published, hash-checked, simulator-ready MaleCNS matrix** with its build rules, plus the preregistration and the validation log, failures included.
|
| 211 |
+
|
| 212 |
+
## Limitations
|
| 213 |
+
|
| 214 |
+
- **Point neurons.** There are no dendrites, gap junctions, neuromodulation, plasticity or spontaneous activity. Every neuron, including the many graded-potential (non-spiking) neurons of the optic lobe and elsewhere, is modelled as a spiking LIF unit.
|
| 215 |
+
- **Parameters fitted to FAFB.** Shiu et al.'s parameters were tuned on the female brain-only FAFB connectome. Here they are carried to a male whole CNS with one global rescaling (R). The VNC and optic lobes are outside what those parameters were tested on.
|
| 216 |
+
- **Machine-predicted transmitters** set every sign (consensus where available). 4,143 neurons with no fast transmitter send no edges.
|
| 217 |
+
- **The engine check's recorded verdict is FAIL** under the original pre-registered rule. The evidence that this is a rule-calibration problem is strong, but it is exploratory.
|
| 218 |
+
- **Only one of three behavioural chains passes.** The chain results test the model's internal consistency with expected anatomy-to-behaviour mappings. They are not a fit to physiology.
|
| 219 |
+
- **Speed figures are provisional** (shared dev container, not the pre-registered target hardware).
|
| 220 |
+
- **Not peer reviewed.** The records were written by the developers during the work.
|
| 221 |
+
|
| 222 |
+
## Software used
|
| 223 |
+
|
| 224 |
+
- [philshiu/Drosophila_brain_model](https://github.com/philshiu/Drosophila_brain_model) at commit `91bdd1e`: Shiu et al.'s original model, run unmodified under [Brian2](https://briansimulator.org/) 2.5.1 as the reference for the engine check.
|
| 225 |
+
|
| 226 |
+
## Licence
|
| 227 |
+
|
| 228 |
+
- **Data** (`data/`): derived from MaleCNS v1.0 by Janelia FlyEM (with Google and collaborators), which is released under CC BY 4.0. The derived matrices and neuron table are released under **CC BY 4.0**. Please cite Berg et al. (below).
|
| 229 |
+
- **Records, docs and figures** (`records/`, `docs/`, `figures/*.png`, this card): **CC BY 4.0**.
|
| 230 |
+
The weight-scale records also contain per-cell-type statistics computed from FAFB / FlyWire tables, which keep their own terms (see `LICENSE`).
|
| 231 |
+
- **Code** (`flysim/`, `workflows/`, `figures/make_figures.py`): **MIT** (`LICENSE-CODE`). The two notebooks in `flysim/tests/fixtures/shiu/` are vendored unchanged from Shiu et al. and keep their own MIT licence.
|
| 232 |
+
|
| 233 |
+
## Citation
|
| 234 |
+
|
| 235 |
+
If you use the data, please cite the connectome:
|
| 236 |
+
|
| 237 |
+
- Berg, S., Beckett, I. R., Costa, M., et al. Sexual dimorphism in the complete *Drosophila* male central nervous system connectome. *Cell* 189(18), 5504–5526.e15 (2026). [doi:10.1016/j.cell.2026.08.015](https://doi.org/10.1016/j.cell.2026.08.015). Preprint: bioRxiv (2025), [doi:10.1101/2025.10.09.680999](https://doi.org/10.1101/2025.10.09.680999).
|
| 238 |
+
|
| 239 |
+
If you use the model or engine, please also cite:
|
| 240 |
+
|
| 241 |
+
- Shiu, P. K., Sterne, G. R., Spiller, N., et al. A *Drosophila* computational brain model reveals sensorimotor processing. *Nature* 634, 210–219 (2024). [doi:10.1038/s41586-024-07763-9](https://doi.org/10.1038/s41586-024-07763-9).
|
| 242 |
+
- Stimberg, M., Brette, R., Goodman, D. F. M. Brian 2, an intuitive and efficient neural simulator. *eLife* 8, e47314 (2019). [doi:10.7554/eLife.47314](https://doi.org/10.7554/eLife.47314).
|
| 243 |
+
|
| 244 |
+
## Citing this dataset
|
| 245 |
+
|
| 246 |
+
```bibtex
|
| 247 |
+
@misc{flysim_malecns_2026,
|
| 248 |
+
title = {flysim-malecns: a whole-CNS spiking model of the male Drosophila connectome},
|
| 249 |
+
author = {{The flysim-malecns authors}},
|
| 250 |
+
year = {2026},
|
| 251 |
+
publisher = {Hugging Face},
|
| 252 |
+
howpublished = {\url{https://huggingface.co/datasets/nynefold/flysim-malecns}},
|
| 253 |
+
url = {https://huggingface.co/datasets/nynefold/flysim-malecns}
|
| 254 |
+
}
|
| 255 |
+
```
|
| 256 |
+
<!-- DOI: add a "doi" field above and to CITATION.cff once one is minted after publication. -->
|
| 257 |
+
|
| 258 |
+
The same entry is in `CITATION.cff`.
|
data/connectome-v1/SHA256SUMS
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
47897de4f124c23d2a60f2c1c83f66e2fed66b9dde68139b18bbad008021e6c0 manifest.json
|
| 2 |
+
e415e795013849e9ee6dff2c9d3caf7109e51a2215b9695980bb97c5b17d1392 matrix-full.tar.zst
|
| 3 |
+
991a49eddf23a4d8b6ae419ba4d8beac7fe54d7c273fd971dc81d3f2ba9714e4 matrix-min10.tar.zst
|
| 4 |
+
f50f01558658ba1137d0e3a9c261732a682e6be7b73b4a0528348245d46d6741 matrix-min2.tar.zst
|
| 5 |
+
5e19ebab9421946ec3a7b27c93d6bbf1f3fc8252dcc9bb654296d88ea4d6fa98 matrix-min3.tar.zst
|
| 6 |
+
1a64a5d061992db61e30ab1f98d63aa07180dc39894cd5101f1bfaed049736d7 matrix-min5.tar.zst
|
| 7 |
+
73c86b24d405622ff39699c45b155bbf2935906fc9f938917954fcca78161166 neurons.parquet
|
data/connectome-v1/manifest.json
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "flysim.connectome/1",
|
| 3 |
+
"dataset": "MaleCNS v1.0",
|
| 4 |
+
"license": "Data: MaleCNS v1.0, FlyEM / Janelia Research Campus, CC-BY 4.0. Cite: Berg, S. et al., Sexual dimorphism in the complete Drosophila male central nervous system connectome, Cell (2026).",
|
| 5 |
+
"sources": {
|
| 6 |
+
"annotations": {
|
| 7 |
+
"url": "https://storage.googleapis.com/flyem-male-cns/v1.0/connectome-data/flat-connectome/body-annotations-male-cns-v1.0-minconf-0.5.feather",
|
| 8 |
+
"sha256": "2177e246113e4cfbf1e7772ec37c6da1955ff22e8063d0b1f833101f99a9a3b2"
|
| 9 |
+
},
|
| 10 |
+
"transmitters": {
|
| 11 |
+
"url": "https://storage.googleapis.com/flyem-male-cns/v1.0/connectome-data/flat-connectome/body-neurotransmitters-male-cns-v1.0.feather",
|
| 12 |
+
"sha256": "95c9289220663abeb3409f3ad9e5a7f8a53f8093f5139d15502cd08da8879621"
|
| 13 |
+
},
|
| 14 |
+
"weights": {
|
| 15 |
+
"url": "https://storage.googleapis.com/flyem-male-cns/v1.0/connectome-data/flat-connectome/connectome-weights-male-cns-v1.0-minconf-0.5.feather",
|
| 16 |
+
"sha256": "e35da783d1c686b2b58b3b87cd6a403ae43bfcfba8bff28e08ef752c1a56afc1"
|
| 17 |
+
}
|
| 18 |
+
},
|
| 19 |
+
"rules": {
|
| 20 |
+
"neurons": "annotations.status == 'Traced'; never culled; same index in every variant",
|
| 21 |
+
"order": "lexicographic (superclass, type, bodyId); missing strings last",
|
| 22 |
+
"sign": "from body-neurotransmitters.consensus_nt of the presynaptic neuron: acetylcholine +1; gaba, glutamate, histamine -1; anything else or missing 0",
|
| 23 |
+
"matrix": "W[post, pre] = sign(pre) * synapse_count; CSC by presynaptic neuron (column = pre, row = post, rows ascending); edges from sign-0 neurons omitted",
|
| 24 |
+
"dtype": "indptr int64, indices int32, weights int16 (lossless)",
|
| 25 |
+
"variants": "keep edges with synapse_count >= min_synapses",
|
| 26 |
+
"weight_scale": "not stored; the engine multiplies by a global w_syn",
|
| 27 |
+
"positions": "somaLocation, else tosomaLocation, else synapse-weighted mean of partner positions (pos_source 3), else NaN; source voxel units"
|
| 28 |
+
},
|
| 29 |
+
"neurons": {
|
| 30 |
+
"count": 165122,
|
| 31 |
+
"sign_counts": {
|
| 32 |
+
"1": 103718,
|
| 33 |
+
"-1": 57261,
|
| 34 |
+
"0": 4143
|
| 35 |
+
},
|
| 36 |
+
"pos_source_counts": {
|
| 37 |
+
"none": 496,
|
| 38 |
+
"soma": 140024,
|
| 39 |
+
"tosoma": 976,
|
| 40 |
+
"partners": 23626
|
| 41 |
+
},
|
| 42 |
+
"file": "neurons.parquet"
|
| 43 |
+
},
|
| 44 |
+
"edges_traced": 25563197,
|
| 45 |
+
"omitted": {
|
| 46 |
+
"edges_from_sign0_neurons": 1023493,
|
| 47 |
+
"synapses_from_sign0_neurons": 3231844
|
| 48 |
+
},
|
| 49 |
+
"variants": {
|
| 50 |
+
"full": {
|
| 51 |
+
"file": "matrix-full.tar.zst",
|
| 52 |
+
"min_synapses": 1,
|
| 53 |
+
"edges": 24539704,
|
| 54 |
+
"edge_fraction": 1.0,
|
| 55 |
+
"synapse_fraction": 1.0,
|
| 56 |
+
"excitatory_edges": 14737539,
|
| 57 |
+
"inhibitory_edges": 9802165,
|
| 58 |
+
"array_sha256": {
|
| 59 |
+
"indptr": "d111310494c41c89fbfbc1bff5f2a95ee17d18a7ce11a62d2eaa8e9faa9b05c7",
|
| 60 |
+
"indices": "def53af8269edfdc130698920ffb0f4cd291ec6d2d227e69a62d3b3d0adf2115",
|
| 61 |
+
"weights": "19c191212168915f5fdc12d4f4e3b2246fd70e4b8984431114ee86d89fbd98f4"
|
| 62 |
+
},
|
| 63 |
+
"file_bytes": 40682941
|
| 64 |
+
},
|
| 65 |
+
"min2": {
|
| 66 |
+
"file": "matrix-min2.tar.zst",
|
| 67 |
+
"min_synapses": 2,
|
| 68 |
+
"edges": 14793713,
|
| 69 |
+
"edge_fraction": 0.6028,
|
| 70 |
+
"synapse_fraction": 0.9193,
|
| 71 |
+
"excitatory_edges": 8983231,
|
| 72 |
+
"inhibitory_edges": 5810482,
|
| 73 |
+
"array_sha256": {
|
| 74 |
+
"indptr": "d6cb014dfe8a76fe0074e45a93841508edde052b70272d3ba121e13ed117f219",
|
| 75 |
+
"indices": "c6d21efd1f856f4f6606943d1142f26792007e94b1a19d16a4a4ff3b47f5f61d",
|
| 76 |
+
"weights": "24541511f963bae9a7902dcca9ac6de0d42087bd0bc524ea326240c1de6c8344"
|
| 77 |
+
},
|
| 78 |
+
"file_bytes": 25954861
|
| 79 |
+
},
|
| 80 |
+
"min3": {
|
| 81 |
+
"file": "matrix-min3.tar.zst",
|
| 82 |
+
"min_synapses": 3,
|
| 83 |
+
"edges": 10228000,
|
| 84 |
+
"edge_fraction": 0.4168,
|
| 85 |
+
"synapse_fraction": 0.8437,
|
| 86 |
+
"excitatory_edges": 6268194,
|
| 87 |
+
"inhibitory_edges": 3959806,
|
| 88 |
+
"array_sha256": {
|
| 89 |
+
"indptr": "b4cc42c83ea8ee93c6f18b130bda7f4a2f1733743f1fe7e99ee17d788a1e1508",
|
| 90 |
+
"indices": "13a002434671fee65586f4cc632ddc5c86e5a37ae5969675ea4df39ae634c6f1",
|
| 91 |
+
"weights": "a3e8c216165f44f5179228b670ee6a62f8c5bba863db092062f179999844f41d"
|
| 92 |
+
},
|
| 93 |
+
"file_bytes": 18696837
|
| 94 |
+
},
|
| 95 |
+
"min5": {
|
| 96 |
+
"file": "matrix-min5.tar.zst",
|
| 97 |
+
"min_synapses": 5,
|
| 98 |
+
"edges": 6093442,
|
| 99 |
+
"edge_fraction": 0.2483,
|
| 100 |
+
"synapse_fraction": 0.7277,
|
| 101 |
+
"excitatory_edges": 3777005,
|
| 102 |
+
"inhibitory_edges": 2316437,
|
| 103 |
+
"array_sha256": {
|
| 104 |
+
"indptr": "e1c83c1c8ef5b5978dda4215522282c0dff4fa74cba796d4aa7993d20c9809c6",
|
| 105 |
+
"indices": "ca6b8a67dd1dc6ad176f7bcfbf6b09b151bdb53e379df241133405ec7c3dd2dc",
|
| 106 |
+
"weights": "867cc2b07b1ba716d9333d00d3a826cc28d40908d1afc1a2ccc1b23d9526e6b1"
|
| 107 |
+
},
|
| 108 |
+
"file_bytes": 11890511
|
| 109 |
+
},
|
| 110 |
+
"min10": {
|
| 111 |
+
"file": "matrix-min10.tar.zst",
|
| 112 |
+
"min_synapses": 10,
|
| 113 |
+
"edges": 2696623,
|
| 114 |
+
"edge_fraction": 0.1099,
|
| 115 |
+
"synapse_fraction": 0.5457,
|
| 116 |
+
"excitatory_edges": 1689817,
|
| 117 |
+
"inhibitory_edges": 1006806,
|
| 118 |
+
"array_sha256": {
|
| 119 |
+
"indptr": "674c5449d7c1df700cc1e192f5df229a916115cea105d6e6c898658f2e7ddd31",
|
| 120 |
+
"indices": "bd15518df15b92209561ccec586c3254ed69a13419a58ba3bae692afd1ee63c0",
|
| 121 |
+
"weights": "d3fd36be7d54eaad029f246201a516b550397a5f81b25dbea5e3b9367fde9d14"
|
| 122 |
+
},
|
| 123 |
+
"file_bytes": 5700852
|
| 124 |
+
}
|
| 125 |
+
}
|
| 126 |
+
}
|
data/connectome-v1/matrix-full.tar.zst
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e415e795013849e9ee6dff2c9d3caf7109e51a2215b9695980bb97c5b17d1392
|
| 3 |
+
size 40682941
|
data/connectome-v1/matrix-min10.tar.zst
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:991a49eddf23a4d8b6ae419ba4d8beac7fe54d7c273fd971dc81d3f2ba9714e4
|
| 3 |
+
size 5700852
|
data/connectome-v1/matrix-min2.tar.zst
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f50f01558658ba1137d0e3a9c261732a682e6be7b73b4a0528348245d46d6741
|
| 3 |
+
size 25954861
|
data/connectome-v1/matrix-min3.tar.zst
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5e19ebab9421946ec3a7b27c93d6bbf1f3fc8252dcc9bb654296d88ea4d6fa98
|
| 3 |
+
size 18696837
|
data/connectome-v1/matrix-min5.tar.zst
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1a64a5d061992db61e30ab1f98d63aa07180dc39894cd5101f1bfaed049736d7
|
| 3 |
+
size 11890511
|
data/connectome-v1/neurons.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:73c86b24d405622ff39699c45b155bbf2935906fc9f938917954fcca78161166
|
| 3 |
+
size 3486135
|
docs/connectome-artifact.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Connectome artefact: MaleCNS v1.0 signed sparse weight matrix
|
| 2 |
+
|
| 3 |
+
This is the input file for the simulation. It is **not trained or fitted**. Every weight is a synapse count from the data multiplied by the presynaptic neuron's sign. The global weight scale is a model parameter that the engine applies, so it is not stored here.
|
| 4 |
+
|
| 5 |
+
- **Published as:** `data/connectome-v1/` of this dataset, at the git tag `connectome-v1`. It was first built on 2026-11-03. The matrices and `neurons.parquet` are byte for byte the files of that build; `manifest.json` was edited for publication (see below).
|
| 6 |
+
- **Built by:** `flysim/src/flysim/pipeline/connectome.py`.
|
| 7 |
+
- **Build workflow:** `workflows/connectome-release.yml`. It ran on GitHub Actions in the development repository and is kept here for reference.
|
| 8 |
+
- **Data licence:** MaleCNS v1.0, FlyEM / Janelia Research Campus, CC BY 4.0. Cite Berg, S. et al., *Cell* (2026).
|
| 9 |
+
|
| 10 |
+
## Get it
|
| 11 |
+
|
| 12 |
+
The files are already in this dataset, under `data/connectome-v1/`. To download one variant with its hash checks from the dataset's `connectome-v1` tag:
|
| 13 |
+
|
| 14 |
+
```bash
|
| 15 |
+
cd flysim && uv sync
|
| 16 |
+
uv run python -m flysim.artifact fetch --variant full --dest ../data # or min2 / min3 / min5 / min10
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
`fetch` checks every file against `SHA256SUMS`, and checks `SHA256SUMS` itself against a hash pinned in the code. Set `HF_TOKEN` if you need authenticated access.
|
| 20 |
+
|
| 21 |
+
```python
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from flysim.artifact import load
|
| 24 |
+
c = load(Path("../data/connectome-v1"), "full")
|
| 25 |
+
j = 0 # presynaptic neuron j
|
| 26 |
+
rows = c.indices[c.indptr[j]:c.indptr[j + 1]] # its postsynaptic targets
|
| 27 |
+
w = c.weights[c.indptr[j]:c.indptr[j + 1]] # signed synapse counts
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
## Files
|
| 31 |
+
|
| 32 |
+
| File | Contents | Size |
|
| 33 |
+
|---|---|---|
|
| 34 |
+
| `neurons.parquet` | One row per neuron (see columns below) | 3.5 MB |
|
| 35 |
+
| `matrix-full.tar.zst` | All traced→traced edges from signed neurons | 40.7 MB |
|
| 36 |
+
| `matrix-min2.tar.zst` | Edges with ≥ 2 synapses | 26.0 MB |
|
| 37 |
+
| `matrix-min3.tar.zst` | ≥ 3 | 18.7 MB |
|
| 38 |
+
| `matrix-min5.tar.zst` | ≥ 5 | 11.9 MB |
|
| 39 |
+
| `matrix-min10.tar.zst` | ≥ 10 | 5.7 MB |
|
| 40 |
+
| `manifest.json` | Source URLs and hashes, rules, counts, per-array SHA-256 | — |
|
| 41 |
+
| `SHA256SUMS` | File hashes, checked by `fetch` | — |
|
| 42 |
+
|
| 43 |
+
**The four culled matrices (`min2` to `min10`) failed the pre-registered pruning-equivalence test**: none of them reproduces the readouts of `full` within its noise floor (see the card and `records/results/culling-equivalence.md`). They are provided for study only. Use `full` for simulation.
|
| 44 |
+
|
| 45 |
+
Each matrix archive holds three `.npy` arrays. Together they form a CSC matrix with one column per presynaptic neuron:
|
| 46 |
+
|
| 47 |
+
| Array | dtype | Length | Contents |
|
| 48 |
+
|---|---|---|---|
|
| 49 |
+
| `indptr` | int64 | n + 1 | Column start offsets |
|
| 50 |
+
| `indices` | int32 | number of edges | Postsynaptic rows, ascending within each column |
|
| 51 |
+
| `weights` | int16 | number of edges | `sign(pre) × synapse_count` |
|
| 52 |
+
|
| 53 |
+
This layout suits an event-driven simulation: each step walks only the outgoing edges of the neurons that just spiked.
|
| 54 |
+
|
| 55 |
+
`neurons.parquet` has one row per neuron, in matrix order. Its columns:
|
| 56 |
+
- `idx`
|
| 57 |
+
- `bodyId`
|
| 58 |
+
- `type`, `instance`, `superclass`, `class`
|
| 59 |
+
- `somaSide`, `rootSide`
|
| 60 |
+
- `transmitter`, `sign`
|
| 61 |
+
- `x`, `y`, `z`
|
| 62 |
+
- `pos_source`, coded as follows:
|
| 63 |
+
|
| 64 |
+
| `pos_source` | Meaning |
|
| 65 |
+
|---|---|
|
| 66 |
+
| 0 | No position |
|
| 67 |
+
| 1 | Soma |
|
| 68 |
+
| 2 | "To soma" location |
|
| 69 |
+
| 3 | Estimated as the synapse-weighted mean of partner positions |
|
| 70 |
+
|
| 71 |
+
Positions are in the source table's voxel units (8 nm), and are meant for display only.
|
| 72 |
+
|
| 73 |
+
## Rules
|
| 74 |
+
|
| 75 |
+
| Step | Rule |
|
| 76 |
+
|---|---|
|
| 77 |
+
| Neurons | `status == "Traced"`, which gives 165,122. Never culled, so every variant uses the same index. |
|
| 78 |
+
| Order | By (superclass, type, bodyId), so cell types sit together. |
|
| 79 |
+
| Sign | From the presynaptic `consensus_nt`: ACh +1; GABA, glutamate, histamine −1; anything else 0. Result: 103,718 neurons +1, 57,261 −1, 4,143 zero. |
|
| 80 |
+
| Edges | Traced → traced: 25,563,197 edges, 124,025,046 synapses. |
|
| 81 |
+
| Omitted | 1,023,493 edges (3.2 M synapses) from sign-0 neurons, which have no fast effect in the model. These neurons still receive input and can spike. |
|
| 82 |
+
| Quantization | int16 is lossless (largest count 2,591). |
|
| 83 |
+
| Culling | A variant keeps edges with count ≥ its threshold, and only edges. Neurons are never removed. |
|
| 84 |
+
|
| 85 |
+
| Variant | Edges | Edges kept | Synapses kept | Excitatory / inhibitory edges | In memory |
|
| 86 |
+
|---|---:|---:|---:|---|---:|
|
| 87 |
+
| full | 24,539,704 | 100% | 100% | 14.74 M / 9.80 M | 148.6 MB |
|
| 88 |
+
| min2 | 14,793,713 | 60.3% | 91.9% | 8.98 M / 5.81 M | 90.1 MB |
|
| 89 |
+
| min3 | 10,228,000 | 41.7% | 84.4% | 6.27 M / 3.96 M | 62.7 MB |
|
| 90 |
+
| min5 | 6,093,442 | 24.8% | 72.8% | 3.78 M / 2.32 M | 37.9 MB |
|
| 91 |
+
| min10 | 2,696,623 | 11.0% | 54.6% | 1.69 M / 1.01 M | 17.5 MB |
|
| 92 |
+
|
| 93 |
+
In memory = edges × 6 bytes (int32 row + int16 weight) + 1.3 MB for `indptr`.
|
| 94 |
+
|
| 95 |
+
Positions: 140,024 come from the soma, 976 from the "to soma" location and 23,626 are estimated from partners; 496 neurons have none.
|
| 96 |
+
|
| 97 |
+
`manifest.json` was edited for publication: its `rules.weight_scale` string no longer cites a section of the development project's internal design notes. Nothing else changed, and `SHA256SUMS` carries the new hash. The current pipeline writes the edited string, so a rebuild reproduces this file.
|
| 98 |
+
|
| 99 |
+
## Rebuilding
|
| 100 |
+
|
| 101 |
+
```bash
|
| 102 |
+
cd flysim
|
| 103 |
+
uv run python -m flysim.pipeline.connectome fetch-raw RAW_DIR # ~1.1 GB of public MaleCNS tables
|
| 104 |
+
uv run python -m flysim.pipeline.connectome build RAW_DIR OUT_DIR
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
## Verification of the build
|
| 108 |
+
- **Unit test:** `flysim/tests/test_connectome.py` checks a synthetic dataset for signs, exclusions, culling, positions and a deterministic rebuild.
|
| 109 |
+
- **Real data:**
|
| 110 |
+
- The summed LC4 → DNp01 and LC9 → DNp09 synapses reproduce an independent structural pre-check (6,362 and 1,977; `records/connectome-precheck.md`).
|
| 111 |
+
- 200 random edges match the raw weights table exactly.
|
| 112 |
+
- The CSC structure (column offsets, row order, sign = neuron sign) is checked over every edge.
|
| 113 |
+
- **The build workflow** rebuilds from the public tables. It can be given the `SHA256SUMS` of a local build, and fails if the hashes differ.
|
docs/live-sim.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Live simulation worker
|
| 2 |
+
|
| 3 |
+
*Engine side of the streaming worker in `flysim.live`. Nothing here is a validation result.*
|
| 4 |
+
|
| 5 |
+
> **Note for this release.** The worker was written for an interactive application (a web app with a 3D view of the brain), which is not part of this release. This document keeps the parts that live in `flysim`: what a block is, the message stream, live or replay, pacing, workers and the cache. The HTTP and WebSocket endpoints, the app settings and the mapping from app inputs to a stimulus were in the application and are left out.
|
| 6 |
+
|
| 7 |
+
The worker runs one stimulus block at a time on the MaleCNS connectome and streams it in 10 ms chunks. Each chunk carries the new spikes and the readout spike counts. Every live block is recorded, and recordings are replayed when the workers are busy or when the same block is asked for again. The client gives the stimulus and the rate explicitly; the stream is a readout only.
|
| 8 |
+
|
| 9 |
+
## Where the code is
|
| 10 |
+
|
| 11 |
+
| Part | Where |
|
| 12 |
+
|---|---|
|
| 13 |
+
| Block definition, stimuli and chain status, the runner | `flysim/src/flysim/live/model.py` |
|
| 14 |
+
| Recordings and the replay cache | `flysim/src/flysim/live/cache.py` |
|
| 15 |
+
| Worker processes, queue, wait estimate | `flysim/src/flysim/live/pool.py` |
|
| 16 |
+
| Live or replay, pacing, message format, settings (`LiveConfig`) | `flysim/src/flysim/live/service.py` |
|
| 17 |
+
| Positions, stimulus targets and readout neurons packed for a 3D view | `flysim/src/flysim/live/brain.py` |
|
| 18 |
+
| Tests | `flysim/tests/test_live.py`, `flysim/tests/test_brain.py` |
|
| 19 |
+
|
| 20 |
+
## What a block is
|
| 21 |
+
A block is exactly one trial of the chain tests (`flysim.validation.chains`):
|
| 22 |
+
- matrix `full` of `connectome-v1` (the only variant that passed the pruning-equivalence test);
|
| 23 |
+
- `CpuEngine(np.float32)` with its default kernel (`vec`, bit for bit equal to the plain kernel on all 1,520 chain-test trials; see `records/results/kernel-check-vec.json`);
|
| 24 |
+
- `ModelParams(w_syn=W_SYN_MALE)`;
|
| 25 |
+
- 600 ms, with Poisson input over [0, 300) ms into the right-side neurons of the stimulus' source types, and nothing after.
|
| 26 |
+
|
| 27 |
+
**Every block starts from rest** (`engine.reset()`). There is no "continuous" option that carries state between blocks. LC4 and LPLC-driven stimuli can switch on a self-sustaining loop of 49 VNC-side neurons, which would otherwise leak into the next block (`records/validation-log.md`: *Chain tests on MaleCNS* and *Decision on the VNC loop*, 2026-11-04).
|
| 28 |
+
|
| 29 |
+
**Seeds** follow the pre-registered seeding rule: `trial_rng(experiment, "<stimulus>/<rate>Hz", seed)`, with experiment `"live"`. With experiment `"chain-tests"`, the same code gives the recorded chain-test trial of that number. The real-connectome test checks this for LC9 at 100 Hz, trial 0: the per-body readout counts and the network spike counts equal the committed `records/results/chain-tests-trials.json`.
|
| 30 |
+
|
| 31 |
+
**Stimuli and chain status**, with their chain-test verdicts:
|
| 32 |
+
|
| 33 |
+
| Stimulus | Chain | Readout | `chain_status` |
|
| 34 |
+
|---|---|---|---|
|
| 35 |
+
| LC4 (55 right-side neurons) | escape | DNp01 | `not_validated` (FAIL: activity persists after the stimulus) |
|
| 36 |
+
| LC16 (94) | back away | MDN | `not_validated` (FAIL: readout too weak and not specific; the pre-registered alternative stimulus fails the post-stimulus criterion) |
|
| 37 |
+
| LC9 (115) | approach | DNp09 | `validated` (PASS) |
|
| 38 |
+
|
| 39 |
+
The worker simulates all three. Every message carries `chain_status`, so a client can say when a readout is not a validated response. The alternative stimulus LC16 + LPLC1 + LPLC2 is not offered.
|
| 40 |
+
|
| 41 |
+
## Using it from Python
|
| 42 |
+
`LiveService(source, LiveConfig(...))` with `source = ConnectomeSource(Path("data/connectome-v1"), unpack_dir=...)`. `service.start()` spawns the workers; `service.info()` lists the stimuli, bounds and defaults; `service.stream(BlockRequest(stimulus, rate_hz, seed, min_stretch=None))` is an async iterator of JSON-ready dicts, one per message; `service.close()` stops the pool. A request is the equivalent of this JSON:
|
| 43 |
+
|
| 44 |
+
```json
|
| 45 |
+
{"stimulus": "LC9", "rate_hz": 100, "seed": 0, "min_stretch": 6.0}
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
- `stimulus` is `LC4`, `LC16` or `LC9`.
|
| 49 |
+
- `rate_hz` is in [0, 200].
|
| 50 |
+
- `seed` is in [0, 2³¹ − 1]. A caller that wants a fresh run picks a fresh seed; the same seed repeats a block exactly (and then replays from the cache).
|
| 51 |
+
- `min_stretch` is optional, in [1, 100]; it defaults to `LiveConfig.min_stretch`.
|
| 52 |
+
|
| 53 |
+
For a single block without the pool, `run_block(make_engine(matrix), LiveModel.build(neurons), BlockSpec(stimulus, rate_hz, seed), experiment)` yields the chunks directly (this is what the real-connectome test does).
|
| 54 |
+
|
| 55 |
+
## Message format
|
| 56 |
+
Each message is a JSON-ready dict. All messages of a block share these fields:
|
| 57 |
+
|
| 58 |
+
| Field | Meaning |
|
| 59 |
+
|---|---|
|
| 60 |
+
| `type` | `queued`, `start`, `chunk`, `end` or `error` |
|
| 61 |
+
| `run` | id of this stream |
|
| 62 |
+
| `source` | `live` or `replay` |
|
| 63 |
+
| `stimulus`, `chain`, `readout` | e.g. `LC9`, `approach`, `DNp09` |
|
| 64 |
+
| `chain_status` | `validated` or `not_validated` |
|
| 65 |
+
|
| 66 |
+
A block arrives in this order:
|
| 67 |
+
1. **`queued`** (live only): `queue_position` (blocks waiting, this one included) and `expected_wait_s` (`null` while no worker is ready).
|
| 68 |
+
2. **`start`**, which describes the block:
|
| 69 |
+
- `replay_reason`: `null` for a live block, `"repeat"` or `"busy"` for a replay;
|
| 70 |
+
- `rate_hz`, the rounded rate that runs, and `rate_hz_requested`;
|
| 71 |
+
- `seed`, the seed that runs (a busy replay may use another one), and `seed_requested`;
|
| 72 |
+
- `status_basis`, the chain-test verdict behind `chain_status` (a short string that cites the record);
|
| 73 |
+
- `block`: `dt_ms` 0.1, `steps` 6000, `chunk_steps` 100, `chunks` 60, `duration_ms` 600, `stimulus_ms` [0, 300], `starts_from_rest` true;
|
| 74 |
+
- `n_neurons`;
|
| 75 |
+
- `readouts`: the sides of each readout, e.g. `{"DNp01": ["L", "R"], ...}`;
|
| 76 |
+
- `pacing`: `stretch`, `min_stretch`, `compute_ratio`, `margin`.
|
| 77 |
+
3. **`chunk`**, 60 times:
|
| 78 |
+
- `index` (0–59), `t0_ms`, `t1_ms`;
|
| 79 |
+
- `neurons`: the neuron indices that spiked in the chunk, in time order (row order of `neurons.parquet`);
|
| 80 |
+
- `steps`: each spike's step within the chunk (0–99, in 0.1 ms);
|
| 81 |
+
- `readouts`: spike counts in this chunk per readout and side, e.g. `{"DNp01": {"L": 0, "R": 2}, "MDN": {...}, "DNp09": {...}}`.
|
| 82 |
+
4. **`end`**:
|
| 83 |
+
- `summary`: total spikes; spikes in the stimulus window; and readout counts per side over the stimulus window (`readouts_stimulus`) and the whole block (`readouts_block`);
|
| 84 |
+
- `compute_s` and `compute_ratio` of the live run. A replay repeats the recorded values.
|
| 85 |
+
|
| 86 |
+
An **`error`** message has `detail` instead, plus the common fields when the request was valid.
|
| 87 |
+
|
| 88 |
+
For size: LC9 at 100 Hz has about 11.5k spikes per block, and the whole stream is about 125 kB of JSON.
|
| 89 |
+
|
| 90 |
+
## Live or replay
|
| 91 |
+
In this order:
|
| 92 |
+
1. If a recording of exactly this (stimulus, rounded rate, seed) exists, it is replayed (`"repeat"`). A block is a pure function of that key, so the replay is the same computation. `serve_repeats=False` turns this off.
|
| 93 |
+
2. Otherwise, if a new block would wait at most `max_wait_s` (2 s) for a worker, it runs live.
|
| 94 |
+
3. Otherwise a recording of the same stimulus and rounded rate is replayed (`"busy"`): the requested seed if it is stored, else the lowest stored seed. `start.seed` says which seed plays.
|
| 95 |
+
4. With no recording to fall back on, the block is queued live anyway. If `max_queue` blocks are already waiting, it is refused instead.
|
| 96 |
+
|
| 97 |
+
**Rate rounding.** Requested rates are rounded to `rate_step_hz` (5 Hz), and both live runs and replays use the rounded rate. A recording is therefore always exactly the live block its key names.
|
| 98 |
+
|
| 99 |
+
**Wait estimate** (`flysim.live.pool.expected_wait`). Every block is assumed to take the current estimate of block compute time. That estimate starts at `compute_ratio_prior` × 0.6 s (1.12, the provisional figure of the `vec` kernel) and then follows an exponential moving average (α 0.3) of measured blocks. Running blocks finish at start + estimate. Queued blocks go, first in first out, to the worker that frees up first. The wait is the time until the earliest worker frees up after that. Before any worker has loaded, the wait is infinite, so a recording is replayed if one exists, and otherwise the block waits for the load.
|
| 100 |
+
|
| 101 |
+
## Pacing (time stretch)
|
| 102 |
+
`stretch = max(min_stretch, measured_compute_ratio × 1.2)`, so compute stays ahead of display and a run streams while it is calculated:
|
| 103 |
+
- **The worker does not pace.** It sends each chunk as soon as it is computed, so the stream runs ahead of the display.
|
| 104 |
+
- **The display applies the stretch.** `start.pacing.stretch` uses the pool's estimated compute ratio at the moment the block starts. The display shows simulated time *t* at wall time *t* × `stretch` after it starts the block. Because the estimate includes the 1.2 margin, chunks normally arrive before they are due. If one is late, the display waits for it.
|
| 105 |
+
- **Replays** have no compute to wait for. Their stretch is `min_stretch`.
|
| 106 |
+
|
| 107 |
+
`min_stretch` defaults to 4.0, a display choice: a 600 ms block then plays over 2.4 s. With the `vec` kernel the compute ratio is about 1.1 on the dev container (1.3 with the margin), so `min_stretch` sets the pace.
|
| 108 |
+
|
| 109 |
+
## Workers, memory, cache
|
| 110 |
+
- **Processes.** The pool is `workers` processes, started with `spawn`. Each loads the matrix once, builds one engine, compiles the kernel with a 10 ms warm-up, and then takes blocks from a shared queue: one block per process at a time. After each chunk, the worker sends it to the parent process.
|
| 111 |
+
- A worker that dies fails its block and is replaced.
|
| 112 |
+
- When no worker can load (for example, missing data), every waiting block fails, and the service reports live runs as unavailable.
|
| 113 |
+
- **Memory.** With `unpack_dir` set, the matrix is unpacked once to `.npy` files there, about 142 MB. Every worker then maps them read-only, so the pages are shared. A worker's RSS was about 250 MB with the mapped matrix touched, where the speed benchmark measured a 590 MB peak when each process decompresses its own copy.
|
| 114 |
+
- **Cache.** Every live block is recorded by its worker, even if the client has gone. A recording holds the spikes and the per-chunk readout counts in a compressed `.npz` file of about 29 kB for LC9 at 100 Hz. It is stored as `<cache_dir>/recordings/<fingerprint>/<stimulus>_<rate>Hz_s<seed>.npz` and written atomically.
|
| 115 |
+
- The fingerprint covers the matrix and neuron hashes from `SHA256SUMS`, the model parameters, the block layout, the seeding experiment and a format number. A change to any of them starts a fresh cache.
|
| 116 |
+
- A damaged file counts as a miss.
|
| 117 |
+
- The cache is bounded by `cache_max_bytes` (default 1 GiB, about 35,000 recordings). After each write, recordings of other fingerprints go first (they can never replay), then the least recently used of the current one; a replay counts as a use.
|
| 118 |
+
|
| 119 |
+
## Settings (`LiveConfig`)
|
| 120 |
+
`workers` (default 1; 0 = replay only), `cache_dir`, `unpack_dir`, `min_stretch` (4.0), `max_wait_s` (2.0), `rate_step_hz` (5.0), `compute_ratio_prior` (1.12), `cache_max_bytes` (1 GiB), `stretch_margin` (1.2), `serve_repeats` (true), `max_queue` (8), `event_timeout_s` (120), `experiment` (`"live"`).
|
| 121 |
+
|
| 122 |
+
## Tests
|
| 123 |
+
- **Synthetic network** (40 neurons; no download):
|
| 124 |
+
- stimuli, statuses and block constants;
|
| 125 |
+
- the stimulus targets (right side) and readout slots;
|
| 126 |
+
- request validation and rate rounding;
|
| 127 |
+
- chunked stepping gives the same spikes as one whole-trial run on the plain kernel;
|
| 128 |
+
- readout counts match the spikes, and there is no input after 300 ms;
|
| 129 |
+
- every block starts from rest (a block after another block repeats exactly);
|
| 130 |
+
- recording round trip, cache keys and fingerprints, busy fallback to another seed, damaged files;
|
| 131 |
+
- `expected_wait` cases;
|
| 132 |
+
- a real spawned worker process streams the same chunks as an in-process run, writes the cache and updates the estimate;
|
| 133 |
+
- a worker that cannot load fails its block;
|
| 134 |
+
- the service: live, then a repeat replay with identical chunks; busy fallback; queue-anyway; refused requests.
|
| 135 |
+
- **Brain layout** (`flysim/tests/test_brain.py`): a small table packed and decoded (bounds, a missing position, region codes, stimulus targets, readout sides, the ETag following the checksums), quantization within half a step, and the real layout (165,122 neurons, 496 without a position).
|
| 136 |
+
- **Real connectome** (uses `data/connectome-v1/` of this dataset, or set `FLYSIM_CONNECTOME`; skipped if absent): a live block under the chain-test seed key reproduces the committed chain-test record for LC9 at 100 Hz, trial 0.
|
| 137 |
+
|
| 138 |
+
## Engine API
|
| 139 |
+
The runner uses `reset`, `schedule_inputs`, `advance_to` and `spikes_since` only. Two small points:
|
| 140 |
+
- `reset()` reallocates the state arrays every block (a few MB, negligible).
|
| 141 |
+
- The spike log grows over the whole block, though the runner only reads the last chunk.
|
figures/chains.png
ADDED
|
Git LFS Details
|
figures/connectivity.png
ADDED
|
Git LFS Details
|
figures/culling.png
ADDED
|
Git LFS Details
|
figures/gate_calibration.png
ADDED
|
Git LFS Details
|
figures/make_figures.py
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.12"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "matplotlib==3.10.7",
|
| 5 |
+
# "numpy==2.3.4",
|
| 6 |
+
# "pyarrow==21.0.0",
|
| 7 |
+
# "zstandard==0.25.0",
|
| 8 |
+
# ]
|
| 9 |
+
# ///
|
| 10 |
+
"""Make the figures of the dataset card from this release's own data and records.
|
| 11 |
+
|
| 12 |
+
uv run figures/make_figures.py # from the dataset root; writes figures/*.png
|
| 13 |
+
|
| 14 |
+
Inputs: data/connectome-v1/ (neurons.parquet, manifest.json, matrix-full.tar.zst) and
|
| 15 |
+
records/ (results/*.json, results/culling-equivalence.md). The numbers of the gate null test are
|
| 16 |
+
quoted from records/validation-log.md (entry *Validation of the recalibrated rule*,
|
| 17 |
+
2026-11-04), which is text only.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import io
|
| 23 |
+
import json
|
| 24 |
+
import re
|
| 25 |
+
import tarfile
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import matplotlib
|
| 29 |
+
|
| 30 |
+
matplotlib.use("Agg")
|
| 31 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 32 |
+
import numpy as np # noqa: E402
|
| 33 |
+
import pyarrow.parquet as pq # noqa: E402
|
| 34 |
+
import zstandard # noqa: E402
|
| 35 |
+
|
| 36 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 37 |
+
DATA = ROOT / "data" / "connectome-v1"
|
| 38 |
+
RES = ROOT / "records" / "results"
|
| 39 |
+
OUT = ROOT / "figures"
|
| 40 |
+
DPI = 200 # figures are laid out at 100 px per inch, so this is 2x
|
| 41 |
+
|
| 42 |
+
# Palette (validated: first three categorical slots, all pairs, light surface)
|
| 43 |
+
SURFACE = "#fcfcfb"
|
| 44 |
+
INK = "#0b0b0b"
|
| 45 |
+
INK2 = "#52514e"
|
| 46 |
+
MUTED = "#898781"
|
| 47 |
+
GRID = "#e1e0d9"
|
| 48 |
+
AXIS = "#c3c2b7"
|
| 49 |
+
BLUE, ORANGE, AQUA = "#2a78d6", "#eb6834", "#1baf7a" # blue, orange, aqua
|
| 50 |
+
OTHER = "#b9b8b1"
|
| 51 |
+
EXC, INH = "#2a78d6", "#e34948" # diverging pair: blue <-> red
|
| 52 |
+
GOOD, CRIT = "#0ca30c", "#d03b3b" # status: pass / fail (always with a text label)
|
| 53 |
+
|
| 54 |
+
plt.rcParams.update({
|
| 55 |
+
"figure.facecolor": SURFACE, "axes.facecolor": SURFACE, "savefig.facecolor": SURFACE,
|
| 56 |
+
"font.family": "sans-serif", "font.size": 10, "text.color": INK,
|
| 57 |
+
"axes.edgecolor": AXIS, "axes.linewidth": 0.8, "axes.labelcolor": INK2,
|
| 58 |
+
"axes.titlesize": 11, "axes.titleweight": "bold", "axes.titlelocation": "left",
|
| 59 |
+
"axes.spines.top": False, "axes.spines.right": False,
|
| 60 |
+
"axes.grid": True, "axes.axisbelow": True, "grid.color": GRID, "grid.linewidth": 0.6,
|
| 61 |
+
"xtick.color": MUTED, "ytick.color": MUTED, "xtick.labelcolor": INK2,
|
| 62 |
+
"ytick.labelcolor": INK2, "legend.frameon": False, "lines.linewidth": 2,
|
| 63 |
+
})
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def save(fig: plt.Figure, name: str) -> None:
|
| 67 |
+
fig.savefig(OUT / name, dpi=DPI, bbox_inches="tight", pad_inches=0.15)
|
| 68 |
+
plt.close(fig)
|
| 69 |
+
print("wrote", OUT / name)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ----------------------------------------------------------------------------- neurons
|
| 73 |
+
|
| 74 |
+
REGION = [ # (label, colour, superclass prefixes); intrinsic, sensory and motor alike
|
| 75 |
+
("Optic lobe", BLUE, ("ol_", "visual_")),
|
| 76 |
+
("Central brain", ORANGE, ("cb_",)),
|
| 77 |
+
("Ventral nerve cord", AQUA, ("vnc_",)),
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def fig_neurons() -> None:
|
| 82 |
+
t = pq.read_table(DATA / "neurons.parquet", columns=["superclass", "x", "y", "z"])
|
| 83 |
+
sc = np.array([s or "" for s in t["superclass"].to_pylist()])
|
| 84 |
+
x, y, z = (t[c].to_numpy(zero_copy_only=False) for c in "xyz")
|
| 85 |
+
ok = np.isfinite(x)
|
| 86 |
+
group = np.full(len(sc), -1)
|
| 87 |
+
for g, (_, _, prefixes) in enumerate(REGION):
|
| 88 |
+
for prefix in prefixes:
|
| 89 |
+
group[np.char.startswith(sc, prefix)] = g
|
| 90 |
+
n_other = int(np.sum(ok & (group == -1)))
|
| 91 |
+
|
| 92 |
+
xr = np.nanmax(x) - np.nanmin(x)
|
| 93 |
+
zr = np.nanmax(z) - np.nanmin(z)
|
| 94 |
+
fig, axes = plt.subplots(1, 2, figsize=(12.5, 5.0), gridspec_kw={"width_ratios": [xr, zr]})
|
| 95 |
+
views = [("Front view (x, y)", x, y), ("Side view (z, y)", z, y)]
|
| 96 |
+
for ax, (title, h, v) in zip(axes, views, strict=True):
|
| 97 |
+
for g, (_, colour, _) in enumerate(REGION):
|
| 98 |
+
m = ok & (group == g)
|
| 99 |
+
ax.scatter(h[m], v[m], s=0.25, c=colour, alpha=0.35, lw=0, rasterized=True)
|
| 100 |
+
m = ok & (group == -1) # the small group goes on top, so it stays visible
|
| 101 |
+
ax.scatter(h[m], v[m], s=0.8, c="#5f5e5a", alpha=0.6, lw=0, rasterized=True)
|
| 102 |
+
ax.set_aspect("equal")
|
| 103 |
+
ax.invert_yaxis() # y grows ventrally in the source volume
|
| 104 |
+
ax.set_title(title)
|
| 105 |
+
ax.set_xlabel("voxels (8 nm)")
|
| 106 |
+
ax.grid(False)
|
| 107 |
+
ax.tick_params(labelsize=8)
|
| 108 |
+
axes[0].set_ylabel("y, voxels (8 nm)")
|
| 109 |
+
handles = [plt.Line2D([], [], ls="", marker="o", ms=7, color=c,
|
| 110 |
+
label=f"{lbl} ({int(np.sum(ok & (group == g))):,})")
|
| 111 |
+
for g, (lbl, c, _) in enumerate(REGION)]
|
| 112 |
+
handles.append(plt.Line2D([], [], ls="", marker="o", ms=7, color="#5f5e5a",
|
| 113 |
+
label=f"Ascending, descending, efferent, unlabelled ({n_other:,})"))
|
| 114 |
+
fig.legend(handles=handles, loc="lower center", ncol=4, fontsize=9,
|
| 115 |
+
bbox_to_anchor=(0.5, -0.02), handletextpad=0.2, columnspacing=1.2)
|
| 116 |
+
fig.suptitle(f"MaleCNS v1.0: {int(ok.sum()):,} traced neurons with a position, by superclass",
|
| 117 |
+
x=0.01, ha="left", fontsize=12, fontweight="bold")
|
| 118 |
+
fig.text(0.01, 0.905, "Soma position, else 'to soma' location, else the synapse-weighted "
|
| 119 |
+
"mean of partner positions. 496 neurons have no position.",
|
| 120 |
+
fontsize=9, color=INK2)
|
| 121 |
+
fig.subplots_adjust(top=0.82, bottom=0.2, left=0.07, right=0.99, wspace=0.1)
|
| 122 |
+
save(fig, "neurons.png")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# ----------------------------------------------------------------------------- matrix
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def load_full() -> dict[str, np.ndarray]:
|
| 129 |
+
raw = (DATA / "matrix-full.tar.zst").read_bytes()
|
| 130 |
+
tar_bytes = zstandard.ZstdDecompressor().decompress(raw, max_output_size=1 << 32)
|
| 131 |
+
arrays = {}
|
| 132 |
+
with tarfile.open(fileobj=io.BytesIO(tar_bytes)) as tar:
|
| 133 |
+
for member in tar.getmembers():
|
| 134 |
+
f = tar.extractfile(member)
|
| 135 |
+
assert f is not None
|
| 136 |
+
arrays[member.name.removesuffix(".npy")] = np.load(io.BytesIO(f.read()))
|
| 137 |
+
return arrays
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def int_log_hist(values: np.ndarray, top: int, n: int = 60) -> tuple[np.ndarray, np.ndarray]:
|
| 141 |
+
"""Histogram of positive integers in log-spaced integer bins [a, b): bin centres
|
| 142 |
+
(geometric mean of the integers a..b-1) and counts per integer value."""
|
| 143 |
+
edges = np.unique(np.round(np.logspace(0, np.log10(top + 1), n)).astype(int))
|
| 144 |
+
h, e = np.histogram(values, bins=edges)
|
| 145 |
+
centre = np.sqrt(e[:-1] * (e[1:] - 1))
|
| 146 |
+
dens = h / np.diff(e)
|
| 147 |
+
keep = dens > 0
|
| 148 |
+
return centre[keep], dens[keep]
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def fig_connectivity() -> None:
|
| 152 |
+
a = load_full()
|
| 153 |
+
w = a["weights"].astype(np.int32)
|
| 154 |
+
n_syn = np.abs(w)
|
| 155 |
+
out_deg = np.diff(a["indptr"])
|
| 156 |
+
in_deg = np.bincount(a["indices"], minlength=len(out_deg))
|
| 157 |
+
exc, inh = w > 0, w < 0
|
| 158 |
+
|
| 159 |
+
fig, axes = plt.subplots(1, 2, figsize=(11, 4.4))
|
| 160 |
+
ax = axes[0]
|
| 161 |
+
top = int(n_syn.max())
|
| 162 |
+
for mask, colour, label in ((exc, EXC, "excitatory (ACh)"),
|
| 163 |
+
(inh, INH, "inhibitory (GABA, Glu, His)")):
|
| 164 |
+
ax.plot(*int_log_hist(n_syn[mask], top), color=colour, label=label)
|
| 165 |
+
ax.set_xscale("log")
|
| 166 |
+
ax.set_yscale("log")
|
| 167 |
+
ax.set_xlabel("synapses per edge")
|
| 168 |
+
ax.set_ylabel("edges per synapse-count value")
|
| 169 |
+
ax.set_title("Edge weights, full matrix")
|
| 170 |
+
ax.legend(fontsize=9, loc="upper right")
|
| 171 |
+
e_share = exc.sum() / len(w)
|
| 172 |
+
s_share = n_syn[exc].sum() / n_syn.sum()
|
| 173 |
+
ax.text(0.0, -0.2,
|
| 174 |
+
f"{len(w) / 1e6:.2f} M edges, {n_syn.sum() / 1e6:.1f} M synapses "
|
| 175 |
+
"(sign-0 senders omitted)\n"
|
| 176 |
+
f"excitatory: {e_share:.1%} of edges, {s_share:.1%} of synapses\n"
|
| 177 |
+
f"{np.mean(n_syn == 1):.1%} of edges are a single synapse; max {top:,}",
|
| 178 |
+
transform=ax.transAxes, fontsize=8.5, color=INK2, va="top")
|
| 179 |
+
|
| 180 |
+
ax = axes[1]
|
| 181 |
+
top = int(max(out_deg.max(), in_deg.max()))
|
| 182 |
+
for deg, colour, label in ((out_deg, BLUE, "out-degree (postsynaptic partners)"),
|
| 183 |
+
(in_deg, ORANGE, "in-degree (presynaptic partners)")):
|
| 184 |
+
ax.plot(*int_log_hist(deg[deg > 0], top, 45), color=colour, label=label)
|
| 185 |
+
ax.set_xscale("log")
|
| 186 |
+
ax.set_yscale("log")
|
| 187 |
+
ax.set_xlabel("partners per neuron")
|
| 188 |
+
ax.set_ylabel("neurons per degree value")
|
| 189 |
+
ax.set_title("Degree distributions, full matrix")
|
| 190 |
+
ax.legend(fontsize=9, loc="lower left")
|
| 191 |
+
ax.text(0.0, -0.2,
|
| 192 |
+
f"median out-degree {int(np.median(out_deg))}, in-degree {int(np.median(in_deg))}\n"
|
| 193 |
+
f"{int(np.sum(out_deg == 0)):,} neurons have no outgoing edge in the matrix "
|
| 194 |
+
"(4,143 of them are sign 0)",
|
| 195 |
+
transform=ax.transAxes, fontsize=8.5, color=INK2, va="top")
|
| 196 |
+
fig.subplots_adjust(wspace=0.25)
|
| 197 |
+
save(fig, "connectivity.png")
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# ----------------------------------------------------------------------------- culling
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def fig_culling() -> None:
|
| 204 |
+
man = json.loads((DATA / "manifest.json").read_text())
|
| 205 |
+
variants = ["full", "min2", "min3", "min5", "min10"]
|
| 206 |
+
edges = [man["variants"][v]["edge_fraction"] * 100 for v in variants]
|
| 207 |
+
syn = [man["variants"][v]["synapse_fraction"] * 100 for v in variants]
|
| 208 |
+
md = (RES / "culling-equivalence.md").read_text()
|
| 209 |
+
checks = {}
|
| 210 |
+
for v, r, rn, lat, ln, same, sn in re.findall(
|
| 211 |
+
r"^\| (min\d+) \| (\d+)/(\d+) \| (\d+)/(\d+) \| (\d+)/(\d+) \|", md, re.M):
|
| 212 |
+
checks[v] = (int(r) + int(lat) + int(same), int(rn) + int(ln) + int(sn))
|
| 213 |
+
|
| 214 |
+
fig, axes = plt.subplots(1, 2, figsize=(11, 4.2), gridspec_kw={"width_ratios": [1.15, 1]})
|
| 215 |
+
ax = axes[0]
|
| 216 |
+
xi = np.arange(len(variants))
|
| 217 |
+
bw = 0.38
|
| 218 |
+
for off, vals, colour, label in ((-bw / 2, edges, BLUE, "edges kept"),
|
| 219 |
+
(bw / 2, syn, ORANGE, "synapses kept")):
|
| 220 |
+
bars = ax.bar(xi + off, vals, bw - 0.03, color=colour, label=label)
|
| 221 |
+
for b, v, val in zip(bars, variants, vals, strict=True):
|
| 222 |
+
if v != "full": # full is 100% by definition
|
| 223 |
+
ax.text(b.get_x() + b.get_width() / 2, val + 1.5, f"{val:.0f}%",
|
| 224 |
+
ha="center", fontsize=8, color=INK2)
|
| 225 |
+
ax.set_xticks(xi, [f"{v}\n(≥{man['variants'][v]['min_synapses']} syn)" for v in variants])
|
| 226 |
+
ax.set_ylim(0, 112)
|
| 227 |
+
ax.set_ylabel("% of the full matrix")
|
| 228 |
+
ax.set_title("What each culled variant keeps")
|
| 229 |
+
ax.legend(fontsize=9, loc="upper right", ncol=2, bbox_to_anchor=(1, 1.02))
|
| 230 |
+
ax.grid(axis="x", visible=False)
|
| 231 |
+
|
| 232 |
+
ax = axes[1]
|
| 233 |
+
culled = variants[1:]
|
| 234 |
+
failed = [checks[v][1] - checks[v][0] for v in culled]
|
| 235 |
+
yi = np.arange(len(culled))[::-1]
|
| 236 |
+
ax.barh(yi, failed, 0.55, color=CRIT)
|
| 237 |
+
for y, v, f in zip(yi, culled, failed, strict=True):
|
| 238 |
+
ax.text(f + 0.6, y, f"{f} of {checks[v][1]} checks fail · ✘ FAIL", va="center",
|
| 239 |
+
fontsize=9, color=INK)
|
| 240 |
+
ax.set_yticks(yi, culled)
|
| 241 |
+
ax.set_xlim(0, 62)
|
| 242 |
+
ax.set_xlabel("failed checks (rates, latencies, chain verdicts); a pass needs 0")
|
| 243 |
+
ax.set_title("Pruning equivalence to full (pre-registered)")
|
| 244 |
+
ax.grid(axis="y", visible=False)
|
| 245 |
+
fig.subplots_adjust(wspace=0.3)
|
| 246 |
+
save(fig, "culling.png")
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# ----------------------------------------------------------------------------- chains
|
| 250 |
+
|
| 251 |
+
CHAINS = [("LC4", "DNp01", "escape", "FAIL: activity after the stimulus"),
|
| 252 |
+
("LC16", "MDN", "back away", "FAIL: readout too weak, not specific"),
|
| 253 |
+
("LC9", "DNp09", "approach", "PASS")]
|
| 254 |
+
READOUT_COLOUR = {"DNp01": BLUE, "MDN": ORANGE, "DNp09": AQUA}
|
| 255 |
+
RATES = [25, 50, 100, 150, 200]
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def readout_rates(cond: dict, readout: str) -> np.ndarray:
|
| 259 |
+
"""Per trial 0-29: spikes in [0, 300) ms over all bodies / 0.3 s / bodies.
|
| 260 |
+
|
| 261 |
+
The rate definition of the chain tests (records/preregistration.md)."""
|
| 262 |
+
trials = cond["trials"]
|
| 263 |
+
counts = np.asarray(cond["counts"][readout], dtype=float) # trial x body
|
| 264 |
+
rows = [i for i, t in enumerate(trials) if t < 30]
|
| 265 |
+
return counts[rows].sum(axis=1) / 0.3 / counts.shape[1]
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def fig_chains() -> None:
|
| 269 |
+
conds = json.loads((RES / "chain-tests-trials.json").read_text())["conditions"]
|
| 270 |
+
fig, axes = plt.subplots(1, 3, figsize=(12.5, 4.2))
|
| 271 |
+
for ax, (src, intended, name, verdict) in zip(axes, CHAINS, strict=True):
|
| 272 |
+
ends, upper = {}, 0.0
|
| 273 |
+
for r, colour in READOUT_COLOUR.items():
|
| 274 |
+
m, se = [], []
|
| 275 |
+
for rate in RATES:
|
| 276 |
+
x = readout_rates(conds[f"{src}/{rate}Hz"], r)
|
| 277 |
+
m.append(x.mean())
|
| 278 |
+
se.append(x.std(ddof=1) / np.sqrt(len(x)))
|
| 279 |
+
m, se = np.array(m), np.array(se)
|
| 280 |
+
lw = 2.4 if r == intended else 1.4
|
| 281 |
+
ax.fill_between(RATES, m - 1.96 * se, m + 1.96 * se, color=colour, alpha=0.15,
|
| 282 |
+
lw=0)
|
| 283 |
+
ax.plot(RATES, m, color=colour, lw=lw, marker="o", ms=4.5,
|
| 284 |
+
label=r + (" (intended)" if r == intended else ""))
|
| 285 |
+
ends[r] = m[-1]
|
| 286 |
+
upper = max(upper, float(np.max(m + 1.96 * se)))
|
| 287 |
+
# direct-label line ends, skipping labels that would collide (the legend has all)
|
| 288 |
+
span = max(ends.values()) or 1.0
|
| 289 |
+
last = None
|
| 290 |
+
for r in sorted(ends, key=lambda k: (ends[k], k != intended)):
|
| 291 |
+
if last is not None and ends[r] - last < 0.08 * span:
|
| 292 |
+
continue
|
| 293 |
+
ax.annotate(r, (RATES[-1], ends[r]), xytext=(5, 0), textcoords="offset points",
|
| 294 |
+
va="center", fontsize=8.5, color=INK2,
|
| 295 |
+
fontweight="bold" if r == intended else "normal")
|
| 296 |
+
last = ends[r]
|
| 297 |
+
ax.set_ylim(bottom=-0.04 * span, top=max(1.12 * span, 1.03 * upper))
|
| 298 |
+
colour = GOOD if verdict.startswith("PASS") else CRIT
|
| 299 |
+
ax.set_title(f"{src} → {intended} ({name})")
|
| 300 |
+
ax.text(0.02, 0.97, ("✔ " if colour == GOOD else "✘ ") + verdict,
|
| 301 |
+
transform=ax.transAxes, va="top", fontsize=9, color=colour,
|
| 302 |
+
fontweight="bold")
|
| 303 |
+
ax.set_xticks(RATES)
|
| 304 |
+
ax.set_xlim(15, 235)
|
| 305 |
+
ax.set_xlabel("input rate (Hz), right-side source neurons")
|
| 306 |
+
axes[0].set_ylabel("readout rate (Hz), mean over 30 trials")
|
| 307 |
+
axes[1].text(0.02, 0.88, "note: own y scale", transform=axes[1].transAxes,
|
| 308 |
+
fontsize=8.5, color=INK2, va="top")
|
| 309 |
+
handles = [plt.Line2D([], [], color=c, marker="o", ms=4.5, label=r)
|
| 310 |
+
for r, c in READOUT_COLOUR.items()]
|
| 311 |
+
fig.legend(handles=handles, loc="upper right", ncol=3, fontsize=9,
|
| 312 |
+
bbox_to_anchor=(0.995, 1.06))
|
| 313 |
+
fig.suptitle("Chain tests on MaleCNS (pre-registered): readout rates in the stimulus window",
|
| 314 |
+
x=0.01, ha="left", y=1.04, fontsize=12, fontweight="bold")
|
| 315 |
+
fig.text(0.01, -0.1, "Readout rate: spikes in [0, 300) ms per body, 30 trials (seeds 0-29). "
|
| 316 |
+
"Bands: 95% interval of the mean. LC4, and LC16's pre-registered alternative "
|
| 317 |
+
"LC16 + LPLC1 + LPLC2 (not shown), both fail\nthe post-stimulus criterion "
|
| 318 |
+
"because of one self-sustaining loop of 49 VNC-side neurons that strong "
|
| 319 |
+
"giant-fiber (DNp01) drive switches on (records/validation-log.md).",
|
| 320 |
+
fontsize=8.5, color=INK2)
|
| 321 |
+
fig.subplots_adjust(wspace=0.22)
|
| 322 |
+
save(fig, "chains.png")
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
# ----------------------------------------------------------------------------- gate
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def fig_gate() -> None:
|
| 329 |
+
# records/validation-log.md (recalibrated-rule validation): 200 null replicates of the full
|
| 330 |
+
# 17-condition gate on our engine only (fake "Brian2" and fake "ours" drawn from the
|
| 331 |
+
# same engine), and 50 replicates per deliberately broken engine.
|
| 332 |
+
null = [("Original\npre-registered rule", 184, 200, (87, 95), ORANGE),
|
| 333 |
+
("Recalibrated rule\n(permutation tests,\nBonferroni)", 9, 200, (2.4, 8.3), BLUE)]
|
| 334 |
+
# failing condition checks per gate, recalibrated rule: (min, median, max); 50/50 failed
|
| 335 |
+
detect = [("refractory-input bug", 24, 28, 31), ("w_syn × 1.05", 15, 20, 25)]
|
| 336 |
+
|
| 337 |
+
fig, axes = plt.subplots(1, 2, figsize=(11.5, 3.8), gridspec_kw={"width_ratios": [1.1, 1]})
|
| 338 |
+
ax = axes[0]
|
| 339 |
+
y = np.arange(len(null))[::-1]
|
| 340 |
+
for yi, (_, k, n, (lo, hi), colour) in zip(y, null, strict=True):
|
| 341 |
+
p = 100 * k / n
|
| 342 |
+
ax.barh(yi, p, 0.5, color=colour)
|
| 343 |
+
ax.plot([lo, hi], [yi, yi], color=INK, lw=1.2)
|
| 344 |
+
for edge in (lo, hi):
|
| 345 |
+
ax.plot([edge, edge], [yi - 0.08, yi + 0.08], color=INK, lw=1.2)
|
| 346 |
+
if p > 50:
|
| 347 |
+
ax.text(lo - 2, yi, f"{p:.0f}% ({k}/{n})", va="center", ha="right",
|
| 348 |
+
fontsize=9.5, color="#ffffff", fontweight="bold")
|
| 349 |
+
else:
|
| 350 |
+
ax.text(hi + 2, yi, f"{p:.1f}% ({k}/{n}; 95% CI {lo}–{hi}%)", va="center",
|
| 351 |
+
fontsize=9.5, color=INK)
|
| 352 |
+
ax.axvline(5, color=INK2, lw=1)
|
| 353 |
+
ax.text(6, 1.42, "5% target", fontsize=8.5, color=INK2, va="center")
|
| 354 |
+
ax.set_yticks(y, [n[0] for n in null])
|
| 355 |
+
ax.set_xlim(0, 100)
|
| 356 |
+
ax.set_ylim(-0.5, 1.55)
|
| 357 |
+
ax.set_xlabel("% of replicates with ≥ 1 false fail (200 replicates)")
|
| 358 |
+
ax.set_title("False alarms: a correct engine judged against itself")
|
| 359 |
+
ax.grid(axis="y", visible=False)
|
| 360 |
+
|
| 361 |
+
ax = axes[1]
|
| 362 |
+
yi = np.arange(len(detect))[::-1]
|
| 363 |
+
for y_, (_, lo, med, hi) in zip(yi, detect, strict=True):
|
| 364 |
+
ax.plot([lo, hi], [y_, y_], color=BLUE, lw=6, solid_capstyle="round", alpha=0.45)
|
| 365 |
+
ax.plot([med], [y_], "o", ms=9, color=BLUE, mec=SURFACE, mew=2)
|
| 366 |
+
ax.text(hi + 1.2, y_, f"median {med} (range {lo}–{hi}) of 68\n50/50 gates fail",
|
| 367 |
+
va="center", fontsize=9, color=INK)
|
| 368 |
+
ax.axvline(1, color=INK2, lw=1)
|
| 369 |
+
ax.text(1.6, 1.42, "1 failing check fails the gate", fontsize=8.5, color=INK2,
|
| 370 |
+
va="center")
|
| 371 |
+
ax.set_yticks(yi, [d[0] for d in detect])
|
| 372 |
+
ax.set_xlim(0, 52)
|
| 373 |
+
ax.set_ylim(-0.5, 1.55)
|
| 374 |
+
ax.set_xlabel("failing condition checks per gate, recalibrated rule")
|
| 375 |
+
ax.set_title("Detection: deliberately broken engines")
|
| 376 |
+
ax.grid(axis="y", visible=False)
|
| 377 |
+
fig.suptitle("Engine-check gate calibration on our engine alone (exploratory; "
|
| 378 |
+
"records/validation-log.md)", x=0.01, ha="left", y=1.04, fontsize=12,
|
| 379 |
+
fontweight="bold")
|
| 380 |
+
fig.text(0.01, -0.1, "The original rule also failed 50/50 gates for both broken engines. "
|
| 381 |
+
"The recorded engine-check verdict stays FAIL under the original rule; "
|
| 382 |
+
"the recalibrated rule's results are exploratory only.", fontsize=8.5, color=INK2)
|
| 383 |
+
fig.subplots_adjust(wspace=0.55)
|
| 384 |
+
save(fig, "gate_calibration.png")
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# ----------------------------------------------------------------------------- speed
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def fig_speed() -> None:
|
| 391 |
+
def table(name: str) -> dict[tuple[str, float], float]:
|
| 392 |
+
d = json.loads((RES / name).read_text())
|
| 393 |
+
return {(r["stimulus"], r["rate"]): r["median_per_sim_s"] for r in d["results"]}
|
| 394 |
+
|
| 395 |
+
plain, vec = table("speed-plain-rerun-2.json"), table("speed-vec.json")
|
| 396 |
+
keys = [k for k in vec if k in plain]
|
| 397 |
+
stim_order = ["LC4", "LC16", "LC9", "LC16+LPLC1+LPLC2"]
|
| 398 |
+
keys.sort(key=lambda k: (stim_order.index(k[0]), k[1]))
|
| 399 |
+
labels = [f"{s.replace('+', ' + ')}, {r:g} Hz" for s, r in keys]
|
| 400 |
+
yi = np.arange(len(keys))[::-1]
|
| 401 |
+
bh = 0.38
|
| 402 |
+
fig, ax = plt.subplots(figsize=(10, 6.2))
|
| 403 |
+
ax.barh(yi + bh / 2, [plain[k] for k in keys], bh - 0.05, color=OTHER, label="plain kernel")
|
| 404 |
+
ax.barh(yi - bh / 2, [vec[k] for k in keys], bh - 0.05, color=BLUE,
|
| 405 |
+
label="vec kernel (default)")
|
| 406 |
+
for y, k in zip(yi, keys, strict=True):
|
| 407 |
+
ax.text(plain[k] + 0.08, y + bh / 2, f"{plain[k]:.2f}", va="center", fontsize=8,
|
| 408 |
+
color=INK2)
|
| 409 |
+
ax.text(vec[k] + 0.08, y - bh / 2, f"{vec[k]:.2f} ({plain[k] / vec[k]:.1f}× faster)",
|
| 410 |
+
va="center", fontsize=8, color=INK, zorder=3,
|
| 411 |
+
bbox={"boxstyle": "square,pad=0.1", "fc": SURFACE, "ec": "none"})
|
| 412 |
+
ax.axvline(1.0, color=INK2, lw=1, zorder=2)
|
| 413 |
+
ax.text(1.03, len(keys) - 0.35, "real time", fontsize=8.5, color=INK2)
|
| 414 |
+
ax.set_yticks(yi, labels)
|
| 415 |
+
ax.set_xlabel("wall seconds per simulated second (median of 5; one core; lower is faster)")
|
| 416 |
+
ax.set_title("Speed on the dev container (provisional, not a gated result)", pad=28)
|
| 417 |
+
ax.legend(fontsize=9, loc="lower left", ncol=2, bbox_to_anchor=(0, 1.0))
|
| 418 |
+
ax.grid(axis="y", visible=False)
|
| 419 |
+
ax.set_xlim(0, max(plain.values()) * 1.15)
|
| 420 |
+
fig.text(0.01, -0.02, "Whole MaleCNS, full matrix (165,122 neurons, 24.5 M edges), float32. "
|
| 421 |
+
"Paired runs on a shared 4-vCPU Xeon @ 2.80 GHz (records speed-vec.json, "
|
| 422 |
+
"speed-plain-rerun-2.json). The vec kernel is bit-identical to plain on all "
|
| 423 |
+
"1,520 chain-test trials.", fontsize=8.5, color=INK2, wrap=True)
|
| 424 |
+
save(fig, "speed.png")
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
if __name__ == "__main__":
|
| 428 |
+
OUT.mkdir(exist_ok=True)
|
| 429 |
+
fig_neurons()
|
| 430 |
+
fig_connectivity()
|
| 431 |
+
fig_culling()
|
| 432 |
+
fig_chains()
|
| 433 |
+
fig_gate()
|
| 434 |
+
fig_speed()
|
figures/neurons.png
ADDED
|
Git LFS Details
|
figures/speed.png
ADDED
|
Git LFS Details
|
flysim/.python-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.13
|
flysim/LICENSE
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 The flysim-malecns authors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
| 23 |
+
---------------------------------------------------------------------------
|
| 24 |
+
Scope: this MIT licence covers the code in this repository: flysim/ (except
|
| 25 |
+
flysim/tests/fixtures/shiu/, see below), workflows/ and figures/make_figures.py.
|
| 26 |
+
|
| 27 |
+
flysim/tests/fixtures/shiu/ holds two notebooks vendored unchanged from Shiu et
|
| 28 |
+
al.'s Drosophila_brain_model repository; they keep their own MIT licence
|
| 29 |
+
(copyright the original authors), in flysim/tests/fixtures/shiu/LICENSE.
|
| 30 |
+
|
| 31 |
+
The data in data/ and the written records, documents and figures are under
|
| 32 |
+
CC BY 4.0; see LICENSE.
|
flysim/pyproject.toml
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "flysim"
|
| 3 |
+
version = "1.0.0"
|
| 4 |
+
description = "Whole-brain LIF simulation of the Drosophila MaleCNS v1.0 connectome (Shiu et al. 2024 model), with its pre-registered validation"
|
| 5 |
+
license = "MIT"
|
| 6 |
+
license-files = ["LICENSE"]
|
| 7 |
+
requires-python = ">=3.12"
|
| 8 |
+
dependencies = [
|
| 9 |
+
"numba==0.62.1",
|
| 10 |
+
"numpy==2.3.4",
|
| 11 |
+
"pyarrow==21.0.0",
|
| 12 |
+
"scipy==1.16.3",
|
| 13 |
+
"zstandard==0.25.0",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
[dependency-groups]
|
| 17 |
+
dev = [
|
| 18 |
+
"mypy==2.4.1",
|
| 19 |
+
"pandas==2.3.3",
|
| 20 |
+
"pytest==8.4.2",
|
| 21 |
+
"ruff==0.17.3",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
[build-system]
|
| 25 |
+
requires = ["hatchling"]
|
| 26 |
+
build-backend = "hatchling.build"
|
| 27 |
+
|
| 28 |
+
[tool.hatch.build.targets.wheel]
|
| 29 |
+
packages = ["src/flysim"]
|
| 30 |
+
|
| 31 |
+
[tool.pytest.ini_options]
|
| 32 |
+
testpaths = ["tests"]
|
| 33 |
+
addopts = "--import-mode=importlib"
|
| 34 |
+
|
| 35 |
+
[tool.ruff]
|
| 36 |
+
line-length = 100
|
| 37 |
+
target-version = "py312"
|
| 38 |
+
# Import order as written when the package lived in a larger workspace: flysim sorts as
|
| 39 |
+
# first-party inside src/ and as third-party in tests/ and scripts/.
|
| 40 |
+
src = ["."]
|
| 41 |
+
# tests/fixtures holds third-party files vendored unchanged (Shiu et al.'s notebooks).
|
| 42 |
+
extend-exclude = ["tests/fixtures"]
|
| 43 |
+
|
| 44 |
+
[tool.ruff.format]
|
| 45 |
+
# The package keeps its hand-aligned layout, so it is linted but not formatted.
|
| 46 |
+
exclude = ["**"]
|
| 47 |
+
|
| 48 |
+
[tool.ruff.lint]
|
| 49 |
+
select = ["E", "F", "W", "I", "B", "UP", "SIM"]
|
| 50 |
+
|
| 51 |
+
[tool.mypy]
|
| 52 |
+
python_version = "3.12"
|
| 53 |
+
strict = true
|
| 54 |
+
packages = ["flysim.live"]
|
| 55 |
+
mypy_path = ["src"]
|
| 56 |
+
|
| 57 |
+
[[tool.mypy.overrides]]
|
| 58 |
+
# Only flysim.live is type-checked; the rest (engine, validation harnesses, pipeline) predates
|
| 59 |
+
# mypy and is checked by its tests.
|
| 60 |
+
module = ["flysim", "flysim.artifact", "flysim.engine.*", "flysim.validation.*", "flysim.pipeline.*"]
|
| 61 |
+
ignore_errors = true
|
| 62 |
+
|
| 63 |
+
[[tool.mypy.overrides]]
|
| 64 |
+
module = ["numba", "numba.*", "scipy", "scipy.*", "pyarrow", "pyarrow.*", "zstandard"]
|
| 65 |
+
ignore_missing_imports = true
|
flysim/scripts/brian_reference.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = "==3.10.*"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "brian2==2.5.1",
|
| 5 |
+
# "numpy==1.22.3",
|
| 6 |
+
# "pandas==1.4.3",
|
| 7 |
+
# "pyarrow==11.0.0",
|
| 8 |
+
# "joblib==1.2.0",
|
| 9 |
+
# "cython==0.29.33",
|
| 10 |
+
# "setuptools==67.8.0",
|
| 11 |
+
# "sympy==1.12",
|
| 12 |
+
# "jinja2==2.11.3",
|
| 13 |
+
# "markupsafe==2.0.1",
|
| 14 |
+
# "pyparsing==3.0.9",
|
| 15 |
+
# ]
|
| 16 |
+
# ///
|
| 17 |
+
"""Brian2 reference runs for the engine check (records/preregistration.md, section 2.1).
|
| 18 |
+
|
| 19 |
+
Runs Shiu et al.'s ``model.py`` at commit 91bdd1e **unmodified**, from a checkout of
|
| 20 |
+
their repository, with the versions of their ``environment_full.yml``. The only
|
| 21 |
+
change is ``n_run = 60`` (seed sets A and B), passed in the params dict. Output is
|
| 22 |
+
``<out>/<condition stem>.parquet`` in Shiu's own format.
|
| 23 |
+
|
| 24 |
+
Each condition runs in a child process, and its save is guarded. Twice the job
|
| 25 |
+
segfaulted (exit 139) right after the simulation, while ``run_exp`` built and wrote the
|
| 26 |
+
brotli parquet (see the validation log, 2026-11-04), losing 12-25 min of work. The child
|
| 27 |
+
therefore pickles the spike table before the parquet write, and writes the parquet
|
| 28 |
+
to a temporary name that is renamed only when complete. If the child dies anyway,
|
| 29 |
+
this process converts the pickle to an uncompressed parquet (same columns and rows;
|
| 30 |
+
only the codec differs) and lists the condition under ``saved_by_fallback`` in
|
| 31 |
+
``brian_env.json``. A crash after a complete parquet keeps the parquet. model.py
|
| 32 |
+
itself stays unmodified; only pandas' writer is wrapped.
|
| 33 |
+
|
| 34 |
+
git clone https://github.com/philshiu/Drosophila_brain_model shiu
|
| 35 |
+
git -C shiu checkout 91bdd1e7dcf193f3e7ca5a8933497fcef63b7960
|
| 36 |
+
uv run scripts/brian_reference.py --shiu shiu --out runs/brian [--only E1] [--n-proc 4]
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
from __future__ import annotations
|
| 40 |
+
|
| 41 |
+
import argparse
|
| 42 |
+
import importlib.util
|
| 43 |
+
import json
|
| 44 |
+
import os
|
| 45 |
+
import subprocess
|
| 46 |
+
import sys
|
| 47 |
+
from pathlib import Path
|
| 48 |
+
|
| 49 |
+
HERE = Path(__file__).resolve().parent
|
| 50 |
+
MANIFEST = HERE.parent / "src" / "flysim" / "validation" / "manifest.py"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _load_manifest():
|
| 54 |
+
# The manifest is stdlib-only; load it by path so this env needs no flysim.
|
| 55 |
+
spec = importlib.util.spec_from_file_location("engine_check_manifest", MANIFEST)
|
| 56 |
+
mod = importlib.util.module_from_spec(spec)
|
| 57 |
+
sys.modules["engine_check_manifest"] = mod # dataclasses look the module up by name
|
| 58 |
+
spec.loader.exec_module(mod)
|
| 59 |
+
return mod
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _part(path: Path) -> Path:
|
| 63 |
+
return path.with_name(path.name + ".part")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _safety(path: Path) -> Path:
|
| 67 |
+
return path.with_name(path.name.removesuffix(".parquet") + ".spikes.pkl")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _guard_parquet_writes() -> None:
|
| 71 |
+
"""In the child: pickle each spike table first, then write the parquet atomically."""
|
| 72 |
+
import pandas as pd # noqa: PLC0415
|
| 73 |
+
|
| 74 |
+
original = pd.DataFrame.to_parquet
|
| 75 |
+
|
| 76 |
+
def to_parquet(self, path, *args, **kwargs):
|
| 77 |
+
path = Path(path)
|
| 78 |
+
safety = _safety(path)
|
| 79 |
+
self.to_pickle(safety)
|
| 80 |
+
with open(safety, "rb") as f:
|
| 81 |
+
os.fsync(f.fileno())
|
| 82 |
+
original(self, _part(path), *args, **kwargs)
|
| 83 |
+
os.replace(_part(path), path)
|
| 84 |
+
safety.unlink()
|
| 85 |
+
|
| 86 |
+
pd.DataFrame.to_parquet = to_parquet
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _settle(path: Path) -> str:
|
| 90 |
+
"""In the parent, after the child: 'ok', 'fallback' or 'missing'."""
|
| 91 |
+
import pandas as pd # noqa: PLC0415
|
| 92 |
+
|
| 93 |
+
if path.is_file():
|
| 94 |
+
pd.read_parquet(path, columns=["t", "trial", "flywire_id"]) # raises if unreadable
|
| 95 |
+
_safety(path).unlink(missing_ok=True)
|
| 96 |
+
return "ok"
|
| 97 |
+
if _safety(path).is_file():
|
| 98 |
+
df = pd.read_pickle(_safety(path))
|
| 99 |
+
df.to_parquet(_part(path), compression=None)
|
| 100 |
+
os.replace(_part(path), path)
|
| 101 |
+
_safety(path).unlink()
|
| 102 |
+
return "fallback"
|
| 103 |
+
return "missing"
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def main() -> int:
|
| 107 |
+
p = argparse.ArgumentParser()
|
| 108 |
+
p.add_argument("--shiu", type=Path, required=True, help="checkout of Shiu et al.'s repo")
|
| 109 |
+
p.add_argument("--out", type=Path, required=True)
|
| 110 |
+
p.add_argument("--only", nargs="*", help="case ids (E1) or condition keys")
|
| 111 |
+
p.add_argument("--n-run", type=int, default=60,
|
| 112 |
+
help="60, as preregistered; less only to smoke-test")
|
| 113 |
+
p.add_argument("--n-proc", type=int, default=-1)
|
| 114 |
+
p.add_argument("--child", action="store_true", help=argparse.SUPPRESS)
|
| 115 |
+
a = p.parse_args()
|
| 116 |
+
if a.child:
|
| 117 |
+
return _child(a)
|
| 118 |
+
|
| 119 |
+
m = _load_manifest()
|
| 120 |
+
head = subprocess.run(["git", "-C", str(a.shiu), "rev-parse", "HEAD"], capture_output=True,
|
| 121 |
+
text=True, check=True).stdout.strip()
|
| 122 |
+
if head != m.SHIU_COMMIT:
|
| 123 |
+
raise SystemExit(f"Shiu checkout is at {head}, expected {m.SHIU_COMMIT}")
|
| 124 |
+
if subprocess.run(["git", "-C", str(a.shiu), "diff", "--quiet", "HEAD", "--", "model.py"]
|
| 125 |
+
).returncode != 0:
|
| 126 |
+
raise SystemExit("model.py is modified; the reference must run it unmodified")
|
| 127 |
+
|
| 128 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 129 |
+
conds = [c for c in m.conditions() if not a.only or c.key in a.only or c.case in a.only]
|
| 130 |
+
fallback, missing = [], []
|
| 131 |
+
for c in conds:
|
| 132 |
+
path = a.out / f"{c.file_stem}.parquet"
|
| 133 |
+
if not path.is_file() and not _safety(path).is_file():
|
| 134 |
+
rc = subprocess.run([
|
| 135 |
+
sys.executable, str(Path(__file__).resolve()), "--child",
|
| 136 |
+
"--shiu", str(a.shiu), "--out", str(a.out), "--only", c.key,
|
| 137 |
+
"--n-run", str(a.n_run), "--n-proc", str(a.n_proc),
|
| 138 |
+
]).returncode
|
| 139 |
+
if rc != 0:
|
| 140 |
+
print(f">>> {c.key}: child exited with {rc}", flush=True)
|
| 141 |
+
state = _settle(path)
|
| 142 |
+
print(f">>> {c.key}: {state}", flush=True)
|
| 143 |
+
if state == "fallback":
|
| 144 |
+
fallback.append(c.key)
|
| 145 |
+
elif state == "missing":
|
| 146 |
+
missing.append(c.key)
|
| 147 |
+
|
| 148 |
+
import brian2 # noqa: PLC0415
|
| 149 |
+
|
| 150 |
+
(a.out / "brian_env.json").write_text(json.dumps({
|
| 151 |
+
"brian2": brian2.__version__, "python": sys.version, "shiu_commit": head,
|
| 152 |
+
"codegen_target": str(brian2.prefs.codegen.target), "n_run": a.n_run,
|
| 153 |
+
"saved_by_fallback": fallback,
|
| 154 |
+
}, indent=1))
|
| 155 |
+
if missing:
|
| 156 |
+
print(f">>> no output for: {' '.join(missing)}", file=sys.stderr)
|
| 157 |
+
return 1
|
| 158 |
+
return 0
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _child(a: argparse.Namespace) -> int:
|
| 162 |
+
"""Runs the one condition named by ``--only`` through Shiu's ``run_exp``."""
|
| 163 |
+
m = _load_manifest()
|
| 164 |
+
_guard_parquet_writes()
|
| 165 |
+
sys.path.insert(0, str(a.shiu.resolve()))
|
| 166 |
+
from brian2 import Hz # noqa: PLC0415
|
| 167 |
+
from model import default_params, run_exp # noqa: PLC0415
|
| 168 |
+
|
| 169 |
+
cases = json.loads((MANIFEST.parent / "cases.json").read_text())
|
| 170 |
+
(c,) = [c for c in m.conditions() if c.key in a.only]
|
| 171 |
+
params = dict(default_params)
|
| 172 |
+
params["n_run"] = a.n_run
|
| 173 |
+
(g1, r1), *rest = c.groups
|
| 174 |
+
params["r_poi"] = r1 * Hz
|
| 175 |
+
exc2: list[int] = []
|
| 176 |
+
if rest:
|
| 177 |
+
(g2, r2), = rest
|
| 178 |
+
params["r_poi2"] = r2 * Hz
|
| 179 |
+
exc2 = cases["groups"][g2]
|
| 180 |
+
run_exp(
|
| 181 |
+
exp_name=c.file_stem,
|
| 182 |
+
neu_exc=cases["groups"][g1],
|
| 183 |
+
neu_exc2=exc2,
|
| 184 |
+
path_res=a.out,
|
| 185 |
+
path_comp=a.shiu / m.FAFB_COMPLETENESS,
|
| 186 |
+
path_con=a.shiu / m.FAFB_CONNECTIVITY,
|
| 187 |
+
params=params,
|
| 188 |
+
n_proc=a.n_proc,
|
| 189 |
+
)
|
| 190 |
+
return 0
|
| 191 |
+
|
| 192 |
+
if __name__ == "__main__":
|
| 193 |
+
sys.exit(main())
|
flysim/scripts/connectome_paths.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Structural check of the three input -> readout chains in MaleCNS v1.0.
|
| 2 |
+
|
| 3 |
+
Counts direct synapses and a crude two-hop estimate (sum over intermediate
|
| 4 |
+
neurons of in-count x out-count, signed by the intermediate's transmitter)
|
| 5 |
+
from each stimulated LC population to each descending-neuron readout.
|
| 6 |
+
This is a pre-simulation sanity check, not a substitute for the chain tests.
|
| 7 |
+
|
| 8 |
+
Usage: python -I connectome_paths.py <dir with the three MaleCNS feather files>
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import pyarrow as pa
|
| 16 |
+
import pyarrow.compute as pc
|
| 17 |
+
import pyarrow.feather as pf
|
| 18 |
+
|
| 19 |
+
SOURCES = ["LC4", "LC16", "LC9"]
|
| 20 |
+
READOUTS = ["DNp01", "MDN", "DNp09"]
|
| 21 |
+
SIGN = {"acetylcholine": 1, "gaba": -1, "glutamate": -1, "histamine": -1}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def main(d: str) -> None:
|
| 25 |
+
ann = pf.read_table(
|
| 26 |
+
f"{d}/body-annotations-male-cns-v1.0-minconf-0.5.feather",
|
| 27 |
+
columns=["bodyId", "type", "status"],
|
| 28 |
+
).to_pandas()
|
| 29 |
+
ann = ann[ann.status == "Traced"]
|
| 30 |
+
nt = (
|
| 31 |
+
pf.read_table(
|
| 32 |
+
f"{d}/body-neurotransmitters-male-cns-v1.0.feather",
|
| 33 |
+
columns=["body", "consensus_nt", "predicted_nt"],
|
| 34 |
+
)
|
| 35 |
+
.to_pandas()
|
| 36 |
+
.set_index("body")
|
| 37 |
+
)
|
| 38 |
+
nt_of = nt.consensus_nt.fillna(nt.predicted_nt)
|
| 39 |
+
traced = set(ann.bodyId)
|
| 40 |
+
type_of = ann.set_index("bodyId").type
|
| 41 |
+
ids = {t: set(ann.bodyId[ann.type == t]) for t in SOURCES + READOUTS}
|
| 42 |
+
|
| 43 |
+
w = pf.read_table(
|
| 44 |
+
f"{d}/connectome-weights-male-cns-v1.0-minconf-0.5.feather", memory_map=True
|
| 45 |
+
)
|
| 46 |
+
all_src = pa.array(list(set().union(*(ids[t] for t in SOURCES))))
|
| 47 |
+
all_dst = pa.array(list(set().union(*(ids[t] for t in READOUTS))))
|
| 48 |
+
into = w.filter(pc.is_in(w.column("body_post"), all_dst)).to_pandas()
|
| 49 |
+
out = w.filter(pc.is_in(w.column("body_pre"), all_src)).to_pandas()
|
| 50 |
+
into = into[into.body_pre.isin(traced)]
|
| 51 |
+
out = out[out.body_post.isin(traced)]
|
| 52 |
+
|
| 53 |
+
for s in SOURCES:
|
| 54 |
+
for t in READOUTS:
|
| 55 |
+
direct = into[into.body_pre.isin(ids[s]) & into.body_post.isin(ids[t])].weight.sum()
|
| 56 |
+
o = out[out.body_pre.isin(ids[s])].groupby("body_post").weight.sum()
|
| 57 |
+
i = into[into.body_post.isin(ids[t])].groupby("body_pre").weight.sum()
|
| 58 |
+
mids = o.index.intersection(i.index)
|
| 59 |
+
sg = np.array([SIGN.get(str(nt_of.get(m, "")).lower(), 0) for m in mids])
|
| 60 |
+
val = o[mids].values * i[mids].values
|
| 61 |
+
top = (
|
| 62 |
+
pd.Series(val * sg, index=[type_of.get(m, "?") for m in mids])
|
| 63 |
+
.groupby(level=0)
|
| 64 |
+
.sum()
|
| 65 |
+
.sort_values()
|
| 66 |
+
)
|
| 67 |
+
print(
|
| 68 |
+
f"{s:5}->{t:6} direct={direct:6} 2hop_mids={len(mids):4} "
|
| 69 |
+
f"exc={val[sg > 0].sum():.3g} inh={val[sg < 0].sum():.3g} "
|
| 70 |
+
f"top+={list(top.tail(3).index)} top-={list(top.head(2).index)}"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if __name__ == "__main__":
|
| 75 |
+
main(sys.argv[1])
|
flysim/scripts/recalibrated_rule_validation.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validation of the recalibrated engine-check rule (records/preregistration.md,
|
| 2 |
+
section 9), using our engine only.
|
| 3 |
+
|
| 4 |
+
No Brian2 data is read here: the rule was validated without the engine check's Brian2
|
| 5 |
+
artifacts. Trials come from the reserved validation range (``SET_VALIDATION``),
|
| 6 |
+
which no preregistered or exploratory comparison ever uses.
|
| 7 |
+
|
| 8 |
+
# 1. our engine, the null pool: trials 5000-5149 of every condition
|
| 9 |
+
python -m flysim.validation.engine_check run --fafb DIR --out runs/null --trials 150 \
|
| 10 |
+
--first-trial 5000
|
| 11 |
+
|
| 12 |
+
# 2. perturbed engines, trials 5200-5229 (seeds disjoint from the pool)
|
| 13 |
+
python scripts/recalibrated_rule_validation.py perturb --fafb DIR --out runs/bug \
|
| 14 |
+
--perturbation refractory-bug
|
| 15 |
+
python scripts/recalibrated_rule_validation.py perturb --fafb DIR --out runs/w105 \
|
| 16 |
+
--perturbation wsyn=1.05
|
| 17 |
+
|
| 18 |
+
# 3. null test: false-fail rates of both rules when there is no engine difference
|
| 19 |
+
python scripts/recalibrated_rule_validation.py null --fafb DIR --runs runs/null --reps 200
|
| 20 |
+
|
| 21 |
+
# 4. detection: perturbed "ours" against resampled pools of the correct engine
|
| 22 |
+
python scripts/recalibrated_rule_validation.py detect --fafb DIR --runs runs/null \
|
| 23 |
+
--perturbed runs/bug --reps 50
|
| 24 |
+
|
| 25 |
+
Null test, per replicate: a random permutation of the 150 pool trials gives a fake
|
| 26 |
+
Brian2 pool (the first 60; set A is the first 30 of those) and a disjoint fake
|
| 27 |
+
"ours" (the next 30). Three rules judge all 17 conditions: the recalibrated rule
|
| 28 |
+
(``recalibrated``: splits of A ∪ ours), its first design (``recalibrated_design1``:
|
| 29 |
+
splits of the Brian2 pool A ∪ B, rejected after this test) and the original rule of
|
| 30 |
+
section 2.3 (``original``). A replicate is a false
|
| 31 |
+
fail if any of the 68 condition checks fails. Replicates share trials (150 per
|
| 32 |
+
condition), so they are not independent and the binomial interval is a lower bound
|
| 33 |
+
on the uncertainty.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
from __future__ import annotations
|
| 37 |
+
|
| 38 |
+
import argparse
|
| 39 |
+
import dataclasses
|
| 40 |
+
import json
|
| 41 |
+
import multiprocessing as mp
|
| 42 |
+
import sys
|
| 43 |
+
import time
|
| 44 |
+
from pathlib import Path
|
| 45 |
+
|
| 46 |
+
import numba
|
| 47 |
+
import numpy as np
|
| 48 |
+
from flysim.engine import CpuEngine
|
| 49 |
+
from flysim.engine import cpu as cpu_mod
|
| 50 |
+
from flysim.validation import engine_check as ec
|
| 51 |
+
from flysim.validation import fafb as fafb_mod
|
| 52 |
+
from flysim.validation import metrics
|
| 53 |
+
from flysim.validation import recalibrated as rc
|
| 54 |
+
from flysim.validation.manifest import conditions, load_cases
|
| 55 |
+
from flysim.validation.runs import RunSet
|
| 56 |
+
|
| 57 |
+
NULL_TRIALS = range(5000, 5150)
|
| 58 |
+
PERTURBED_TRIALS = range(5200, 5230)
|
| 59 |
+
REPLICATE_SEED = 20261105
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# -- perturbed engines ------------------------------------------------------------
|
| 63 |
+
@numba.njit(cache=True, nogil=True, boundscheck=False)
|
| 64 |
+
def _buggy_run_steps(s0, s1, v, g, last, rfc, v_0, v_rst, v_th, a, b, c, w_syn, w_input,
|
| 65 |
+
delay, indptr, indices, weights, in_ptr, in_idx, log, log_ptr, log_len):
|
| 66 |
+
"""The kernel before the refractory-input fix (validation log, 2026-11-03): input
|
| 67 |
+
reaching a refractory neuron is not dropped but accumulates in ``g`` (frozen) and
|
| 68 |
+
acts when the refractory period ends. Everything else is the production kernel."""
|
| 69 |
+
n = v.shape[0]
|
| 70 |
+
zero = v.dtype.type(0)
|
| 71 |
+
n_in_steps = in_ptr.shape[0] - 1
|
| 72 |
+
for s in range(s0, s1):
|
| 73 |
+
if log_len + n > log.shape[0]:
|
| 74 |
+
return s, log_len
|
| 75 |
+
start = log_len
|
| 76 |
+
log_ptr[s] = start
|
| 77 |
+
for i in range(n):
|
| 78 |
+
if s - last[i] < rfc[i]:
|
| 79 |
+
continue
|
| 80 |
+
vi = v[i]
|
| 81 |
+
gi = g[i]
|
| 82 |
+
if gi == zero and vi == v_0:
|
| 83 |
+
continue
|
| 84 |
+
vi = v_0 + (vi - v_0) * a + gi * b
|
| 85 |
+
g[i] = gi * c
|
| 86 |
+
v[i] = vi
|
| 87 |
+
if vi > v_th:
|
| 88 |
+
log[log_len] = i
|
| 89 |
+
log_len += 1
|
| 90 |
+
last[i] = s
|
| 91 |
+
log_ptr[s + 1] = log_len
|
| 92 |
+
sd = s - delay
|
| 93 |
+
if sd >= 0:
|
| 94 |
+
for k in range(log_ptr[sd], log_ptr[sd + 1]):
|
| 95 |
+
j = log[k]
|
| 96 |
+
for e in range(indptr[j], indptr[j + 1]):
|
| 97 |
+
g[indices[e]] += w_syn * weights[e] # the bug: no refractory guard
|
| 98 |
+
if s < n_in_steps:
|
| 99 |
+
for k in range(in_ptr[s], in_ptr[s + 1]):
|
| 100 |
+
v[in_idx[k]] += w_input
|
| 101 |
+
for k in range(start, log_len):
|
| 102 |
+
i = log[k]
|
| 103 |
+
v[i] = v_rst
|
| 104 |
+
g[i] = zero
|
| 105 |
+
return s1, log_len
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
_w: dict = {}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _init_perturbed(fafb_dir: str, perturbation: str) -> None:
|
| 112 |
+
params = ec.PARAMS
|
| 113 |
+
if perturbation == "refractory-bug":
|
| 114 |
+
cpu_mod.run_steps = _buggy_run_steps # this worker process only
|
| 115 |
+
elif perturbation.startswith("wsyn="):
|
| 116 |
+
params = dataclasses.replace(ec.PARAMS, w_syn=ec.PARAMS.w_syn
|
| 117 |
+
* float(perturbation.split("=", 1)[1]))
|
| 118 |
+
else:
|
| 119 |
+
raise SystemExit(f"unknown perturbation {perturbation!r}")
|
| 120 |
+
f = fafb_mod.load(Path(fafb_dir))
|
| 121 |
+
eng = CpuEngine(np.float32, skip_rest=False) # the reference kernel the gate ran on
|
| 122 |
+
eng.load(f.matrix, params)
|
| 123 |
+
_w.update(fafb=f, engine=eng, cases=load_cases(), params=params)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _perturbed_task(args: tuple[str, int]):
|
| 127 |
+
key, trial = args
|
| 128 |
+
cond = next(c for c in conditions() if c.key == key)
|
| 129 |
+
steps, neurons = ec.run_trial(cond, trial, _w["fafb"], _w["engine"], _w["cases"])
|
| 130 |
+
return key, trial, steps, neurons
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def cmd_perturb(a: argparse.Namespace) -> int:
|
| 134 |
+
conds = [c for c in conditions() if not a.only or c.key in a.only or c.case in a.only]
|
| 135 |
+
tasks = [(c.key, t) for c in conds for t in PERTURBED_TRIALS]
|
| 136 |
+
done: dict[str, list] = {c.key: [] for c in conds}
|
| 137 |
+
n_neurons = len(fafb_mod.read_root_ids(a.fafb))
|
| 138 |
+
with mp.get_context("fork").Pool(a.jobs, initializer=_init_perturbed,
|
| 139 |
+
initargs=(str(a.fafb), a.perturbation)) as pool:
|
| 140 |
+
for key, trial, steps, neurons in pool.imap_unordered(_perturbed_task, tasks):
|
| 141 |
+
done[key].append((trial, steps, neurons))
|
| 142 |
+
if len(done[key]) == len(PERTURBED_TRIALS):
|
| 143 |
+
rs = RunSet.from_trials(done[key], n_neurons=n_neurons, n_steps=ec.N_STEPS,
|
| 144 |
+
dt_ms=ec.PARAMS.dt,
|
| 145 |
+
meta={"perturbation": a.perturbation, "key": key})
|
| 146 |
+
stem = next(c for c in conds if c.key == key).file_stem
|
| 147 |
+
rs.save(a.out / f"{stem}.npz")
|
| 148 |
+
print(f" {key}: {len(rs.neurons)} spikes", flush=True)
|
| 149 |
+
return 0
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# -- judging ------------------------------------------------------------------------
|
| 153 |
+
def _renumbered(rs: RunSet, trials: np.ndarray) -> RunSet:
|
| 154 |
+
sub = rs.subset(trials)
|
| 155 |
+
return dataclasses.replace(sub, trials=np.arange(len(trials), dtype=np.int32))
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _readouts(fafb_dir: Path) -> dict[str, int]:
|
| 159 |
+
root_ids = fafb_mod.read_root_ids(fafb_dir)
|
| 160 |
+
return {name: int(np.flatnonzero(root_ids == rid)[0])
|
| 161 |
+
for name, rid in load_cases()["readouts"].items()}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _judge_all(c, ours_rs: RunSet, pool_rs: RunSet, ro: int, ours_arr, pool_arr,
|
| 165 |
+
masks: np.ndarray, design1: bool) -> dict[str, dict]:
|
| 166 |
+
"""The rules on one comparison. ``pool_*`` is the (fake) Brian2 pool of 60, set A
|
| 167 |
+
first."""
|
| 168 |
+
a = pool_arr.take(range(rc.HALF))
|
| 169 |
+
new = rc.judge_rule(c.key, ours_arr, a, masks)
|
| 170 |
+
old = metrics.compare_condition(c.key, ours_rs, pool_rs, ro)
|
| 171 |
+
out = {"recalibrated": {k.name: k.passed for k in new.checks},
|
| 172 |
+
"original": {k.name: k.passed for k in old.checks},
|
| 173 |
+
"recalibrated_values": {k.name: [k.value, k.threshold] for k in new.checks}}
|
| 174 |
+
if design1:
|
| 175 |
+
first = rc.judge(c.key, ours_arr, a, rc.floors(pool_arr, masks))
|
| 176 |
+
out["recalibrated_design1"] = {k.name: k.passed for k in first.checks}
|
| 177 |
+
return out
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _summarise(per_rep: list[dict], label: str) -> dict:
|
| 181 |
+
out: dict = {"label": label, "reps": len(per_rep),
|
| 182 |
+
"conditions": len(per_rep[0]) if per_rep else 0}
|
| 183 |
+
rules = [r for r in ("recalibrated", "recalibrated_design1", "original")
|
| 184 |
+
if per_rep and all(r in cond for cond in per_rep[0].values())]
|
| 185 |
+
for rule in rules:
|
| 186 |
+
any_fail = [any(not ok for cond in rep.values() for ok in cond[rule].values())
|
| 187 |
+
for rep in per_rep]
|
| 188 |
+
per_check: dict[str, int] = {}
|
| 189 |
+
for rep in per_rep:
|
| 190 |
+
for key, cond in rep.items():
|
| 191 |
+
for name, ok in cond[rule].items():
|
| 192 |
+
per_check[f"{key} {name}"] = per_check.get(f"{key} {name}", 0) + (not ok)
|
| 193 |
+
k, n = int(sum(any_fail)), len(any_fail)
|
| 194 |
+
out[rule] = {"replicates_with_a_fail": k, "rate": k / n,
|
| 195 |
+
"wilson95": _wilson(k, n),
|
| 196 |
+
"checks_failed": int(sum(per_check.values())),
|
| 197 |
+
"failing_checks": {c: v for c, v in sorted(per_check.items()) if v}}
|
| 198 |
+
return out
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _wilson(k: int, n: int, z: float = 1.96) -> list[float]:
|
| 202 |
+
p = k / n
|
| 203 |
+
d = 1 + z * z / n
|
| 204 |
+
mid = (p + z * z / (2 * n)) / d
|
| 205 |
+
half = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
|
| 206 |
+
return [round(float(mid - half), 4), round(float(mid + half), 4)]
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _selected(only: list[str] | None):
|
| 210 |
+
return [c for c in conditions() if not only or c.key in only or c.case in only]
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _load(fafb_dir: Path, directory: Path, c, trials: range):
|
| 214 |
+
ro = _readouts(fafb_dir)[c.readout]
|
| 215 |
+
rs = RunSet.load(directory / f"{c.file_stem}.npz").subset(trials)
|
| 216 |
+
return rs, ro, rc.trial_arrays(rs, ro)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _condition_job(args: tuple) -> tuple[str, list[dict], float]:
|
| 220 |
+
"""One condition, all replicates. ``perturbed`` None: null test; else detection."""
|
| 221 |
+
key, fafb_dir, runs, perturbed, reps, design1 = args
|
| 222 |
+
t0 = time.perf_counter()
|
| 223 |
+
c = next(c for c in conditions() if c.key == key)
|
| 224 |
+
rs, ro, arr = _load(fafb_dir, runs, c, NULL_TRIALS)
|
| 225 |
+
masks = rc.split_masks()
|
| 226 |
+
out = []
|
| 227 |
+
if perturbed is None:
|
| 228 |
+
rng = np.random.default_rng(REPLICATE_SEED)
|
| 229 |
+
for _ in range(reps):
|
| 230 |
+
p = rng.permutation(len(NULL_TRIALS))
|
| 231 |
+
pool_idx, ours_idx = p[:60], p[60:90]
|
| 232 |
+
out.append(_judge_all(c, _renumbered(rs, rs.trials[ours_idx]),
|
| 233 |
+
_renumbered(rs, rs.trials[pool_idx]), ro,
|
| 234 |
+
arr.take(ours_idx), arr.take(pool_idx), masks, design1))
|
| 235 |
+
else:
|
| 236 |
+
bad_rs, _, bad_arr = _load(fafb_dir, perturbed, c, PERTURBED_TRIALS)
|
| 237 |
+
bad_rs = _renumbered(bad_rs, bad_rs.trials)
|
| 238 |
+
rng = np.random.default_rng(REPLICATE_SEED + 1)
|
| 239 |
+
for _ in range(reps):
|
| 240 |
+
pool_idx = rng.permutation(len(NULL_TRIALS))[:60]
|
| 241 |
+
out.append(_judge_all(c, bad_rs, _renumbered(rs, rs.trials[pool_idx]), ro,
|
| 242 |
+
bad_arr, arr.take(pool_idx), masks, design1))
|
| 243 |
+
return key, out, time.perf_counter() - t0
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _run_jobs(a: argparse.Namespace, perturbed: Path | None) -> list[dict]:
|
| 247 |
+
"""Replicate i uses the same draw in every condition (the replicate seed is per
|
| 248 |
+
condition, and conditions' trials are independent), so a replicate is one full
|
| 249 |
+
17-condition gate."""
|
| 250 |
+
jobs = [(c.key, a.fafb, a.runs, perturbed, a.reps, a.design1) for c in _selected(a.only)]
|
| 251 |
+
per_rep: list[dict] = [{} for _ in range(a.reps)]
|
| 252 |
+
with mp.get_context("fork").Pool(a.jobs) as pool:
|
| 253 |
+
for key, results, secs in pool.imap_unordered(_condition_job, jobs):
|
| 254 |
+
for i, r in enumerate(results):
|
| 255 |
+
per_rep[i][key] = r
|
| 256 |
+
print(f" {key}: {secs:.0f} s", flush=True)
|
| 257 |
+
return per_rep
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def cmd_null(a: argparse.Namespace) -> int:
|
| 261 |
+
per_rep = _run_jobs(a, None)
|
| 262 |
+
_write(a.out, _summarise(per_rep, "null: correct engine on both sides"), per_rep)
|
| 263 |
+
return 0
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def cmd_detect(a: argparse.Namespace) -> int:
|
| 267 |
+
per_rep = _run_jobs(a, a.perturbed)
|
| 268 |
+
_write(a.out, _summarise(per_rep, f"detection: {a.perturbed.name} against the correct "
|
| 269 |
+
"engine"), per_rep)
|
| 270 |
+
return 0
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _write(out: Path | None, summary: dict, per_rep: list[dict]) -> None:
|
| 274 |
+
text = json.dumps(summary, indent=1)
|
| 275 |
+
print(text)
|
| 276 |
+
if out:
|
| 277 |
+
out.write_text(json.dumps({"summary": summary, "replicates": per_rep}, indent=0))
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def main(argv: list[str] | None = None) -> int:
|
| 281 |
+
p = argparse.ArgumentParser()
|
| 282 |
+
sub = p.add_subparsers(dest="cmd", required=True)
|
| 283 |
+
pr = sub.add_parser("perturb")
|
| 284 |
+
pr.add_argument("--fafb", type=Path, required=True)
|
| 285 |
+
pr.add_argument("--out", type=Path, required=True)
|
| 286 |
+
pr.add_argument("--perturbation", required=True, help="refractory-bug | wsyn=<factor>")
|
| 287 |
+
pr.add_argument("--jobs", type=int, default=mp.cpu_count())
|
| 288 |
+
pr.add_argument("--only", nargs="*")
|
| 289 |
+
for name in ("null", "detect"):
|
| 290 |
+
q = sub.add_parser(name)
|
| 291 |
+
q.add_argument("--fafb", type=Path, required=True)
|
| 292 |
+
q.add_argument("--runs", type=Path, required=True)
|
| 293 |
+
q.add_argument("--reps", type=int, default=200 if name == "null" else 50)
|
| 294 |
+
q.add_argument("--only", nargs="*")
|
| 295 |
+
q.add_argument("--out", type=Path)
|
| 296 |
+
q.add_argument("--jobs", type=int, default=mp.cpu_count())
|
| 297 |
+
q.add_argument("--design1", action="store_true",
|
| 298 |
+
help="also judge by the rejected first design (splits of A ∪ B)")
|
| 299 |
+
if name == "detect":
|
| 300 |
+
q.add_argument("--perturbed", type=Path, required=True)
|
| 301 |
+
a = p.parse_args(argv)
|
| 302 |
+
return {"perturb": cmd_perturb, "null": cmd_null, "detect": cmd_detect}[a.cmd](a)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
if __name__ == "__main__":
|
| 306 |
+
sys.exit(main())
|
flysim/src/flysim/__init__.py
ADDED
|
File without changes
|
flysim/src/flysim/artifact.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download and load the published connectome artefact.
|
| 2 |
+
|
| 3 |
+
python -m flysim.artifact fetch --variant min3 [--dest data] [--revision connectome-v1]
|
| 4 |
+
|
| 5 |
+
Files come from the Hugging Face dataset ``nynefold/flysim-malecns``, path
|
| 6 |
+
``data/connectome-v<N>/``, at the git revision (tag, branch or commit) given by
|
| 7 |
+
``--revision``; the default is the tag of the same name as the artefact,
|
| 8 |
+
``connectome-v1``. Every file is checked against the artefact's SHA256SUMS, whose own
|
| 9 |
+
hash is pinned below (``KNOWN_SUMS``). Set ``HF_TOKEN`` if the dataset is private or
|
| 10 |
+
you hit rate limits.
|
| 11 |
+
|
| 12 |
+
Only the ``full`` matrix passed the pre-registered pruning-equivalence test (see
|
| 13 |
+
``records/validation-log.md``); the culled variants are provided for study only.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import hashlib
|
| 20 |
+
import io
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
import tarfile
|
| 25 |
+
import urllib.parse
|
| 26 |
+
import urllib.request
|
| 27 |
+
from dataclasses import dataclass
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
import pyarrow.parquet as pq
|
| 32 |
+
import zstandard
|
| 33 |
+
|
| 34 |
+
HF_REPO = "nynefold/flysim-malecns"
|
| 35 |
+
HF_BASE = "https://huggingface.co/datasets"
|
| 36 |
+
DEFAULT_TAG = "connectome-v1"
|
| 37 |
+
DEFAULT_DEST = Path("data")
|
| 38 |
+
VARIANTS = ("full", "min2", "min3", "min5", "min10")
|
| 39 |
+
#: SHA-256 of each published artefact's SHA256SUMS, so the whole download is pinned.
|
| 40 |
+
KNOWN_SUMS = {"connectome-v1": "98b93daf2cd91c84a4633db08d075d9887acd66ea957cf40ca57ba256ac0ac1f"}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _get(url: str) -> bytes:
|
| 44 |
+
req = urllib.request.Request(url, headers={"User-Agent": "flysim"})
|
| 45 |
+
token = os.environ.get("HF_TOKEN")
|
| 46 |
+
if token:
|
| 47 |
+
# Unredirected: the token goes to huggingface.co only, never to the storage
|
| 48 |
+
# host the download is redirected to (that URL is signed).
|
| 49 |
+
req.add_unredirected_header("Authorization", f"Bearer {token}")
|
| 50 |
+
with urllib.request.urlopen(req) as r:
|
| 51 |
+
return r.read()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def file_url(name: str, tag: str = DEFAULT_TAG, revision: str | None = None) -> str:
|
| 55 |
+
"""Download URL of one artefact file on the Hugging Face Hub."""
|
| 56 |
+
rev = urllib.parse.quote(revision or tag, safe="")
|
| 57 |
+
return f"{HF_BASE}/{HF_REPO}/resolve/{rev}/data/{tag}/{name}"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _sha256(data: bytes) -> str:
|
| 61 |
+
return hashlib.sha256(data).hexdigest()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def fetch(variant: str, dest: Path = DEFAULT_DEST, tag: str = DEFAULT_TAG,
|
| 65 |
+
revision: str | None = None) -> Path:
|
| 66 |
+
"""Download ``variant`` plus the shared files into ``dest/tag`` and check every hash.
|
| 67 |
+
|
| 68 |
+
Files already present with the right hash are kept. Returns the directory."""
|
| 69 |
+
if variant not in VARIANTS:
|
| 70 |
+
raise ValueError(f"unknown variant {variant!r}; choose from {VARIANTS}")
|
| 71 |
+
out = dest / tag
|
| 72 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 73 |
+
raw_sums = _get(file_url("SHA256SUMS", tag, revision))
|
| 74 |
+
if tag in KNOWN_SUMS and _sha256(raw_sums) != KNOWN_SUMS[tag]:
|
| 75 |
+
raise RuntimeError(f"SHA256SUMS of {tag} does not match the pinned hash")
|
| 76 |
+
sums = raw_sums.decode()
|
| 77 |
+
(out / "SHA256SUMS").write_text(sums)
|
| 78 |
+
expected = dict(reversed(line.split(" ", 1)) for line in sums.splitlines() if line)
|
| 79 |
+
for name in ("manifest.json", "neurons.parquet", f"matrix-{variant}.tar.zst"):
|
| 80 |
+
path = out / name
|
| 81 |
+
if path.exists() and _sha256(path.read_bytes()) == expected[name]:
|
| 82 |
+
continue
|
| 83 |
+
data = _get(file_url(name, tag, revision))
|
| 84 |
+
if _sha256(data) != expected[name]:
|
| 85 |
+
raise RuntimeError(f"hash mismatch for {name}")
|
| 86 |
+
path.write_bytes(data)
|
| 87 |
+
print(f"fetched {name} ({len(data) / 1e6:.1f} MB)")
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@dataclass(frozen=True)
|
| 92 |
+
class Connectome:
|
| 93 |
+
"""Signed sparse weight matrix, CSC by presynaptic neuron.
|
| 94 |
+
|
| 95 |
+
Outgoing edges of neuron ``j``: rows ``indices[indptr[j]:indptr[j+1]]`` with
|
| 96 |
+
signed synapse counts ``weights[indptr[j]:indptr[j+1]]``.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
indptr: np.ndarray # int64, n + 1
|
| 100 |
+
indices: np.ndarray # int32, postsynaptic rows
|
| 101 |
+
weights: np.ndarray # int16, sign(pre) * synapse count
|
| 102 |
+
neurons: object # pyarrow.Table
|
| 103 |
+
manifest: dict
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def n(self) -> int:
|
| 107 |
+
return len(self.indptr) - 1
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def load(directory: Path, variant: str) -> Connectome:
|
| 111 |
+
manifest = json.loads((directory / "manifest.json").read_text())
|
| 112 |
+
raw = (directory / f"matrix-{variant}.tar.zst").read_bytes()
|
| 113 |
+
tar_bytes = zstandard.ZstdDecompressor().decompress(raw, max_output_size=1 << 32)
|
| 114 |
+
arrays = {}
|
| 115 |
+
with tarfile.open(fileobj=io.BytesIO(tar_bytes)) as tar:
|
| 116 |
+
for member in tar.getmembers():
|
| 117 |
+
f = tar.extractfile(member)
|
| 118 |
+
assert f is not None
|
| 119 |
+
arrays[member.name.removesuffix(".npy")] = np.load(io.BytesIO(f.read()))
|
| 120 |
+
neurons = pq.read_table(directory / "neurons.parquet")
|
| 121 |
+
return Connectome(arrays["indptr"], arrays["indices"], arrays["weights"], neurons, manifest)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def main(argv: list[str] | None = None) -> int:
|
| 125 |
+
p = argparse.ArgumentParser(prog="python -m flysim.artifact")
|
| 126 |
+
sub = p.add_subparsers(dest="cmd", required=True)
|
| 127 |
+
f = sub.add_parser("fetch")
|
| 128 |
+
f.add_argument("--variant", default="full", choices=VARIANTS)
|
| 129 |
+
f.add_argument("--dest", type=Path, default=DEFAULT_DEST)
|
| 130 |
+
f.add_argument("--tag", default=DEFAULT_TAG,
|
| 131 |
+
help="artefact version, i.e. the folder data/<tag>/ (default %(default)s)")
|
| 132 |
+
f.add_argument("--revision", default=None,
|
| 133 |
+
help="dataset git revision (tag, branch or commit); default: same as --tag")
|
| 134 |
+
a = p.parse_args(argv)
|
| 135 |
+
print(fetch(a.variant, a.dest, a.tag, a.revision))
|
| 136 |
+
return 0
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
sys.exit(main())
|
flysim/src/flysim/engine/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Our LIF simulation engine (records/preregistration.md, section 1)."""
|
| 2 |
+
|
| 3 |
+
from flysim.engine.base import Engine, EngineState, SynapseMatrix
|
| 4 |
+
from flysim.engine.cpu import CpuEngine
|
| 5 |
+
from flysim.engine.inputs import InputSchedule, poisson_schedule, trial_rng, trial_seed
|
| 6 |
+
from flysim.engine.params import ModelParams
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"CpuEngine",
|
| 10 |
+
"Engine",
|
| 11 |
+
"EngineState",
|
| 12 |
+
"InputSchedule",
|
| 13 |
+
"ModelParams",
|
| 14 |
+
"SynapseMatrix",
|
| 15 |
+
"poisson_schedule",
|
| 16 |
+
"trial_rng",
|
| 17 |
+
"trial_seed",
|
| 18 |
+
]
|
flysim/src/flysim/engine/base.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The engine interface and the data it works on."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import Protocol
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from flysim.engine.inputs import InputSchedule
|
| 11 |
+
from flysim.engine.params import ModelParams
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass(frozen=True)
|
| 15 |
+
class SynapseMatrix:
|
| 16 |
+
"""Signed synapse counts, CSC by presynaptic neuron.
|
| 17 |
+
|
| 18 |
+
Outgoing edges of ``j`` are ``indices[indptr[j]:indptr[j+1]]`` (postsynaptic rows)
|
| 19 |
+
with ``weights`` = sign × synapse count. The effective weight is ``w_syn × weight``.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
indptr: np.ndarray # int64, n + 1
|
| 23 |
+
indices: np.ndarray # int32
|
| 24 |
+
weights: np.ndarray # int16
|
| 25 |
+
|
| 26 |
+
@property
|
| 27 |
+
def n(self) -> int:
|
| 28 |
+
return len(self.indptr) - 1
|
| 29 |
+
|
| 30 |
+
@classmethod
|
| 31 |
+
def from_edges(cls, pre: np.ndarray, post: np.ndarray, weight: np.ndarray, n: int
|
| 32 |
+
) -> SynapseMatrix:
|
| 33 |
+
"""Build from an edge list. Edges keep their order within each presynaptic neuron."""
|
| 34 |
+
pre = np.asarray(pre, dtype=np.int64)
|
| 35 |
+
order = np.argsort(pre, kind="stable")
|
| 36 |
+
w = np.asarray(weight)[order]
|
| 37 |
+
if len(w) and (w.min() < np.iinfo(np.int16).min or w.max() > np.iinfo(np.int16).max):
|
| 38 |
+
raise ValueError("weight outside int16")
|
| 39 |
+
indptr = np.zeros(n + 1, dtype=np.int64)
|
| 40 |
+
np.cumsum(np.bincount(pre, minlength=n), out=indptr[1:])
|
| 41 |
+
return cls(indptr, np.asarray(post, dtype=np.int32)[order], w.astype(np.int16))
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def from_connectome(cls, c: object) -> SynapseMatrix:
|
| 45 |
+
"""Wrap a :class:`flysim.artifact.Connectome` (no copy)."""
|
| 46 |
+
return cls(c.indptr, c.indices, c.weights) # type: ignore[attr-defined]
|
| 47 |
+
|
| 48 |
+
def validate(self) -> None:
|
| 49 |
+
if self.indptr.dtype != np.int64 or self.indices.dtype != np.int32:
|
| 50 |
+
raise TypeError("indptr must be int64 and indices int32")
|
| 51 |
+
if self.weights.dtype != np.int16:
|
| 52 |
+
raise TypeError("weights must be int16")
|
| 53 |
+
if self.indptr[0] != 0 or not (self.indptr[-1] == len(self.indices) == len(self.weights)):
|
| 54 |
+
raise ValueError("indptr does not match indices/weights")
|
| 55 |
+
if len(self.indices) and (self.indices.min() < 0 or self.indices.max() >= self.n):
|
| 56 |
+
raise ValueError("postsynaptic index out of range")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@dataclass(frozen=True)
|
| 60 |
+
class EngineState:
|
| 61 |
+
step: int
|
| 62 |
+
v: np.ndarray
|
| 63 |
+
g: np.ndarray
|
| 64 |
+
last_spike: np.ndarray
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class Engine(Protocol):
|
| 68 |
+
"""A simulation backend. Steps are ``params.dt`` long and start at 0 after ``reset``."""
|
| 69 |
+
|
| 70 |
+
def load(self, matrix: SynapseMatrix, params: ModelParams) -> None: ...
|
| 71 |
+
|
| 72 |
+
def reset(self) -> None:
|
| 73 |
+
"""Every neuron at rest, ``g = 0``, no inputs scheduled, step 0."""
|
| 74 |
+
|
| 75 |
+
def schedule_inputs(self, schedule: InputSchedule) -> None:
|
| 76 |
+
"""Add input spikes at steps ``>=`` the current step."""
|
| 77 |
+
|
| 78 |
+
def advance_to(self, step: int) -> None: ...
|
| 79 |
+
|
| 80 |
+
def spikes_since(self, step: int) -> tuple[np.ndarray, np.ndarray]:
|
| 81 |
+
"""``(steps, neurons)`` of spikes in ``[step, current step)``."""
|
| 82 |
+
...
|
| 83 |
+
|
| 84 |
+
def snapshot(self) -> EngineState: ...
|
flysim/src/flysim/engine/cpu.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU engine: numba kernel plus the bookkeeping around it."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from flysim.engine.base import EngineState, SynapseMatrix
|
| 8 |
+
from flysim.engine.inputs import InputSchedule
|
| 9 |
+
from flysim.engine.kernel import VEC_BLOCK, run_steps, run_steps_active, run_steps_vec
|
| 10 |
+
from flysim.engine.params import ModelParams
|
| 11 |
+
|
| 12 |
+
_NEVER = np.iinfo(np.int64).min // 2
|
| 13 |
+
_NEVER32 = np.iinfo(np.int32).min // 2
|
| 14 |
+
#: selectable kernels; see :class:`CpuEngine`
|
| 15 |
+
KERNELS = ("plain", "skip_rest", "vec")
|
| 16 |
+
#: skip_rest sweeps every neuron, until reset, once more than n / DENSE_DIV may be off rest
|
| 17 |
+
DENSE_DIV = 2
|
| 18 |
+
#: the same switch for vec, whose dense sweep is cheaper per neuron than its list
|
| 19 |
+
VEC_DENSE_DIV = 8
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class CpuEngine:
|
| 23 |
+
"""Single-threaded event-driven LIF engine.
|
| 24 |
+
|
| 25 |
+
``dtype`` is the state precision. Production and every gated run use float32
|
| 26 |
+
(preregistration, section 1); float64 exists only to diagnose problems.
|
| 27 |
+
|
| 28 |
+
``kernel`` picks the kernel; all give the same spikes and state bit for bit:
|
| 29 |
+
|
| 30 |
+
- ``"plain"``: :func:`~flysim.engine.kernel.run_steps`, the reference every
|
| 31 |
+
preregistered test ran on (also ``skip_rest=False``);
|
| 32 |
+
- ``"skip_rest"``: :func:`~flysim.engine.kernel.run_steps_active`, which visits
|
| 33 |
+
only neurons off rest; identical to plain on all 1,520 chain-test trials, as
|
| 34 |
+
preregistration section 6 requires (``records/validation-log.md``);
|
| 35 |
+
- ``"vec"`` (the default, also ``skip_rest=True``):
|
| 36 |
+
:func:`~flysim.engine.kernel.run_steps_vec`, ``skip_rest`` with an int32
|
| 37 |
+
"refractory until" step and a vectorized dense sweep; identical to plain on all
|
| 38 |
+
1,520 chain-test trials (``records/validation-log.md``).
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, dtype: type[np.floating] = np.float32, skip_rest: bool = True,
|
| 42 |
+
kernel: str | None = None) -> None:
|
| 43 |
+
if kernel is None:
|
| 44 |
+
kernel = "vec" if skip_rest else "plain"
|
| 45 |
+
if kernel not in KERNELS:
|
| 46 |
+
raise ValueError(f"unknown kernel {kernel!r}; one of {KERNELS}")
|
| 47 |
+
self.dtype = np.dtype(dtype)
|
| 48 |
+
self.kernel = kernel
|
| 49 |
+
self.skip_rest = kernel != "plain"
|
| 50 |
+
self.dense_div = VEC_DENSE_DIV if kernel == "vec" else DENSE_DIV
|
| 51 |
+
self._loaded = False
|
| 52 |
+
|
| 53 |
+
# -- Engine protocol ---------------------------------------------------
|
| 54 |
+
def load(self, matrix: SynapseMatrix, params: ModelParams) -> None:
|
| 55 |
+
matrix.validate()
|
| 56 |
+
self.matrix = matrix
|
| 57 |
+
self.params = params
|
| 58 |
+
f = self.dtype.type
|
| 59 |
+
a, b, c = params.coefficients()
|
| 60 |
+
self._scalars = dict(
|
| 61 |
+
v_0=f(params.v_0), v_rst=f(params.v_rst), v_th=f(params.v_th),
|
| 62 |
+
a=f(a), b=f(b), c=f(c), w_syn=f(params.w_syn), w_input=f(params.w_input),
|
| 63 |
+
)
|
| 64 |
+
self._loaded = True
|
| 65 |
+
self.reset()
|
| 66 |
+
|
| 67 |
+
def reset(self) -> None:
|
| 68 |
+
self._require_loaded()
|
| 69 |
+
n = self.matrix.n
|
| 70 |
+
self.v = np.full(n, self.params.v_0, dtype=self.dtype)
|
| 71 |
+
self.g = np.zeros(n, dtype=self.dtype)
|
| 72 |
+
self.last = np.full(n, _NEVER, dtype=np.int64)
|
| 73 |
+
self.rfc = np.full(n, self.params.rfc_steps, dtype=np.int64)
|
| 74 |
+
self.step = 0
|
| 75 |
+
self._log = np.empty(max(4 * n, 1 << 16), dtype=np.int32)
|
| 76 |
+
self._log_len = 0
|
| 77 |
+
self._log_ptr = np.zeros(1024 + 1, dtype=np.int64)
|
| 78 |
+
self._in_steps = np.empty(0, dtype=np.int64)
|
| 79 |
+
self._in_neurons = np.empty(0, dtype=np.int32)
|
| 80 |
+
self._in_ptr = np.zeros(1, dtype=np.int64)
|
| 81 |
+
self._in_idx = np.empty(0, dtype=np.int32)
|
| 82 |
+
self._spk = np.empty(VEC_BLOCK, dtype=np.uint8)
|
| 83 |
+
self._rebuild_until()
|
| 84 |
+
self._rebuild_active()
|
| 85 |
+
|
| 86 |
+
def _rebuild_until(self) -> None:
|
| 87 |
+
"""``vec``'s refractory state from ``last`` and ``rfc``: see ``run_steps_vec``."""
|
| 88 |
+
rfc1 = np.maximum(self.rfc, 1)
|
| 89 |
+
self._rfc1 = rfc1.astype(np.int32)
|
| 90 |
+
self._until = np.where(self.last == _NEVER, _NEVER32, self.last + rfc1).astype(np.int32)
|
| 91 |
+
|
| 92 |
+
def _rebuild_active(self) -> None:
|
| 93 |
+
"""Active list from the state: every neuron not exactly at rest."""
|
| 94 |
+
n = self.matrix.n
|
| 95 |
+
off = np.flatnonzero((self.v != self.dtype.type(self.params.v_0)) | (self.g != 0))
|
| 96 |
+
self._act = np.empty((2, n), dtype=np.int32)
|
| 97 |
+
self._act[0, : len(off)] = off
|
| 98 |
+
self._cur, self._n_act = 0, len(off)
|
| 99 |
+
self._new = np.empty(n, dtype=np.int32)
|
| 100 |
+
self._n_new = 0
|
| 101 |
+
self._flag = np.zeros(n, dtype=np.uint8)
|
| 102 |
+
self._flag[off] = 1
|
| 103 |
+
self._dense = False
|
| 104 |
+
|
| 105 |
+
def schedule_inputs(self, schedule: InputSchedule) -> None:
|
| 106 |
+
self._require_loaded()
|
| 107 |
+
if len(schedule.targets) and (
|
| 108 |
+
schedule.targets.min() < 0 or schedule.targets.max() >= self.matrix.n
|
| 109 |
+
):
|
| 110 |
+
raise ValueError("input target out of range")
|
| 111 |
+
if len(schedule.steps) and schedule.steps[0] < self.step:
|
| 112 |
+
raise ValueError(f"input at step {schedule.steps[0]} is before step {self.step}")
|
| 113 |
+
self.rfc[schedule.targets] = 0
|
| 114 |
+
self._rebuild_until()
|
| 115 |
+
steps = np.concatenate([self._in_steps, schedule.steps])
|
| 116 |
+
neurons = np.concatenate([self._in_neurons, schedule.neurons])
|
| 117 |
+
order = np.argsort(steps, kind="stable")
|
| 118 |
+
self._in_steps, self._in_neurons = steps[order], neurons[order]
|
| 119 |
+
horizon = int(self._in_steps[-1]) + 1 if len(self._in_steps) else 0
|
| 120 |
+
self._in_ptr = np.searchsorted(self._in_steps, np.arange(horizon + 1)).astype(np.int64)
|
| 121 |
+
self._in_idx = self._in_neurons
|
| 122 |
+
|
| 123 |
+
def advance_to(self, step: int) -> None:
|
| 124 |
+
self._require_loaded()
|
| 125 |
+
if step < self.step:
|
| 126 |
+
raise ValueError(f"cannot go back from step {self.step} to {step}")
|
| 127 |
+
if self.kernel == "vec" and step + int(self._rfc1.max(initial=1)) >= 2**31:
|
| 128 |
+
raise ValueError("vec keeps steps in int32: reset before step 2**31")
|
| 129 |
+
if len(self._log_ptr) < step + 2:
|
| 130 |
+
grown = np.zeros(max(step + 2, 2 * len(self._log_ptr)), dtype=np.int64)
|
| 131 |
+
grown[: len(self._log_ptr)] = self._log_ptr
|
| 132 |
+
self._log_ptr = grown
|
| 133 |
+
m, s = self.matrix, self._scalars
|
| 134 |
+
while self.step < step:
|
| 135 |
+
args = (
|
| 136 |
+
self.step, step, self.v, self.g, self.last, self.rfc,
|
| 137 |
+
s["v_0"], s["v_rst"], s["v_th"], s["a"], s["b"], s["c"],
|
| 138 |
+
s["w_syn"], s["w_input"], self.params.delay_steps,
|
| 139 |
+
m.indptr, m.indices, m.weights,
|
| 140 |
+
self._in_ptr, self._in_idx,
|
| 141 |
+
self._log, self._log_ptr, self._log_len,
|
| 142 |
+
)
|
| 143 |
+
if self.kernel == "vec":
|
| 144 |
+
(self.step, self._log_len, self._cur, self._n_act, self._n_new, self._dense
|
| 145 |
+
) = run_steps_vec(*args[:5], self._until, self._rfc1, *args[6:], self._act,
|
| 146 |
+
self._cur, self._n_act, self._new, self._n_new,
|
| 147 |
+
self._flag, self.dense_div, self._dense, self._spk)
|
| 148 |
+
elif self.kernel == "skip_rest":
|
| 149 |
+
(self.step, self._log_len, self._cur, self._n_act, self._n_new, self._dense
|
| 150 |
+
) = run_steps_active(*args, self._act, self._cur, self._n_act, self._new,
|
| 151 |
+
self._n_new, self._flag, self.dense_div, self._dense)
|
| 152 |
+
else:
|
| 153 |
+
self.step, self._log_len = run_steps(*args)
|
| 154 |
+
if self.step < step: # log full: grow it and carry on
|
| 155 |
+
grown = np.empty(2 * len(self._log), dtype=np.int32)
|
| 156 |
+
grown[: self._log_len] = self._log[: self._log_len]
|
| 157 |
+
self._log = grown
|
| 158 |
+
|
| 159 |
+
def spikes_since(self, step: int) -> tuple[np.ndarray, np.ndarray]:
|
| 160 |
+
"""Spikes at steps ``[step, self.step)`` as ``(steps, neurons)``, in time order."""
|
| 161 |
+
step = max(0, min(step, self.step))
|
| 162 |
+
lo, hi = self._log_ptr[step], self._log_ptr[self.step]
|
| 163 |
+
neurons = self._log[lo:hi].copy()
|
| 164 |
+
counts = np.diff(self._log_ptr[step : self.step + 1])
|
| 165 |
+
steps = np.repeat(np.arange(step, self.step, dtype=np.int64), counts)
|
| 166 |
+
return steps, neurons
|
| 167 |
+
|
| 168 |
+
def snapshot(self) -> EngineState:
|
| 169 |
+
return EngineState(
|
| 170 |
+
step=self.step, v=self.v.copy(), g=self.g.copy(), last_spike=self.last.copy()
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# -----------------------------------------------------------------------
|
| 174 |
+
def _require_loaded(self) -> None:
|
| 175 |
+
if not self._loaded:
|
| 176 |
+
raise RuntimeError("call load() first")
|
flysim/src/flysim/engine/inputs.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Poisson stimulus and seeding (records/preregistration.md, section 1).
|
| 2 |
+
|
| 3 |
+
Seeds: every draw comes from ``SeedSequence(20261103)`` with the spawn key
|
| 4 |
+
``(key(experiment), key(condition), trial)``, where ``key`` is the first 8 bytes
|
| 5 |
+
of the string's SHA-256 as an unsigned integer. That makes the tree of child
|
| 6 |
+
seeds a pure function of the fixed condition strings, so the same key and trial
|
| 7 |
+
give the same input trains on any matrix variant and in any process.
|
| 8 |
+
|
| 9 |
+
Two experiments have public names that differ from the strings that are hashed:
|
| 10 |
+
``"chain-tests"`` (condition keys such as ``"LC9/100Hz"`` or ``"control-55/03"``)
|
| 11 |
+
and ``"live"`` (the streaming worker). See :func:`seed_strings`.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import hashlib
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
ROOT_SEED = 20261103
|
| 22 |
+
|
| 23 |
+
#: Seed namespace strings fixed when the recorded runs were made; changing them changes
|
| 24 |
+
#: every seed. Public experiment name -> the namespace string that is hashed; for these
|
| 25 |
+
#: experiments the hashed condition string is ``"<namespace>/<condition>"``.
|
| 26 |
+
_SEED_NAMESPACE = {"chain-tests": "M0.4", "live": "live"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def string_key(s: str) -> int:
|
| 30 |
+
return int.from_bytes(hashlib.sha256(s.encode()).digest()[:8], "big")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def seed_strings(experiment: str, condition: str) -> tuple[str, str]:
|
| 34 |
+
"""The (experiment, condition) strings that are hashed into the spawn key."""
|
| 35 |
+
ns = _SEED_NAMESPACE.get(experiment)
|
| 36 |
+
return (experiment, condition) if ns is None else (ns, f"{ns}/{condition}")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def trial_seed(experiment: str, condition: str, trial: int) -> np.random.SeedSequence:
|
| 40 |
+
if trial < 0:
|
| 41 |
+
raise ValueError("trial must be >= 0")
|
| 42 |
+
e, c = seed_strings(experiment, condition)
|
| 43 |
+
return np.random.SeedSequence(ROOT_SEED, spawn_key=(string_key(e), string_key(c), trial))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def trial_rng(experiment: str, condition: str, trial: int) -> np.random.Generator:
|
| 47 |
+
return np.random.Generator(np.random.PCG64(trial_seed(experiment, condition, trial)))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass(frozen=True)
|
| 51 |
+
class InputSchedule:
|
| 52 |
+
"""Input spikes to inject, sorted by step.
|
| 53 |
+
|
| 54 |
+
``targets`` lists every stimulated neuron, including ones that happen to get
|
| 55 |
+
no input spike (e.g. a 0 Hz group): all of them get refractory period 0, as
|
| 56 |
+
Brian2's ``poi()`` sets it for every PoissonInput target.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
targets: np.ndarray # int32, unique
|
| 60 |
+
steps: np.ndarray # int64, absolute step of each input spike, sorted
|
| 61 |
+
neurons: np.ndarray # int32, target of each input spike
|
| 62 |
+
|
| 63 |
+
def __post_init__(self) -> None:
|
| 64 |
+
if len(self.steps) != len(self.neurons):
|
| 65 |
+
raise ValueError("steps and neurons differ in length")
|
| 66 |
+
if len(self.steps) and np.any(np.diff(self.steps) < 0):
|
| 67 |
+
raise ValueError("input steps must be sorted")
|
| 68 |
+
if len(np.unique(self.targets)) != len(self.targets):
|
| 69 |
+
raise ValueError("targets must be unique")
|
| 70 |
+
if len(self.neurons) and not np.all(np.isin(self.neurons, self.targets)):
|
| 71 |
+
raise ValueError("an input spike goes to a neuron not listed in targets")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def poisson_schedule(
|
| 75 |
+
rng: np.random.Generator,
|
| 76 |
+
targets: np.ndarray,
|
| 77 |
+
rates_hz: float | np.ndarray,
|
| 78 |
+
start_step: int,
|
| 79 |
+
stop_step: int,
|
| 80 |
+
dt_ms: float,
|
| 81 |
+
) -> InputSchedule:
|
| 82 |
+
"""Independent Poisson trains: one Bernoulli(``rate * dt``) draw per target and step.
|
| 83 |
+
|
| 84 |
+
The draws are one ``rng.random((stop - start, len(targets)))`` call in row-major
|
| 85 |
+
order (step, then target in the order given), so a schedule is reproducible
|
| 86 |
+
from the generator state alone.
|
| 87 |
+
"""
|
| 88 |
+
targets = np.asarray(targets, dtype=np.int32)
|
| 89 |
+
rates = np.broadcast_to(np.asarray(rates_hz, dtype=np.float64), targets.shape)
|
| 90 |
+
if np.any(rates < 0):
|
| 91 |
+
raise ValueError("rates must be >= 0")
|
| 92 |
+
p = rates * dt_ms * 1e-3
|
| 93 |
+
n_steps = stop_step - start_step
|
| 94 |
+
if n_steps < 0:
|
| 95 |
+
raise ValueError("stop_step < start_step")
|
| 96 |
+
hits = rng.random((n_steps, len(targets))) < p
|
| 97 |
+
step_i, target_i = np.nonzero(hits) # row-major, so sorted by step
|
| 98 |
+
return InputSchedule(
|
| 99 |
+
targets=targets,
|
| 100 |
+
steps=step_i.astype(np.int64) + start_step,
|
| 101 |
+
neurons=targets[target_i],
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def merge(a: InputSchedule, b: InputSchedule) -> InputSchedule:
|
| 106 |
+
steps = np.concatenate([a.steps, b.steps])
|
| 107 |
+
neurons = np.concatenate([a.neurons, b.neurons])
|
| 108 |
+
order = np.argsort(steps, kind="stable")
|
| 109 |
+
return InputSchedule(
|
| 110 |
+
targets=np.union1d(a.targets, b.targets).astype(np.int32),
|
| 111 |
+
steps=steps[order],
|
| 112 |
+
neurons=neurons[order],
|
| 113 |
+
)
|
flysim/src/flysim/engine/kernel.py
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The numba kernel: one fused pass per time step.
|
| 2 |
+
|
| 3 |
+
Per step ``s`` this follows Brian2's default schedule for Shiu et al.'s model:
|
| 4 |
+
|
| 5 |
+
1. **groups** — every non-refractory neuron advances by the exact propagator.
|
| 6 |
+
Refractory means ``s - last_spike < rfc_steps``; ``v`` and ``g`` are frozen then.
|
| 7 |
+
A neuron exactly at rest (``v == v_0`` and ``g == 0``) is skipped: the update
|
| 8 |
+
would leave it unchanged bit for bit, so this is an exact optimization.
|
| 9 |
+
2. **thresholds** — a non-refractory neuron with ``v > v_th`` spikes at step ``s``.
|
| 10 |
+
3. **synapses** — the spikes of step ``s - delay`` deliver ``w_syn * W[post, pre]``
|
| 11 |
+
to ``g``, then this step's Poisson inputs add ``w_input`` to ``v``. Both writes
|
| 12 |
+
are **dropped** for a neuron that is refractory or spiked in this step: Brian2
|
| 13 |
+
marks ``(unless refractory)`` variables with ``set_conditional_write(not_refractory)``,
|
| 14 |
+
which guards every code object writing them (synaptic ``on_pre`` and
|
| 15 |
+
``PoissonInput`` included), and the thresholder has already set
|
| 16 |
+
``not_refractory = False`` for this step's spikes, also when ``rfc`` is 0.
|
| 17 |
+
4. **resets** — neurons that spiked at ``s`` get ``v = v_rst`` and ``g = 0``
|
| 18 |
+
(the resetter alone overrides the conditional write).
|
| 19 |
+
|
| 20 |
+
The spike log doubles as the delay line ("sparse ring buffer"): delivery reads
|
| 21 |
+
the log entries of step ``s - delay`` and walks only those neurons' outgoing
|
| 22 |
+
edges in the CSC matrix.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import numba
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@numba.njit(cache=True, nogil=True, boundscheck=False)
|
| 32 |
+
def run_steps( # noqa: PLR0913 - a flat signature keeps the kernel numba-friendly
|
| 33 |
+
s0: int,
|
| 34 |
+
s1: int,
|
| 35 |
+
v: np.ndarray,
|
| 36 |
+
g: np.ndarray,
|
| 37 |
+
last: np.ndarray,
|
| 38 |
+
rfc: np.ndarray,
|
| 39 |
+
v_0: float,
|
| 40 |
+
v_rst: float,
|
| 41 |
+
v_th: float,
|
| 42 |
+
a: float,
|
| 43 |
+
b: float,
|
| 44 |
+
c: float,
|
| 45 |
+
w_syn: float,
|
| 46 |
+
w_input: float,
|
| 47 |
+
delay: int,
|
| 48 |
+
indptr: np.ndarray,
|
| 49 |
+
indices: np.ndarray,
|
| 50 |
+
weights: np.ndarray,
|
| 51 |
+
in_ptr: np.ndarray,
|
| 52 |
+
in_idx: np.ndarray,
|
| 53 |
+
log: np.ndarray,
|
| 54 |
+
log_ptr: np.ndarray,
|
| 55 |
+
log_len: int,
|
| 56 |
+
) -> tuple[int, int]:
|
| 57 |
+
"""Advance steps ``[s0, s1)``. Returns ``(next_step, log_len)``.
|
| 58 |
+
|
| 59 |
+
Stops early, before a step, when the spike log might not have room for it
|
| 60 |
+
(fewer than ``n`` free slots); the caller grows the log and calls again.
|
| 61 |
+
``in_ptr`` covers absolute steps ``[0, len(in_ptr) - 1)``.
|
| 62 |
+
"""
|
| 63 |
+
n = v.shape[0]
|
| 64 |
+
zero = v.dtype.type(0)
|
| 65 |
+
n_in_steps = in_ptr.shape[0] - 1
|
| 66 |
+
for s in range(s0, s1):
|
| 67 |
+
if log_len + n > log.shape[0]:
|
| 68 |
+
return s, log_len
|
| 69 |
+
start = log_len
|
| 70 |
+
log_ptr[s] = start
|
| 71 |
+
|
| 72 |
+
# 1 + 2: integrate and threshold
|
| 73 |
+
for i in range(n):
|
| 74 |
+
if s - last[i] < rfc[i]:
|
| 75 |
+
continue
|
| 76 |
+
vi = v[i]
|
| 77 |
+
gi = g[i]
|
| 78 |
+
if gi == zero and vi == v_0:
|
| 79 |
+
continue
|
| 80 |
+
vi = v_0 + (vi - v_0) * a + gi * b
|
| 81 |
+
g[i] = gi * c
|
| 82 |
+
v[i] = vi
|
| 83 |
+
if vi > v_th:
|
| 84 |
+
log[log_len] = i
|
| 85 |
+
log_len += 1
|
| 86 |
+
last[i] = s
|
| 87 |
+
log_ptr[s + 1] = log_len
|
| 88 |
+
|
| 89 |
+
# 3: synaptic delivery, then Poisson input
|
| 90 |
+
sd = s - delay
|
| 91 |
+
if sd >= 0:
|
| 92 |
+
for k in range(log_ptr[sd], log_ptr[sd + 1]):
|
| 93 |
+
j = log[k]
|
| 94 |
+
for e in range(indptr[j], indptr[j + 1]):
|
| 95 |
+
i = indices[e]
|
| 96 |
+
since = s - last[i]
|
| 97 |
+
if since >= rfc[i] and since != 0: # not refractory, not spiked now
|
| 98 |
+
g[i] += w_syn * weights[e]
|
| 99 |
+
if s < n_in_steps:
|
| 100 |
+
for k in range(in_ptr[s], in_ptr[s + 1]):
|
| 101 |
+
i = in_idx[k]
|
| 102 |
+
since = s - last[i]
|
| 103 |
+
if since >= rfc[i] and since != 0:
|
| 104 |
+
v[i] += w_input
|
| 105 |
+
|
| 106 |
+
# 4: reset
|
| 107 |
+
for k in range(start, log_len):
|
| 108 |
+
i = log[k]
|
| 109 |
+
v[i] = v_rst
|
| 110 |
+
g[i] = zero
|
| 111 |
+
return s1, log_len
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@numba.njit(cache=True, nogil=True, boundscheck=False)
|
| 115 |
+
def run_steps_active( # noqa: PLR0913, PLR0912, PLR0915 - see run_steps
|
| 116 |
+
s0: int,
|
| 117 |
+
s1: int,
|
| 118 |
+
v: np.ndarray,
|
| 119 |
+
g: np.ndarray,
|
| 120 |
+
last: np.ndarray,
|
| 121 |
+
rfc: np.ndarray,
|
| 122 |
+
v_0: float,
|
| 123 |
+
v_rst: float,
|
| 124 |
+
v_th: float,
|
| 125 |
+
a: float,
|
| 126 |
+
b: float,
|
| 127 |
+
c: float,
|
| 128 |
+
w_syn: float,
|
| 129 |
+
w_input: float,
|
| 130 |
+
delay: int,
|
| 131 |
+
indptr: np.ndarray,
|
| 132 |
+
indices: np.ndarray,
|
| 133 |
+
weights: np.ndarray,
|
| 134 |
+
in_ptr: np.ndarray,
|
| 135 |
+
in_idx: np.ndarray,
|
| 136 |
+
log: np.ndarray,
|
| 137 |
+
log_ptr: np.ndarray,
|
| 138 |
+
log_len: int,
|
| 139 |
+
act: np.ndarray,
|
| 140 |
+
cur: int,
|
| 141 |
+
n_act: int,
|
| 142 |
+
new: np.ndarray,
|
| 143 |
+
n_new: int,
|
| 144 |
+
flag: np.ndarray,
|
| 145 |
+
dense_div: int,
|
| 146 |
+
dense: bool,
|
| 147 |
+
) -> tuple[int, int, int, int, int, bool]:
|
| 148 |
+
""":func:`run_steps` that visits only neurons off rest ("skip neurons that are
|
| 149 |
+
exactly at rest"). Returns ``(next_step, log_len, cur, n_act, n_new, dense)``.
|
| 150 |
+
|
| 151 |
+
Exact by construction: a neuron at rest (``v == v_0``, ``g == 0``) is skipped by
|
| 152 |
+
:func:`run_steps` as well and cannot cross threshold. ``act[cur, :n_act]`` lists, in
|
| 153 |
+
ascending index order, every neuron that may be off rest; ``new[:n_new]`` the
|
| 154 |
+
neurons that left rest since (``flag`` marks members of either list). Each step
|
| 155 |
+
merges the two in index order, so neurons are visited, and spikes logged and
|
| 156 |
+
delivered, in exactly the order of :func:`run_steps`, and every float sum is
|
| 157 |
+
the same. A neuron found at rest is dropped from the list.
|
| 158 |
+
|
| 159 |
+
Once more than ``n / dense_div`` neurons may be off rest, the kernel turns
|
| 160 |
+
``dense``: from then on each step sweeps every neuron in index order, testing
|
| 161 |
+
rest first, and keeps no list. Neurons touched by a stimulus stay off rest for
|
| 162 |
+
the rest of the trial (``g`` reaches exactly 0 only after thousands of steps),
|
| 163 |
+
so the mode stays until the caller resets. Both modes visit the same off-rest
|
| 164 |
+
neurons in the same order.
|
| 165 |
+
"""
|
| 166 |
+
n = v.shape[0]
|
| 167 |
+
zero = v.dtype.type(0)
|
| 168 |
+
n_in_steps = in_ptr.shape[0] - 1
|
| 169 |
+
for s in range(s0, s1):
|
| 170 |
+
if log_len + n > log.shape[0]:
|
| 171 |
+
return s, log_len, cur, n_act, n_new, dense
|
| 172 |
+
start = log_len
|
| 173 |
+
log_ptr[s] = start
|
| 174 |
+
|
| 175 |
+
nxt = 1 - cur
|
| 176 |
+
out = 0
|
| 177 |
+
if not dense and (n_act + n_new) * dense_div > n:
|
| 178 |
+
dense = True
|
| 179 |
+
if dense:
|
| 180 |
+
# 1 + 2, dense: every neuron in index order, rest tested first
|
| 181 |
+
for i in range(n):
|
| 182 |
+
vi = v[i]
|
| 183 |
+
gi = g[i]
|
| 184 |
+
if gi == zero and vi == v_0:
|
| 185 |
+
continue
|
| 186 |
+
if s - last[i] < rfc[i]:
|
| 187 |
+
continue
|
| 188 |
+
vi = v_0 + (vi - v_0) * a + gi * b
|
| 189 |
+
g[i] = gi * c
|
| 190 |
+
v[i] = vi
|
| 191 |
+
if vi > v_th:
|
| 192 |
+
log[log_len] = i
|
| 193 |
+
log_len += 1
|
| 194 |
+
last[i] = s
|
| 195 |
+
else:
|
| 196 |
+
# 1 + 2, sparse: act ∪ new in index order; survivors go to the other buffer
|
| 197 |
+
fresh = np.sort(new[:n_new])
|
| 198 |
+
n_new = 0
|
| 199 |
+
p = 0
|
| 200 |
+
q = 0
|
| 201 |
+
while p < n_act or q < fresh.shape[0]:
|
| 202 |
+
if q >= fresh.shape[0] or (p < n_act and act[cur, p] < fresh[q]):
|
| 203 |
+
i = act[cur, p]
|
| 204 |
+
p += 1
|
| 205 |
+
else:
|
| 206 |
+
i = fresh[q]
|
| 207 |
+
q += 1
|
| 208 |
+
vi = v[i]
|
| 209 |
+
gi = g[i]
|
| 210 |
+
if gi == zero and vi == v_0:
|
| 211 |
+
flag[i] = 0
|
| 212 |
+
continue
|
| 213 |
+
act[nxt, out] = i
|
| 214 |
+
out += 1
|
| 215 |
+
if s - last[i] < rfc[i]:
|
| 216 |
+
continue
|
| 217 |
+
vi = v_0 + (vi - v_0) * a + gi * b
|
| 218 |
+
g[i] = gi * c
|
| 219 |
+
v[i] = vi
|
| 220 |
+
if vi > v_th:
|
| 221 |
+
log[log_len] = i
|
| 222 |
+
log_len += 1
|
| 223 |
+
last[i] = s
|
| 224 |
+
if not dense:
|
| 225 |
+
cur = nxt
|
| 226 |
+
n_act = out
|
| 227 |
+
log_ptr[s + 1] = log_len
|
| 228 |
+
|
| 229 |
+
# 3: synaptic delivery, then Poisson input (a write puts the neuron on the list)
|
| 230 |
+
sd = s - delay
|
| 231 |
+
if sd >= 0:
|
| 232 |
+
for k in range(log_ptr[sd], log_ptr[sd + 1]):
|
| 233 |
+
j = log[k]
|
| 234 |
+
for e in range(indptr[j], indptr[j + 1]):
|
| 235 |
+
i = indices[e]
|
| 236 |
+
since = s - last[i]
|
| 237 |
+
if since >= rfc[i] and since != 0:
|
| 238 |
+
g[i] += w_syn * weights[e]
|
| 239 |
+
if not dense and flag[i] == 0:
|
| 240 |
+
flag[i] = 1
|
| 241 |
+
new[n_new] = i
|
| 242 |
+
n_new += 1
|
| 243 |
+
if s < n_in_steps:
|
| 244 |
+
for k in range(in_ptr[s], in_ptr[s + 1]):
|
| 245 |
+
i = in_idx[k]
|
| 246 |
+
since = s - last[i]
|
| 247 |
+
if since >= rfc[i] and since != 0:
|
| 248 |
+
v[i] += w_input
|
| 249 |
+
if not dense and flag[i] == 0:
|
| 250 |
+
flag[i] = 1
|
| 251 |
+
new[n_new] = i
|
| 252 |
+
n_new += 1
|
| 253 |
+
|
| 254 |
+
# 4: reset (the neuron is on the list: it was visited this step)
|
| 255 |
+
for k in range(start, log_len):
|
| 256 |
+
i = log[k]
|
| 257 |
+
v[i] = v_rst
|
| 258 |
+
g[i] = zero
|
| 259 |
+
return s1, log_len, cur, n_act, n_new, dense
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
#: neurons per block of the vectorized dense sweep in :func:`run_steps_vec`
|
| 263 |
+
VEC_BLOCK = 512
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@numba.njit(cache=True, nogil=True, boundscheck=False)
|
| 267 |
+
def _sweep( # noqa: PLR0913
|
| 268 |
+
v: np.ndarray,
|
| 269 |
+
g: np.ndarray,
|
| 270 |
+
until: np.ndarray,
|
| 271 |
+
s: int,
|
| 272 |
+
v_0: float,
|
| 273 |
+
a: float,
|
| 274 |
+
b: float,
|
| 275 |
+
c: float,
|
| 276 |
+
v_th: float,
|
| 277 |
+
spk: np.ndarray,
|
| 278 |
+
) -> int:
|
| 279 |
+
"""Dense update of one block (the arrays are views of it). Marks spikes in ``spk``
|
| 280 |
+
and returns their number. Branch free, so LLVM vectorizes it; see :func:`run_steps_vec`.
|
| 281 |
+
"""
|
| 282 |
+
zero = v.dtype.type(0)
|
| 283 |
+
hits = 0
|
| 284 |
+
for i in range(v.shape[0]):
|
| 285 |
+
vi = v[i]
|
| 286 |
+
gi = g[i]
|
| 287 |
+
ok = (s >= until[i]) & ((gi != zero) | (vi != v_0)) # not refractory, not at rest
|
| 288 |
+
vn = v_0 + (vi - v_0) * a + gi * b
|
| 289 |
+
gn = gi * c
|
| 290 |
+
v[i] = vn if ok else vi
|
| 291 |
+
g[i] = gn if ok else gi
|
| 292 |
+
hit = ok & (vn > v_th)
|
| 293 |
+
spk[i] = hit
|
| 294 |
+
hits += hit
|
| 295 |
+
return hits
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
@numba.njit(cache=True, nogil=True, boundscheck=False)
|
| 299 |
+
def run_steps_vec( # noqa: PLR0913, PLR0912, PLR0915 - see run_steps
|
| 300 |
+
s0: int,
|
| 301 |
+
s1: int,
|
| 302 |
+
v: np.ndarray,
|
| 303 |
+
g: np.ndarray,
|
| 304 |
+
last: np.ndarray,
|
| 305 |
+
until: np.ndarray,
|
| 306 |
+
rfc1: np.ndarray,
|
| 307 |
+
v_0: float,
|
| 308 |
+
v_rst: float,
|
| 309 |
+
v_th: float,
|
| 310 |
+
a: float,
|
| 311 |
+
b: float,
|
| 312 |
+
c: float,
|
| 313 |
+
w_syn: float,
|
| 314 |
+
w_input: float,
|
| 315 |
+
delay: int,
|
| 316 |
+
indptr: np.ndarray,
|
| 317 |
+
indices: np.ndarray,
|
| 318 |
+
weights: np.ndarray,
|
| 319 |
+
in_ptr: np.ndarray,
|
| 320 |
+
in_idx: np.ndarray,
|
| 321 |
+
log: np.ndarray,
|
| 322 |
+
log_ptr: np.ndarray,
|
| 323 |
+
log_len: int,
|
| 324 |
+
act: np.ndarray,
|
| 325 |
+
cur: int,
|
| 326 |
+
n_act: int,
|
| 327 |
+
new: np.ndarray,
|
| 328 |
+
n_new: int,
|
| 329 |
+
flag: np.ndarray,
|
| 330 |
+
dense_div: int,
|
| 331 |
+
dense: bool,
|
| 332 |
+
spk: np.ndarray,
|
| 333 |
+
) -> tuple[int, int, int, int, int, bool]:
|
| 334 |
+
""":func:`run_steps_active` with narrow refractory state and a vectorized dense sweep.
|
| 335 |
+
|
| 336 |
+
**Refractory state.** ``until[i]`` (int32) is the first step at which neuron ``i``
|
| 337 |
+
may be written again: ``last[i] + max(rfc[i], 1)``, set when it spikes (``rfc1``
|
| 338 |
+
holds ``max(rfc, 1)``; ``last`` is still written, for snapshots, but never read).
|
| 339 |
+
This reproduces both tests of :func:`run_steps` exactly:
|
| 340 |
+
|
| 341 |
+
- *integration* at step ``s`` (always ``s > last[i]``): ``s - last < rfc`` is
|
| 342 |
+
``s < until`` (for ``rfc == 0`` neither holds, as ``s >= last + 1``);
|
| 343 |
+
- *conditional write* at step ``s`` (``s >= last``): ``since >= rfc and since != 0``
|
| 344 |
+
is ``s >= until`` (``max(rfc, 1)`` supplies the ``since != 0`` part for ``rfc == 0``).
|
| 345 |
+
|
| 346 |
+
The caller rebuilds ``until`` whenever ``rfc`` changes.
|
| 347 |
+
|
| 348 |
+
**Dense sweep.** :func:`run_steps_active`'s dense loop branches per neuron and logs
|
| 349 |
+
spikes inside the loop; those stores keep LLVM from vectorizing it. Here the update
|
| 350 |
+
of a block of :data:`VEC_BLOCK` neurons is a separate loop, :func:`_sweep`, with no
|
| 351 |
+
branches: it computes the update for every neuron and keeps it, with a select, only
|
| 352 |
+
for those neither refractory nor exactly at rest (the tests of :func:`run_steps`),
|
| 353 |
+
and marks spikes in ``spk``. Then the block's spikes are logged in index order.
|
| 354 |
+
The float operations and their order are those of :func:`run_steps` (no fastmath,
|
| 355 |
+
no reassociation), so every value is identical, and so are the log order and
|
| 356 |
+
hence the delivery sums. The sparse path is :func:`run_steps_active`'s, with the
|
| 357 |
+
refractory test above.
|
| 358 |
+
"""
|
| 359 |
+
n = v.shape[0]
|
| 360 |
+
zero = v.dtype.type(0)
|
| 361 |
+
n_in_steps = in_ptr.shape[0] - 1
|
| 362 |
+
for s in range(s0, s1):
|
| 363 |
+
if log_len + n > log.shape[0]:
|
| 364 |
+
return s, log_len, cur, n_act, n_new, dense
|
| 365 |
+
start = log_len
|
| 366 |
+
log_ptr[s] = start
|
| 367 |
+
|
| 368 |
+
nxt = 1 - cur
|
| 369 |
+
out = 0
|
| 370 |
+
if not dense and (n_act + n_new) * dense_div > n:
|
| 371 |
+
dense = True
|
| 372 |
+
if dense:
|
| 373 |
+
# 1 + 2, dense: every neuron, in blocks; a select instead of branches
|
| 374 |
+
for b0 in range(0, n, VEC_BLOCK):
|
| 375 |
+
b1 = min(b0 + VEC_BLOCK, n)
|
| 376 |
+
if _sweep(v[b0:b1], g[b0:b1], until[b0:b1], s, v_0, a, b, c, v_th, spk):
|
| 377 |
+
for j in range(b1 - b0): # log this block's spikes in index order
|
| 378 |
+
if spk[j]:
|
| 379 |
+
i = b0 + j
|
| 380 |
+
log[log_len] = i
|
| 381 |
+
log_len += 1
|
| 382 |
+
last[i] = s
|
| 383 |
+
until[i] = s + rfc1[i]
|
| 384 |
+
else:
|
| 385 |
+
# 1 + 2, sparse: act ∪ new in index order; survivors go to the other buffer
|
| 386 |
+
fresh = np.sort(new[:n_new])
|
| 387 |
+
n_new = 0
|
| 388 |
+
p = 0
|
| 389 |
+
q = 0
|
| 390 |
+
while p < n_act or q < fresh.shape[0]:
|
| 391 |
+
if q >= fresh.shape[0] or (p < n_act and act[cur, p] < fresh[q]):
|
| 392 |
+
i = act[cur, p]
|
| 393 |
+
p += 1
|
| 394 |
+
else:
|
| 395 |
+
i = fresh[q]
|
| 396 |
+
q += 1
|
| 397 |
+
vi = v[i]
|
| 398 |
+
gi = g[i]
|
| 399 |
+
if gi == zero and vi == v_0:
|
| 400 |
+
flag[i] = 0
|
| 401 |
+
continue
|
| 402 |
+
act[nxt, out] = i
|
| 403 |
+
out += 1
|
| 404 |
+
if s < until[i]:
|
| 405 |
+
continue
|
| 406 |
+
vi = v_0 + (vi - v_0) * a + gi * b
|
| 407 |
+
g[i] = gi * c
|
| 408 |
+
v[i] = vi
|
| 409 |
+
if vi > v_th:
|
| 410 |
+
log[log_len] = i
|
| 411 |
+
log_len += 1
|
| 412 |
+
last[i] = s
|
| 413 |
+
until[i] = s + rfc1[i]
|
| 414 |
+
if not dense:
|
| 415 |
+
cur = nxt
|
| 416 |
+
n_act = out
|
| 417 |
+
log_ptr[s + 1] = log_len
|
| 418 |
+
|
| 419 |
+
# 3: synaptic delivery, then Poisson input (a write puts the neuron on the list)
|
| 420 |
+
sd = s - delay
|
| 421 |
+
if sd >= 0:
|
| 422 |
+
for k in range(log_ptr[sd], log_ptr[sd + 1]):
|
| 423 |
+
j = log[k]
|
| 424 |
+
for e in range(indptr[j], indptr[j + 1]):
|
| 425 |
+
i = indices[e]
|
| 426 |
+
if s >= until[i]:
|
| 427 |
+
g[i] += w_syn * weights[e]
|
| 428 |
+
if not dense and flag[i] == 0:
|
| 429 |
+
flag[i] = 1
|
| 430 |
+
new[n_new] = i
|
| 431 |
+
n_new += 1
|
| 432 |
+
if s < n_in_steps:
|
| 433 |
+
for k in range(in_ptr[s], in_ptr[s + 1]):
|
| 434 |
+
i = in_idx[k]
|
| 435 |
+
if s >= until[i]:
|
| 436 |
+
v[i] += w_input
|
| 437 |
+
if not dense and flag[i] == 0:
|
| 438 |
+
flag[i] = 1
|
| 439 |
+
new[n_new] = i
|
| 440 |
+
n_new += 1
|
| 441 |
+
|
| 442 |
+
# 4: reset
|
| 443 |
+
for k in range(start, log_len):
|
| 444 |
+
i = log[k]
|
| 445 |
+
v[i] = v_rst
|
| 446 |
+
g[i] = zero
|
| 447 |
+
return s1, log_len, cur, n_act, n_new, dense
|
flysim/src/flysim/engine/params.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fixed model parameters (records/preregistration.md, section 1, after Shiu et al.'s ``model.py``).
|
| 2 |
+
|
| 3 |
+
Units are mV and ms throughout. Everything a run needs to be reproduced lives in
|
| 4 |
+
:class:`ModelParams`; the engine derives its integer step counts and float32
|
| 5 |
+
update coefficients from it.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import math
|
| 11 |
+
from dataclasses import asdict, dataclass
|
| 12 |
+
|
| 13 |
+
#: FAFB weight per synapse (Shiu et al.), mV.
|
| 14 |
+
W_SYN_FAFB = 0.275
|
| 15 |
+
#: MaleCNS ÷ FAFB v630 synapse-density ratio R (records/preregistration.md, section 3),
|
| 16 |
+
#: computed by ``flysim.validation.weight_scale`` on 2026-11-04; record in
|
| 17 |
+
#: ``records/results/weight-scale.*``.
|
| 18 |
+
R_MALECNS = 1.7504725897920606
|
| 19 |
+
#: MaleCNS weight per synapse for the chain tests (preregistration, section 3: 0.275 mV / R), mV.
|
| 20 |
+
#: The Poisson input weight stays ``W_SYN_FAFB * F_POI`` (preregistration, section 1).
|
| 21 |
+
W_SYN_MALE = W_SYN_FAFB / R_MALECNS
|
| 22 |
+
#: Poisson input weight factor: each input spike adds ``w_syn * F_POI`` to ``v``.
|
| 23 |
+
F_POI = 250
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass(frozen=True)
|
| 27 |
+
class ModelParams:
|
| 28 |
+
v_0: float = -52.0 # resting potential, mV
|
| 29 |
+
v_rst: float = -52.0 # reset potential, mV
|
| 30 |
+
v_th: float = -45.0 # threshold, mV
|
| 31 |
+
t_mbr: float = 20.0 # membrane time constant, ms
|
| 32 |
+
tau: float = 5.0 # synaptic time constant, ms
|
| 33 |
+
t_rfc: float = 2.2 # refractory period, ms (0 for stimulated neurons)
|
| 34 |
+
t_dly: float = 1.8 # synaptic delay, ms
|
| 35 |
+
dt: float = 0.1 # time step, ms
|
| 36 |
+
w_syn: float = W_SYN_FAFB # mV per synapse
|
| 37 |
+
#: Weight of one Poisson input spike, mV. Not rescaled on MaleCNS (preregistration, section 1).
|
| 38 |
+
w_input: float = W_SYN_FAFB * F_POI
|
| 39 |
+
|
| 40 |
+
# Step counts, rounded as Brian2 does (``timestep(x, dt)``).
|
| 41 |
+
@property
|
| 42 |
+
def rfc_steps(self) -> int:
|
| 43 |
+
return _steps(self.t_rfc, self.dt)
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def delay_steps(self) -> int:
|
| 47 |
+
return _steps(self.t_dly, self.dt)
|
| 48 |
+
|
| 49 |
+
def coefficients(self) -> tuple[float, float, float]:
|
| 50 |
+
"""Exact one-step propagator of the linear system (frozen while refractory).
|
| 51 |
+
|
| 52 |
+
With ``u = v - v_0``: ``u' = (-u + g) / t_mbr`` and ``g' = -g / tau``, so over one
|
| 53 |
+
step ``u <- a u + b g`` and ``g <- c g`` with the values returned here.
|
| 54 |
+
"""
|
| 55 |
+
a = math.exp(-self.dt / self.t_mbr)
|
| 56 |
+
c = math.exp(-self.dt / self.tau)
|
| 57 |
+
b = self.tau / (self.tau - self.t_mbr) * (c - a)
|
| 58 |
+
return a, b, c
|
| 59 |
+
|
| 60 |
+
def to_dict(self) -> dict[str, float]:
|
| 61 |
+
return asdict(self)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _steps(t: float, dt: float) -> int:
|
| 65 |
+
# Brian2: timestep(t, dt) = int((t + 1e-3 * dt) / dt)
|
| 66 |
+
return int((t + 1e-3 * dt) / dt)
|
flysim/src/flysim/live/__init__.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Live simulation worker: blocks stepped in 10 ms chunks, a process pool with
|
| 2 |
+
one engine per worker, a queue with a wait estimate, and a replay cache.
|
| 3 |
+
|
| 4 |
+
Design notes and the message format: ``docs/live-sim.md``.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from flysim.live.cache import Recording, ReplayCache
|
| 8 |
+
from flysim.live.model import (
|
| 9 |
+
BLOCK_S,
|
| 10 |
+
CHUNK_STEPS,
|
| 11 |
+
MAX_RATE_HZ,
|
| 12 |
+
N_CHUNKS,
|
| 13 |
+
STIMULI,
|
| 14 |
+
BlockSpec,
|
| 15 |
+
Chunk,
|
| 16 |
+
ConnectomeSource,
|
| 17 |
+
InMemorySource,
|
| 18 |
+
InvalidRequest,
|
| 19 |
+
LiveModel,
|
| 20 |
+
LiveStimulus,
|
| 21 |
+
ModelSource,
|
| 22 |
+
make_engine,
|
| 23 |
+
model_fingerprint,
|
| 24 |
+
round_rate,
|
| 25 |
+
run_block,
|
| 26 |
+
)
|
| 27 |
+
from flysim.live.pool import PoolUnavailable, WorkerPool, expected_wait
|
| 28 |
+
from flysim.live.service import BlockRequest, LiveConfig, LiveService
|
| 29 |
+
|
| 30 |
+
__all__ = [
|
| 31 |
+
"BLOCK_S",
|
| 32 |
+
"CHUNK_STEPS",
|
| 33 |
+
"MAX_RATE_HZ",
|
| 34 |
+
"N_CHUNKS",
|
| 35 |
+
"STIMULI",
|
| 36 |
+
"BlockRequest",
|
| 37 |
+
"BlockSpec",
|
| 38 |
+
"Chunk",
|
| 39 |
+
"ConnectomeSource",
|
| 40 |
+
"InMemorySource",
|
| 41 |
+
"InvalidRequest",
|
| 42 |
+
"LiveConfig",
|
| 43 |
+
"LiveModel",
|
| 44 |
+
"LiveService",
|
| 45 |
+
"LiveStimulus",
|
| 46 |
+
"ModelSource",
|
| 47 |
+
"PoolUnavailable",
|
| 48 |
+
"Recording",
|
| 49 |
+
"ReplayCache",
|
| 50 |
+
"WorkerPool",
|
| 51 |
+
"expected_wait",
|
| 52 |
+
"make_engine",
|
| 53 |
+
"model_fingerprint",
|
| 54 |
+
"round_rate",
|
| 55 |
+
"run_block",
|
| 56 |
+
]
|
flysim/src/flysim/live/brain.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Neuron positions packed for a 3D viewer in a browser client.
|
| 2 |
+
|
| 3 |
+
Such a viewer draws about 165k points coloured by recent activity. It needs each neuron's
|
| 4 |
+
position in the order of the spike indices the stream sends (the row order of
|
| 5 |
+
``neurons.parquet``), plus which neurons the stimuli drive and which are the readouts.
|
| 6 |
+
This module reads that from a fetched ``connectome-v1`` directory once and packs it:
|
| 7 |
+
|
| 8 |
+
- ``meta`` (JSON): the count, the bounding box in voxels, the region names, the
|
| 9 |
+
stimulus targets and the readout neurons per side;
|
| 10 |
+
- ``blob`` (binary, little-endian): ``n × 3`` uint16 positions, each axis scaled from the
|
| 11 |
+
bounding box to [0, 65534] (65535 on all three axes: no position), then ``n`` uint8
|
| 12 |
+
region codes. About 1.1 MB, a resolution of 1.5 voxels (12 nm) on the longest axis.
|
| 13 |
+
|
| 14 |
+
Positions are the artefact's: the soma where it was traced, else the "to soma"
|
| 15 |
+
location, else the synapse-weighted mean of the partners (``docs/connectome-artifact.md``).
|
| 16 |
+
There is no neuropil mesh in the artefact; the soma cloud itself gives the shape.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import hashlib
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import pyarrow.parquet as pq
|
| 27 |
+
|
| 28 |
+
from flysim.validation import chains
|
| 29 |
+
|
| 30 |
+
from .model import READOUTS, STIMULI, LiveModel
|
| 31 |
+
|
| 32 |
+
FORMAT = 1
|
| 33 |
+
MISSING = 0xFFFF
|
| 34 |
+
SCALE = 0xFFFE
|
| 35 |
+
#: MaleCNS voxels are 8 nm.
|
| 36 |
+
VOXEL_NM = 8.0
|
| 37 |
+
|
| 38 |
+
#: Coarse regions for the resting cloud's tint, by the neuron's superclass.
|
| 39 |
+
REGIONS: tuple[str, ...] = ("optic lobe", "central brain", "ventral nerve cord",
|
| 40 |
+
"descending and ascending", "other")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def region_of(superclass: object) -> int:
|
| 44 |
+
s = str(superclass or "")
|
| 45 |
+
if s.startswith(("ol_", "visual_")):
|
| 46 |
+
return 0
|
| 47 |
+
if s.startswith("cb_"):
|
| 48 |
+
return 1
|
| 49 |
+
if s.startswith("vnc_"):
|
| 50 |
+
return 2
|
| 51 |
+
if s.startswith(("descending", "ascending", "efferent_ascending", "efferent_descending")):
|
| 52 |
+
return 3
|
| 53 |
+
return 4
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@dataclass(frozen=True)
|
| 57 |
+
class BrainLayout:
|
| 58 |
+
meta: dict[str, object]
|
| 59 |
+
blob: bytes
|
| 60 |
+
|
| 61 |
+
@property
|
| 62 |
+
def etag(self) -> str:
|
| 63 |
+
return str(self.meta["etag"])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def pack(xyz: np.ndarray, regions: np.ndarray) -> tuple[bytes, list[float], list[float]]:
|
| 67 |
+
"""Quantize ``xyz`` (n × 3, NaN where unknown) to the blob; also the box it spans."""
|
| 68 |
+
xyz = np.asarray(xyz, dtype=np.float64)
|
| 69 |
+
known = np.isfinite(xyz).all(axis=1)
|
| 70 |
+
if known.any():
|
| 71 |
+
lo, hi = xyz[known].min(axis=0), xyz[known].max(axis=0)
|
| 72 |
+
else:
|
| 73 |
+
lo = hi = np.zeros(3)
|
| 74 |
+
span = np.where(hi > lo, hi - lo, 1.0)
|
| 75 |
+
q = np.full(xyz.shape, MISSING, dtype=np.uint16)
|
| 76 |
+
q[known] = np.rint((xyz[known] - lo) / span * SCALE).astype(np.uint16)
|
| 77 |
+
blob = q.astype("<u2").tobytes() + np.asarray(regions, dtype=np.uint8).tobytes()
|
| 78 |
+
return blob, [float(v) for v in lo], [float(v) for v in hi]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def build(directory: Path) -> BrainLayout:
|
| 82 |
+
"""The layout of a fetched ``connectome-v1`` directory."""
|
| 83 |
+
t = pq.read_table(directory / "neurons.parquet",
|
| 84 |
+
columns=["idx", "x", "y", "z", "superclass"])
|
| 85 |
+
n = t.num_rows
|
| 86 |
+
if not np.array_equal(t["idx"].to_numpy(), np.arange(n)):
|
| 87 |
+
raise ValueError("neurons.parquet is not in index order")
|
| 88 |
+
xyz = np.stack([t[c].to_numpy(zero_copy_only=False).astype(np.float64)
|
| 89 |
+
for c in ("x", "y", "z")], axis=1)
|
| 90 |
+
regions = np.fromiter((region_of(s) for s in t["superclass"].to_pylist()),
|
| 91 |
+
dtype=np.uint8, count=n)
|
| 92 |
+
neurons = chains.Neurons.load(directory)
|
| 93 |
+
return layout(xyz, regions, LiveModel.build(neurons, check_sizes=False), directory)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def layout(xyz: np.ndarray, regions: np.ndarray, model: LiveModel,
|
| 97 |
+
directory: Path | None = None) -> BrainLayout:
|
| 98 |
+
blob, lo, hi = pack(xyz, regions)
|
| 99 |
+
readouts: dict[str, dict[str, list[int]]] = {r: {} for r in READOUTS}
|
| 100 |
+
for slot, (r, side) in enumerate(model.slots):
|
| 101 |
+
readouts[r][side] = np.flatnonzero(model.slot_of == slot).astype(int).tolist()
|
| 102 |
+
sums = directory / "SHA256SUMS" if directory is not None else None
|
| 103 |
+
ident = sums.read_bytes() if sums is not None and sums.exists() else blob
|
| 104 |
+
meta: dict[str, object] = {
|
| 105 |
+
"format": FORMAT,
|
| 106 |
+
"n": model.n,
|
| 107 |
+
"missing": int((np.frombuffer(blob[: model.n * 6], "<u2") == MISSING).sum() // 3),
|
| 108 |
+
"voxel_nm": VOXEL_NM,
|
| 109 |
+
"bounds": {"min": lo, "max": hi},
|
| 110 |
+
"encoding": {"positions": "uint16le n*3, scaled to [0, 65534] over bounds; "
|
| 111 |
+
"65535 = no position", "regions": "uint8 n"},
|
| 112 |
+
"regions": list(REGIONS),
|
| 113 |
+
"stimuli": {name: {"targets": model.targets[name].astype(int).tolist(),
|
| 114 |
+
"readout": s.readout, "chain_status": s.status}
|
| 115 |
+
for name, s in STIMULI.items()},
|
| 116 |
+
"readouts": readouts,
|
| 117 |
+
"etag": hashlib.sha256(b"brain-%d\n" % FORMAT + ident).hexdigest()[:32],
|
| 118 |
+
}
|
| 119 |
+
return BrainLayout(meta, blob)
|
flysim/src/flysim/live/cache.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Recordings of live blocks and the on-disk replay cache.
|
| 2 |
+
|
| 3 |
+
Every live block is stored: its spikes (compressed) and the per-chunk readout counts,
|
| 4 |
+
so a replay sends exactly the messages the live run sent. Recordings are keyed by
|
| 5 |
+
(stimulus, rounded rate, seed) under a directory named after the model fingerprint
|
| 6 |
+
(:func:`flysim.live.model.model_fingerprint`), so a change of data, model, block layout
|
| 7 |
+
or seeding never replays a stale recording.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import contextlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import re
|
| 16 |
+
import tempfile
|
| 17 |
+
from collections.abc import Iterable, Iterator
|
| 18 |
+
from dataclasses import dataclass, field
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from flysim.live.model import (
|
| 25 |
+
CHUNK_STEPS,
|
| 26 |
+
N_CHUNKS,
|
| 27 |
+
PARAMS,
|
| 28 |
+
READOUTS,
|
| 29 |
+
STIM_STEPS,
|
| 30 |
+
BlockSpec,
|
| 31 |
+
Chunk,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class Recording:
|
| 37 |
+
spec: BlockSpec
|
| 38 |
+
experiment: str
|
| 39 |
+
n_neurons: int
|
| 40 |
+
slots: tuple[tuple[str, str], ...]
|
| 41 |
+
steps: np.ndarray # int64, absolute steps, time order
|
| 42 |
+
neurons: np.ndarray # int32
|
| 43 |
+
chunk_counts: np.ndarray # int32, (N_CHUNKS, len(slots))
|
| 44 |
+
compute_s: float
|
| 45 |
+
meta: dict[str, Any] = field(default_factory=dict)
|
| 46 |
+
|
| 47 |
+
@classmethod
|
| 48 |
+
def from_chunks(cls, spec: BlockSpec, experiment: str, n_neurons: int,
|
| 49 |
+
slots: tuple[tuple[str, str], ...], chunks: Iterable[Chunk],
|
| 50 |
+
compute_s: float, meta: dict[str, Any] | None = None) -> Recording:
|
| 51 |
+
cs = list(chunks)
|
| 52 |
+
if [c.index for c in cs] != list(range(N_CHUNKS)):
|
| 53 |
+
raise ValueError("a recording needs every chunk of the block, in order")
|
| 54 |
+
empty_i64, empty_i32 = np.empty(0, np.int64), np.empty(0, np.int32)
|
| 55 |
+
return cls(
|
| 56 |
+
spec, experiment, n_neurons, slots,
|
| 57 |
+
np.concatenate([empty_i64, *(c.steps for c in cs)]).astype(np.int64),
|
| 58 |
+
np.concatenate([empty_i32, *(c.neurons for c in cs)]).astype(np.int32),
|
| 59 |
+
np.stack([c.counts for c in cs]).astype(np.int32),
|
| 60 |
+
compute_s, dict(meta or {}),
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
def chunks(self) -> Iterator[Chunk]:
|
| 64 |
+
bounds = np.searchsorted(self.steps, np.arange(N_CHUNKS + 1) * CHUNK_STEPS)
|
| 65 |
+
for k in range(N_CHUNKS):
|
| 66 |
+
lo, hi = bounds[k], bounds[k + 1]
|
| 67 |
+
yield Chunk(k, k * CHUNK_STEPS, (k + 1) * CHUNK_STEPS, self.steps[lo:hi],
|
| 68 |
+
self.neurons[lo:hi], self.chunk_counts[k])
|
| 69 |
+
|
| 70 |
+
def summary(self) -> dict[str, Any]:
|
| 71 |
+
"""Readout counts per side over the stimulus window and the whole block."""
|
| 72 |
+
stim_chunks = STIM_STEPS // CHUNK_STEPS
|
| 73 |
+
stim = self.chunk_counts[:stim_chunks].sum(axis=0)
|
| 74 |
+
block = self.chunk_counts.sum(axis=0)
|
| 75 |
+
out: dict[str, Any] = {"spikes": int(len(self.neurons)),
|
| 76 |
+
"spikes_stimulus": int(np.sum(self.steps < STIM_STEPS))}
|
| 77 |
+
out["readouts_stimulus"] = _per_readout(self.slots, stim)
|
| 78 |
+
out["readouts_block"] = _per_readout(self.slots, block)
|
| 79 |
+
return out
|
| 80 |
+
|
| 81 |
+
# -- disk ----------------------------------------------------------------
|
| 82 |
+
def save(self, path: Path) -> None:
|
| 83 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 84 |
+
meta = {
|
| 85 |
+
"stimulus": self.spec.stimulus, "rate_hz": self.spec.rate_hz,
|
| 86 |
+
"seed": self.spec.seed, "experiment": self.experiment,
|
| 87 |
+
"n_neurons": self.n_neurons, "slots": [list(s) for s in self.slots],
|
| 88 |
+
"compute_s": self.compute_s, "dt_ms": PARAMS.dt, **self.meta,
|
| 89 |
+
}
|
| 90 |
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".rec-", suffix=".npz")
|
| 91 |
+
try:
|
| 92 |
+
os.chmod(tmp, 0o644)
|
| 93 |
+
with os.fdopen(fd, "wb") as f:
|
| 94 |
+
np.savez_compressed(
|
| 95 |
+
f, steps=self.steps.astype(np.int16), neurons=self.neurons,
|
| 96 |
+
chunk_counts=self.chunk_counts, meta=np.array(json.dumps(meta)))
|
| 97 |
+
os.replace(tmp, path)
|
| 98 |
+
except BaseException:
|
| 99 |
+
Path(tmp).unlink(missing_ok=True)
|
| 100 |
+
raise
|
| 101 |
+
|
| 102 |
+
@classmethod
|
| 103 |
+
def load(cls, path: Path) -> Recording:
|
| 104 |
+
with np.load(path, allow_pickle=False) as z:
|
| 105 |
+
meta = json.loads(str(z["meta"]))
|
| 106 |
+
steps = z["steps"].astype(np.int64)
|
| 107 |
+
neurons = z["neurons"].astype(np.int32)
|
| 108 |
+
counts = z["chunk_counts"].astype(np.int32)
|
| 109 |
+
spec = BlockSpec(meta.pop("stimulus"), float(meta.pop("rate_hz")), int(meta.pop("seed")))
|
| 110 |
+
slots = tuple((str(a), str(b)) for a, b in meta.pop("slots"))
|
| 111 |
+
return cls(spec, meta.pop("experiment"), int(meta.pop("n_neurons")), slots, steps,
|
| 112 |
+
neurons, counts, float(meta.pop("compute_s")), meta)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _per_readout(slots: tuple[tuple[str, str], ...], counts: np.ndarray
|
| 116 |
+
) -> dict[str, dict[str, int]]:
|
| 117 |
+
out: dict[str, dict[str, int]] = {r: {} for r in READOUTS}
|
| 118 |
+
for (r, side), c in zip(slots, counts, strict=True):
|
| 119 |
+
out.setdefault(r, {})[side] = int(c)
|
| 120 |
+
return out
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
_NAME = re.compile(r"^(?P<stim>[A-Za-z0-9+]+)_(?P<rate>[0-9.]+)Hz_s(?P<seed>[0-9]+)\.npz$")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class ReplayCache:
|
| 127 |
+
"""Recordings on disk under ``root/<fingerprint[:16]>/``, one ``.npz`` each.
|
| 128 |
+
|
| 129 |
+
``max_bytes`` bounds the cache: after each write, recordings of other fingerprints
|
| 130 |
+
(which can never be replayed again) are deleted first, then the least recently used
|
| 131 |
+
ones of this fingerprint until the total fits. A replay counts as a use (its file's
|
| 132 |
+
modification time is refreshed). Several worker processes may evict at once; a file
|
| 133 |
+
another one already removed is skipped.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
def __init__(self, root: Path, fingerprint: str, max_bytes: int | None = None) -> None:
|
| 137 |
+
self.root = Path(root)
|
| 138 |
+
self.fingerprint = fingerprint
|
| 139 |
+
self.dir = self.root / fingerprint[:16]
|
| 140 |
+
self.max_bytes = max_bytes
|
| 141 |
+
|
| 142 |
+
def path(self, spec: BlockSpec) -> Path:
|
| 143 |
+
return self.dir / f"{spec.stimulus}_{spec.rate_hz:g}Hz_s{spec.seed}.npz"
|
| 144 |
+
|
| 145 |
+
def get(self, spec: BlockSpec) -> Recording | None:
|
| 146 |
+
p = self.path(spec)
|
| 147 |
+
if not p.exists():
|
| 148 |
+
return None
|
| 149 |
+
try:
|
| 150 |
+
rec = Recording.load(p)
|
| 151 |
+
except (OSError, ValueError, KeyError):
|
| 152 |
+
return None # a damaged file is treated as a miss and overwritten later
|
| 153 |
+
with contextlib.suppress(OSError):
|
| 154 |
+
os.utime(p) # a use, for least-recently-used eviction
|
| 155 |
+
return rec
|
| 156 |
+
|
| 157 |
+
def seeds(self, stimulus: str, rate_hz: float) -> list[int]:
|
| 158 |
+
if not self.dir.exists():
|
| 159 |
+
return []
|
| 160 |
+
out = []
|
| 161 |
+
for p in self.dir.iterdir():
|
| 162 |
+
m = _NAME.match(p.name)
|
| 163 |
+
if m and m["stim"] == stimulus and float(m["rate"]) == rate_hz:
|
| 164 |
+
out.append(int(m["seed"]))
|
| 165 |
+
return sorted(out)
|
| 166 |
+
|
| 167 |
+
def find(self, spec: BlockSpec) -> Recording | None:
|
| 168 |
+
"""The recording for ``spec``, or else the one with the lowest seed for the same
|
| 169 |
+
stimulus and rate (the busy fallback)."""
|
| 170 |
+
exact = self.get(spec)
|
| 171 |
+
if exact is not None:
|
| 172 |
+
return exact
|
| 173 |
+
for seed in self.seeds(spec.stimulus, spec.rate_hz):
|
| 174 |
+
rec = self.get(BlockSpec(spec.stimulus, spec.rate_hz, seed))
|
| 175 |
+
if rec is not None:
|
| 176 |
+
return rec
|
| 177 |
+
return None
|
| 178 |
+
|
| 179 |
+
def put(self, rec: Recording) -> Path:
|
| 180 |
+
p = self.path(rec.spec)
|
| 181 |
+
rec.save(p)
|
| 182 |
+
self.evict()
|
| 183 |
+
return p
|
| 184 |
+
|
| 185 |
+
def evict(self) -> int:
|
| 186 |
+
"""Delete recordings until the cache fits ``max_bytes``. Returns how many went."""
|
| 187 |
+
if self.max_bytes is None or not self.root.exists():
|
| 188 |
+
return 0
|
| 189 |
+
stale: list[Path] = []
|
| 190 |
+
current: list[tuple[float, int, Path]] = []
|
| 191 |
+
for p in self.root.glob("*/*.npz"):
|
| 192 |
+
try:
|
| 193 |
+
st = p.stat()
|
| 194 |
+
except OSError:
|
| 195 |
+
continue
|
| 196 |
+
if p.parent == self.dir:
|
| 197 |
+
current.append((st.st_mtime, st.st_size, p))
|
| 198 |
+
else:
|
| 199 |
+
stale.append(p)
|
| 200 |
+
removed = 0
|
| 201 |
+
for p in stale:
|
| 202 |
+
p.unlink(missing_ok=True)
|
| 203 |
+
removed += 1
|
| 204 |
+
total = sum(size for _, size, _ in current)
|
| 205 |
+
for _, size, p in sorted(current):
|
| 206 |
+
if total <= self.max_bytes:
|
| 207 |
+
break
|
| 208 |
+
p.unlink(missing_ok=True)
|
| 209 |
+
total -= size
|
| 210 |
+
removed += 1
|
| 211 |
+
return removed
|
flysim/src/flysim/live/model.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""What a live block is, and the runner that steps it in chunks.
|
| 2 |
+
|
| 3 |
+
A block is one chain-test trial (``flysim.validation.chains``): 600 ms from rest,
|
| 4 |
+
Poisson input into the right-side neurons of the stimulus' source types over
|
| 5 |
+
[0, 300) ms, nothing after. The live runner steps it in 10 ms chunks and yields each
|
| 6 |
+
chunk's spikes and readout counts. Blocks always start from rest (see the VNC-loop
|
| 7 |
+
decision in ``records/validation-log.md``); there is no "continuous" mode that carries
|
| 8 |
+
state between blocks.
|
| 9 |
+
|
| 10 |
+
Seeds follow section 1 of the preregistration: ``trial_rng(experiment,
|
| 11 |
+
"<stimulus>/<rate>Hz", seed)``. The live default experiment is ``"live"``. With
|
| 12 |
+
``experiment="chain-tests"`` a block is exactly the recorded chain-test trial of that
|
| 13 |
+
number (the tests use this).
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import hashlib
|
| 19 |
+
import json
|
| 20 |
+
import math
|
| 21 |
+
from collections.abc import Iterator
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Literal, Protocol
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
from flysim import artifact
|
| 29 |
+
from flysim.engine import CpuEngine, ModelParams, SynapseMatrix, poisson_schedule, trial_rng
|
| 30 |
+
from flysim.validation import chains
|
| 31 |
+
|
| 32 |
+
#: The live matrix: every culled variant failed the culling-equivalence test.
|
| 33 |
+
VARIANT = "full"
|
| 34 |
+
PARAMS: ModelParams = chains.PARAMS # w_syn = W_SYN_MALE (preregistration, section 3)
|
| 35 |
+
BLOCK_STEPS: int = chains.TRIAL_STEPS # 600 ms
|
| 36 |
+
STIM_STEPS: int = chains.STIM_STEPS # stimulus over [0, 300) ms
|
| 37 |
+
CHUNK_STEPS = 100 # 10 ms
|
| 38 |
+
N_CHUNKS = BLOCK_STEPS // CHUNK_STEPS
|
| 39 |
+
BLOCK_S = BLOCK_STEPS * PARAMS.dt * 1e-3
|
| 40 |
+
READOUTS: tuple[str, ...] = chains.READOUTS
|
| 41 |
+
MAX_RATE_HZ = 200.0 # the top of the chain-test rate range
|
| 42 |
+
MAX_SEED = 2**31 - 1
|
| 43 |
+
EXPERIMENT = "live"
|
| 44 |
+
#: Bump when the block, the seeding or the recording layout changes (invalidates caches).
|
| 45 |
+
FORMAT = 1
|
| 46 |
+
|
| 47 |
+
Status = Literal["validated", "not_validated"]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass(frozen=True)
|
| 51 |
+
class LiveStimulus:
|
| 52 |
+
name: str
|
| 53 |
+
source_types: tuple[str, ...]
|
| 54 |
+
chain: str
|
| 55 |
+
readout: str
|
| 56 |
+
#: ``validated``: the chain passed its chain test, so its readout may be presented as
|
| 57 |
+
#: the model's response. ``not_validated``: it failed; the simulation still runs and
|
| 58 |
+
#: streams, but a client must not present the readout as a validated response.
|
| 59 |
+
status: Status
|
| 60 |
+
basis: str
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _stim(name: str, status: Status, basis: str) -> LiveStimulus:
|
| 64 |
+
(chain,) = [c for c in chains.CHAINS if c.source == name]
|
| 65 |
+
return LiveStimulus(name, chains.STIMULI[name], chain.name, chain.readout, status, basis)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
#: The live stimuli and their chain-test verdicts (``records/results-summary.md``).
|
| 69 |
+
STIMULI: dict[str, LiveStimulus] = {
|
| 70 |
+
s.name: s
|
| 71 |
+
for s in (
|
| 72 |
+
_stim("LC4", "not_validated",
|
| 73 |
+
"chain test LC4 -> DNp01 FAIL (C4), records/results/chain-tests.md"),
|
| 74 |
+
_stim("LC16", "not_validated",
|
| 75 |
+
"chain test LC16 -> MDN FAIL (C1, C5; section 4.3 steps fail C4), "
|
| 76 |
+
"records/results/chain-tests.md"),
|
| 77 |
+
_stim("LC9", "validated", "chain test LC9 -> DNp09 PASS, records/results/chain-tests.md"),
|
| 78 |
+
)
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class InvalidRequest(ValueError):
|
| 83 |
+
pass
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass(frozen=True)
|
| 87 |
+
class BlockSpec:
|
| 88 |
+
stimulus: str
|
| 89 |
+
rate_hz: float
|
| 90 |
+
seed: int
|
| 91 |
+
|
| 92 |
+
def validate(self) -> None:
|
| 93 |
+
if self.stimulus not in STIMULI:
|
| 94 |
+
raise InvalidRequest(f"unknown stimulus {self.stimulus!r}; one of {sorted(STIMULI)}")
|
| 95 |
+
if not (math.isfinite(self.rate_hz) and 0.0 <= self.rate_hz <= MAX_RATE_HZ):
|
| 96 |
+
raise InvalidRequest(f"rate_hz must be in [0, {MAX_RATE_HZ:g}]")
|
| 97 |
+
if not (0 <= self.seed <= MAX_SEED):
|
| 98 |
+
raise InvalidRequest(f"seed must be in [0, {MAX_SEED}]")
|
| 99 |
+
|
| 100 |
+
def condition(self) -> str:
|
| 101 |
+
"""The seed condition key, as in the chain tests: ``<stimulus>/<rate>Hz``."""
|
| 102 |
+
return f"{self.stimulus}/{self.rate_hz:g}Hz"
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def round_rate(rate_hz: float, step_hz: float) -> float:
|
| 106 |
+
"""The rate a request runs at: rounded to ``step_hz`` (live and replay use the same)."""
|
| 107 |
+
if step_hz <= 0:
|
| 108 |
+
return float(rate_hz)
|
| 109 |
+
r = round(rate_hz / step_hz) * step_hz
|
| 110 |
+
return float(min(MAX_RATE_HZ, max(0.0, round(r, 6))))
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ----------------------------------------------------------------------------- model
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class ModelSource(Protocol):
|
| 117 |
+
"""Where a worker gets its matrix and neuron table. Must be picklable (it is sent to
|
| 118 |
+
spawned worker processes) and cheap to fingerprint without loading the matrix."""
|
| 119 |
+
|
| 120 |
+
def load(self) -> tuple[SynapseMatrix, chains.Neurons]: ...
|
| 121 |
+
|
| 122 |
+
def fingerprint(self) -> str: ...
|
| 123 |
+
|
| 124 |
+
def check_sizes(self) -> bool: ...
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@dataclass(frozen=True)
|
| 128 |
+
class ConnectomeSource:
|
| 129 |
+
"""A fetched ``connectome-v1`` directory (``python -m flysim.artifact fetch``).
|
| 130 |
+
|
| 131 |
+
With ``unpack_dir`` set, the first load unpacks the matrix to ``.npy`` files there,
|
| 132 |
+
and every worker then maps them read-only (one copy in memory, shared by the page
|
| 133 |
+
cache) instead of decompressing its own.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
directory: Path
|
| 137 |
+
unpack_dir: Path | None = None
|
| 138 |
+
|
| 139 |
+
def fingerprint(self) -> str:
|
| 140 |
+
sums = self.directory / "SHA256SUMS"
|
| 141 |
+
if sums.exists():
|
| 142 |
+
lines = sums.read_text().splitlines()
|
| 143 |
+
wanted = (f"matrix-{VARIANT}.tar.zst", "neurons.parquet")
|
| 144 |
+
ident = "\n".join(sorted(x for x in lines if x.endswith(wanted)))
|
| 145 |
+
else:
|
| 146 |
+
ident = "\n".join(
|
| 147 |
+
f"{p.name} {p.stat().st_size} {p.stat().st_mtime_ns}" if p.exists()
|
| 148 |
+
else f"{p.name} absent"
|
| 149 |
+
for p in (self.directory / f"matrix-{VARIANT}.tar.zst",
|
| 150 |
+
self.directory / "neurons.parquet")
|
| 151 |
+
)
|
| 152 |
+
return hashlib.sha256(f"{VARIANT}\n{ident}".encode()).hexdigest()
|
| 153 |
+
|
| 154 |
+
def check_sizes(self) -> bool:
|
| 155 |
+
return True
|
| 156 |
+
|
| 157 |
+
def load(self) -> tuple[SynapseMatrix, chains.Neurons]:
|
| 158 |
+
neurons = chains.Neurons.load(self.directory)
|
| 159 |
+
if self.unpack_dir is None:
|
| 160 |
+
c = artifact.load(self.directory, VARIANT)
|
| 161 |
+
return SynapseMatrix(c.indptr, c.indices, c.weights), neurons
|
| 162 |
+
return self._mapped(), neurons
|
| 163 |
+
|
| 164 |
+
def _mapped(self) -> SynapseMatrix:
|
| 165 |
+
assert self.unpack_dir is not None
|
| 166 |
+
d = self.unpack_dir / f"{VARIANT}-{self.fingerprint()[:16]}"
|
| 167 |
+
names = ("indptr", "indices", "weights")
|
| 168 |
+
if not (d / "complete").exists():
|
| 169 |
+
c = artifact.load(self.directory, VARIANT)
|
| 170 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 171 |
+
for name in names:
|
| 172 |
+
tmp = d / f"{name}.npy.tmp"
|
| 173 |
+
with tmp.open("wb") as f:
|
| 174 |
+
np.save(f, getattr(c, name))
|
| 175 |
+
tmp.replace(d / f"{name}.npy")
|
| 176 |
+
(d / "complete").write_text("")
|
| 177 |
+
arrays = [np.asarray(np.load(d / f"{n}.npy", mmap_mode="r")) for n in names]
|
| 178 |
+
return SynapseMatrix(*arrays)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@dataclass(frozen=True)
|
| 182 |
+
class InMemorySource:
|
| 183 |
+
"""A matrix and neuron table held in memory (tests, synthetic networks)."""
|
| 184 |
+
|
| 185 |
+
matrix: SynapseMatrix
|
| 186 |
+
neurons: chains.Neurons
|
| 187 |
+
|
| 188 |
+
def fingerprint(self) -> str:
|
| 189 |
+
h = hashlib.sha256(b"in-memory\n")
|
| 190 |
+
for a in (self.matrix.indptr, self.matrix.indices, self.matrix.weights,
|
| 191 |
+
self.neurons.body, self.neurons.sign):
|
| 192 |
+
h.update(np.ascontiguousarray(a).tobytes())
|
| 193 |
+
for a in (self.neurons.type, self.neurons.side):
|
| 194 |
+
h.update(json.dumps([None if x is None else str(x) for x in a]).encode())
|
| 195 |
+
return h.hexdigest()
|
| 196 |
+
|
| 197 |
+
def check_sizes(self) -> bool:
|
| 198 |
+
return False
|
| 199 |
+
|
| 200 |
+
def load(self) -> tuple[SynapseMatrix, chains.Neurons]:
|
| 201 |
+
return self.matrix, self.neurons
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def model_fingerprint(source: ModelSource, experiment: str) -> str:
|
| 205 |
+
"""Everything a recording depends on: data, model, block layout, seeding."""
|
| 206 |
+
blob = json.dumps({
|
| 207 |
+
"format": FORMAT, "source": source.fingerprint(), "params": PARAMS.to_dict(),
|
| 208 |
+
"dtype": "float32", "block_steps": BLOCK_STEPS, "stim_steps": STIM_STEPS,
|
| 209 |
+
"chunk_steps": CHUNK_STEPS, "experiment": experiment,
|
| 210 |
+
}, sort_keys=True)
|
| 211 |
+
return hashlib.sha256(blob.encode()).hexdigest()
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@dataclass(frozen=True)
|
| 215 |
+
class LiveModel:
|
| 216 |
+
"""What the runner needs from the neuron table: stimulus targets and readout slots.
|
| 217 |
+
|
| 218 |
+
A *slot* is one (readout, side) pair, e.g. ``("DNp09", "R")``; readout counts are
|
| 219 |
+
reported per slot. ``slot_of[i]`` is neuron ``i``'s slot, or -1.
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
n: int
|
| 223 |
+
targets: dict[str, np.ndarray]
|
| 224 |
+
slots: tuple[tuple[str, str], ...]
|
| 225 |
+
slot_of: np.ndarray # int16, n
|
| 226 |
+
|
| 227 |
+
@classmethod
|
| 228 |
+
def build(cls, neurons: chains.Neurons, check_sizes: bool = True) -> LiveModel:
|
| 229 |
+
n = len(neurons.body)
|
| 230 |
+
targets = {}
|
| 231 |
+
for name, s in STIMULI.items():
|
| 232 |
+
t = neurons.of_types(s.source_types, side="R")
|
| 233 |
+
if check_sizes and len(t) != chains.SIZES[name]:
|
| 234 |
+
raise ValueError(f"{name}: {len(t)} right-side neurons, the preregistration says "
|
| 235 |
+
f"{chains.SIZES[name]}")
|
| 236 |
+
if len(t) == 0:
|
| 237 |
+
raise ValueError(f"{name}: no right-side neurons")
|
| 238 |
+
targets[name] = t
|
| 239 |
+
slots: list[tuple[str, str]] = []
|
| 240 |
+
slot_of = np.full(n, -1, dtype=np.int16)
|
| 241 |
+
for r in READOUTS:
|
| 242 |
+
idx = neurons.of_types((r,))
|
| 243 |
+
if len(idx) == 0:
|
| 244 |
+
raise ValueError(f"readout {r} has no neurons")
|
| 245 |
+
sides = np.array([_side(x) for x in neurons.side[idx]], dtype=object)
|
| 246 |
+
for side in sorted(set(sides)):
|
| 247 |
+
slot_of[idx[sides == side]] = len(slots)
|
| 248 |
+
slots.append((r, side))
|
| 249 |
+
return cls(n, targets, tuple(slots), slot_of)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _side(x: object) -> str:
|
| 253 |
+
return str(x) if x in ("L", "R", "M") else "?"
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
# ----------------------------------------------------------------------------- runner
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@dataclass(frozen=True)
|
| 260 |
+
class Chunk:
|
| 261 |
+
index: int
|
| 262 |
+
step0: int
|
| 263 |
+
step1: int
|
| 264 |
+
steps: np.ndarray # int64, absolute step of each spike, in time order
|
| 265 |
+
neurons: np.ndarray # int32
|
| 266 |
+
counts: np.ndarray # int32, readout spikes per slot
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def make_engine(matrix: SynapseMatrix) -> CpuEngine:
|
| 270 |
+
eng = CpuEngine(np.float32) # default kernel: vec (records/validation-log.md)
|
| 271 |
+
eng.load(matrix, PARAMS)
|
| 272 |
+
return eng
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def run_block(engine: CpuEngine, model: LiveModel, spec: BlockSpec,
|
| 276 |
+
experiment: str = EXPERIMENT) -> Iterator[Chunk]:
|
| 277 |
+
"""Reset to rest, schedule the block's input, then step it chunk by chunk."""
|
| 278 |
+
spec.validate()
|
| 279 |
+
targets = model.targets[spec.stimulus]
|
| 280 |
+
rng = trial_rng(experiment, spec.condition(), spec.seed)
|
| 281 |
+
engine.reset()
|
| 282 |
+
engine.schedule_inputs(
|
| 283 |
+
poisson_schedule(rng, targets, spec.rate_hz, 0, STIM_STEPS, PARAMS.dt))
|
| 284 |
+
n_slots = len(model.slots)
|
| 285 |
+
for k in range(N_CHUNKS):
|
| 286 |
+
s0, s1 = k * CHUNK_STEPS, (k + 1) * CHUNK_STEPS
|
| 287 |
+
engine.advance_to(s1)
|
| 288 |
+
steps, neurons = engine.spikes_since(s0)
|
| 289 |
+
slot = model.slot_of[neurons]
|
| 290 |
+
counts = np.bincount(slot[slot >= 0], minlength=n_slots).astype(np.int32)
|
| 291 |
+
yield Chunk(k, s0, s1, steps, neurons, counts)
|
flysim/src/flysim/live/pool.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The simulation worker pool: one block at a time per process, a queue in front.
|
| 2 |
+
|
| 3 |
+
Each worker process loads the matrix once, builds one engine and then takes blocks from
|
| 4 |
+
a shared queue. It sends every chunk back as soon as it is computed, then stores the
|
| 5 |
+
recording in the replay cache. The parent keeps track of what is queued and running, so
|
| 6 |
+
it can estimate how long a new block would wait (:func:`expected_wait`).
|
| 7 |
+
|
| 8 |
+
Workers are started with ``spawn``: the parent is usually an async web server with
|
| 9 |
+
threads, where ``fork`` is unsafe.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import contextlib
|
| 15 |
+
import heapq
|
| 16 |
+
import logging
|
| 17 |
+
import math
|
| 18 |
+
import multiprocessing as mp
|
| 19 |
+
import queue
|
| 20 |
+
import threading
|
| 21 |
+
import time
|
| 22 |
+
from collections.abc import Callable
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
from multiprocessing.process import BaseProcess
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any
|
| 27 |
+
|
| 28 |
+
from flysim.live.cache import Recording, ReplayCache
|
| 29 |
+
from flysim.live.model import (
|
| 30 |
+
BLOCK_S,
|
| 31 |
+
CHUNK_STEPS,
|
| 32 |
+
EXPERIMENT,
|
| 33 |
+
BlockSpec,
|
| 34 |
+
LiveModel,
|
| 35 |
+
ModelSource,
|
| 36 |
+
make_engine,
|
| 37 |
+
model_fingerprint,
|
| 38 |
+
run_block,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
log = logging.getLogger(__name__)
|
| 42 |
+
|
| 43 |
+
#: (kind, payload). Kinds: ``started`` (n_neurons, slots), ``chunk`` (Chunk), ``done``
|
| 44 |
+
#: (compute_s, summary), ``failed`` (message).
|
| 45 |
+
Event = tuple[str, Any]
|
| 46 |
+
Callback = Callable[[str, Any], None]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclass(frozen=True)
|
| 50 |
+
class WorkerConfig:
|
| 51 |
+
source: ModelSource
|
| 52 |
+
experiment: str
|
| 53 |
+
cache_root: Path | None
|
| 54 |
+
fingerprint: str
|
| 55 |
+
cache_max_bytes: int | None = None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _worker_main(idx: int, cfg: WorkerConfig, tasks: Any, out: Any) -> None:
|
| 59 |
+
try:
|
| 60 |
+
matrix, neurons = cfg.source.load()
|
| 61 |
+
model = LiveModel.build(neurons, cfg.source.check_sizes())
|
| 62 |
+
engine = make_engine(matrix)
|
| 63 |
+
engine.advance_to(CHUNK_STEPS) # load (or compile) the kernel before the first block
|
| 64 |
+
except BaseException as e: # noqa: BLE001 - reported to the parent, then exit
|
| 65 |
+
out.put((None, "load_failed", (idx, f"{type(e).__name__}: {e}")))
|
| 66 |
+
return
|
| 67 |
+
cache = (ReplayCache(cfg.cache_root, cfg.fingerprint, cfg.cache_max_bytes)
|
| 68 |
+
if cfg.cache_root else None)
|
| 69 |
+
out.put((None, "ready", idx))
|
| 70 |
+
while True:
|
| 71 |
+
task = tasks.get()
|
| 72 |
+
if task is None:
|
| 73 |
+
return
|
| 74 |
+
job_id, spec = task
|
| 75 |
+
out.put((job_id, "started", (idx, model.n, model.slots)))
|
| 76 |
+
try:
|
| 77 |
+
t0 = time.perf_counter()
|
| 78 |
+
chunks = []
|
| 79 |
+
for c in run_block(engine, model, spec, cfg.experiment):
|
| 80 |
+
out.put((job_id, "chunk", c))
|
| 81 |
+
chunks.append(c)
|
| 82 |
+
compute_s = time.perf_counter() - t0
|
| 83 |
+
rec = Recording.from_chunks(spec, cfg.experiment, model.n, model.slots, chunks,
|
| 84 |
+
compute_s)
|
| 85 |
+
if cache is not None:
|
| 86 |
+
try:
|
| 87 |
+
cache.put(rec)
|
| 88 |
+
except OSError as e:
|
| 89 |
+
log.warning("could not store recording: %s", e)
|
| 90 |
+
out.put((job_id, "done", (compute_s, rec.summary())))
|
| 91 |
+
except Exception as e: # noqa: BLE001
|
| 92 |
+
out.put((job_id, "failed", f"{type(e).__name__}: {e}"))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def expected_wait(now: float, ready: int, running_since: list[float], pending: int,
|
| 96 |
+
block_s: float) -> float:
|
| 97 |
+
"""Seconds until a block submitted now would start.
|
| 98 |
+
|
| 99 |
+
``ready`` workers; ``running_since`` holds the start time of each running block (each
|
| 100 |
+
on its own ready worker); ``pending`` blocks are queued ahead, FIFO; every block is
|
| 101 |
+
assumed to take ``block_s``. No ready worker gives ``inf``.
|
| 102 |
+
"""
|
| 103 |
+
if ready <= 0:
|
| 104 |
+
return math.inf
|
| 105 |
+
free = [max(now, t0 + block_s) for t0 in running_since[:ready]]
|
| 106 |
+
free += [now] * (ready - len(free))
|
| 107 |
+
heapq.heapify(free)
|
| 108 |
+
for _ in range(pending):
|
| 109 |
+
heapq.heappush(free, heapq.heappop(free) + block_s)
|
| 110 |
+
return max(0.0, free[0] - now)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class PoolUnavailable(RuntimeError):
|
| 114 |
+
pass
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class WorkerPool:
|
| 118 |
+
"""``workers`` processes, each with one engine. Thread-safe; callbacks run on the
|
| 119 |
+
pool's reader thread and must not block."""
|
| 120 |
+
|
| 121 |
+
def __init__(self, source: ModelSource, workers: int, *, experiment: str = EXPERIMENT,
|
| 122 |
+
cache_root: Path | None = None, cache_max_bytes: int | None = None,
|
| 123 |
+
compute_ratio_prior: float = 1.12, ewma: float = 0.3,
|
| 124 |
+
context: str = "spawn") -> None:
|
| 125 |
+
if workers < 1:
|
| 126 |
+
raise ValueError("workers must be >= 1")
|
| 127 |
+
self.workers = workers
|
| 128 |
+
self.experiment = experiment
|
| 129 |
+
self.fingerprint = model_fingerprint(source, experiment)
|
| 130 |
+
self._cfg = WorkerConfig(source, experiment, cache_root, self.fingerprint,
|
| 131 |
+
cache_max_bytes)
|
| 132 |
+
self._ctx: Any = mp.get_context(context)
|
| 133 |
+
self._tasks: Any = self._ctx.Queue()
|
| 134 |
+
self._out: Any = self._ctx.Queue()
|
| 135 |
+
self._lock = threading.Lock()
|
| 136 |
+
self._procs: dict[int, BaseProcess] = {}
|
| 137 |
+
self._ready: set[int] = set()
|
| 138 |
+
self._running: dict[int, tuple[int, float]] = {} # worker -> (job, start)
|
| 139 |
+
self._pending: dict[int, BlockSpec] = {} # queued, in submit order
|
| 140 |
+
self._callbacks: dict[int, Callback] = {}
|
| 141 |
+
self._next_job = 0
|
| 142 |
+
self._next_worker = 0
|
| 143 |
+
self._block_s = compute_ratio_prior * BLOCK_S
|
| 144 |
+
self._ewma = ewma
|
| 145 |
+
self._closing = False
|
| 146 |
+
self.error: str | None = None
|
| 147 |
+
self._reader: threading.Thread | None = None
|
| 148 |
+
|
| 149 |
+
# -- lifecycle -------------------------------------------------------------
|
| 150 |
+
def start(self) -> None:
|
| 151 |
+
with self._lock:
|
| 152 |
+
if self._reader is not None:
|
| 153 |
+
return
|
| 154 |
+
for _ in range(self.workers):
|
| 155 |
+
self._spawn()
|
| 156 |
+
self._reader = threading.Thread(target=self._read, name="flysim-pool", daemon=True)
|
| 157 |
+
self._reader.start()
|
| 158 |
+
|
| 159 |
+
def _spawn(self) -> None:
|
| 160 |
+
idx = self._next_worker
|
| 161 |
+
self._next_worker += 1
|
| 162 |
+
p = self._ctx.Process(target=_worker_main, args=(idx, self._cfg, self._tasks, self._out),
|
| 163 |
+
name=f"flysim-worker-{idx}", daemon=True)
|
| 164 |
+
p.start()
|
| 165 |
+
self._procs[idx] = p
|
| 166 |
+
|
| 167 |
+
def close(self, timeout: float = 5.0) -> None:
|
| 168 |
+
"""Drop queued blocks, let running ones finish within ``timeout``, stop workers."""
|
| 169 |
+
with self._lock:
|
| 170 |
+
if self._closing:
|
| 171 |
+
return
|
| 172 |
+
self._closing = True
|
| 173 |
+
procs = list(self._procs.values())
|
| 174 |
+
with contextlib.suppress(queue.Empty, OSError):
|
| 175 |
+
while True:
|
| 176 |
+
self._tasks.get_nowait()
|
| 177 |
+
for _ in procs:
|
| 178 |
+
self._tasks.put(None)
|
| 179 |
+
deadline = time.monotonic() + timeout
|
| 180 |
+
for p in procs:
|
| 181 |
+
p.join(max(0.0, deadline - time.monotonic()))
|
| 182 |
+
if p.is_alive():
|
| 183 |
+
p.terminate()
|
| 184 |
+
p.join(1.0)
|
| 185 |
+
if self._reader is not None:
|
| 186 |
+
self._reader.join(2.0)
|
| 187 |
+
with self._lock:
|
| 188 |
+
callbacks = list(self._callbacks.values())
|
| 189 |
+
self._callbacks.clear()
|
| 190 |
+
for cb in callbacks:
|
| 191 |
+
cb("failed", "simulation pool closed")
|
| 192 |
+
# Release the queues' semaphores now, not at interpreter exit.
|
| 193 |
+
for q in (self._tasks, self._out):
|
| 194 |
+
q.close()
|
| 195 |
+
q.join_thread()
|
| 196 |
+
for p in procs:
|
| 197 |
+
with contextlib.suppress(ValueError):
|
| 198 |
+
p.close()
|
| 199 |
+
|
| 200 |
+
# -- state -------------------------------------------------------------------
|
| 201 |
+
@property
|
| 202 |
+
def ready(self) -> int:
|
| 203 |
+
with self._lock:
|
| 204 |
+
return len(self._ready)
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def block_s(self) -> float:
|
| 208 |
+
"""Current estimate of the compute time of one block, seconds."""
|
| 209 |
+
return self._block_s
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def compute_ratio(self) -> float:
|
| 213 |
+
"""Estimated wall seconds per simulated second."""
|
| 214 |
+
return self._block_s / BLOCK_S
|
| 215 |
+
|
| 216 |
+
@property
|
| 217 |
+
def queued(self) -> int:
|
| 218 |
+
with self._lock:
|
| 219 |
+
return len(self._pending)
|
| 220 |
+
|
| 221 |
+
def expected_wait(self, now: float | None = None) -> float:
|
| 222 |
+
now = time.monotonic() if now is None else now
|
| 223 |
+
with self._lock:
|
| 224 |
+
running = [t0 for w, (_, t0) in self._running.items() if w in self._ready]
|
| 225 |
+
return expected_wait(now, len(self._ready), running, len(self._pending),
|
| 226 |
+
self._block_s)
|
| 227 |
+
|
| 228 |
+
# -- jobs ----------------------------------------------------------------------
|
| 229 |
+
def submit(self, spec: BlockSpec, callback: Callback) -> int:
|
| 230 |
+
spec.validate()
|
| 231 |
+
with self._lock:
|
| 232 |
+
if self.error is not None and not self._ready:
|
| 233 |
+
raise PoolUnavailable(self.error)
|
| 234 |
+
if self._closing or self._reader is None:
|
| 235 |
+
raise PoolUnavailable("simulation pool is not running")
|
| 236 |
+
job = self._next_job
|
| 237 |
+
self._next_job += 1
|
| 238 |
+
self._pending[job] = spec
|
| 239 |
+
self._callbacks[job] = callback
|
| 240 |
+
self._tasks.put((job, spec))
|
| 241 |
+
return job
|
| 242 |
+
|
| 243 |
+
def _read(self) -> None:
|
| 244 |
+
while True:
|
| 245 |
+
try:
|
| 246 |
+
job, kind, payload = self._out.get(timeout=0.5)
|
| 247 |
+
except queue.Empty:
|
| 248 |
+
if self._closing:
|
| 249 |
+
return
|
| 250 |
+
self._check_workers()
|
| 251 |
+
continue
|
| 252 |
+
except (EOFError, OSError):
|
| 253 |
+
return
|
| 254 |
+
if job is None:
|
| 255 |
+
self._control(kind, payload)
|
| 256 |
+
continue
|
| 257 |
+
self._dispatch(job, kind, payload)
|
| 258 |
+
|
| 259 |
+
def _control(self, kind: str, payload: Any) -> None:
|
| 260 |
+
with self._lock:
|
| 261 |
+
if kind == "ready":
|
| 262 |
+
self._ready.add(payload)
|
| 263 |
+
self.error = None
|
| 264 |
+
return
|
| 265 |
+
idx, msg = payload
|
| 266 |
+
log.error("simulation worker %s failed to load: %s", idx, msg)
|
| 267 |
+
self.error = msg
|
| 268 |
+
self._procs.pop(idx, None)
|
| 269 |
+
dead_pool = not self._procs
|
| 270 |
+
orphans = list(self._callbacks.items()) if dead_pool else []
|
| 271 |
+
if dead_pool:
|
| 272 |
+
self._callbacks.clear()
|
| 273 |
+
self._pending.clear()
|
| 274 |
+
for _, cb in orphans:
|
| 275 |
+
cb("failed", f"simulation worker failed to load: {msg}")
|
| 276 |
+
|
| 277 |
+
def _dispatch(self, job: int, kind: str, payload: Any) -> None:
|
| 278 |
+
with self._lock:
|
| 279 |
+
cb = self._callbacks.get(job)
|
| 280 |
+
if kind == "started":
|
| 281 |
+
self._pending.pop(job, None)
|
| 282 |
+
self._running[payload[0]] = (job, time.monotonic())
|
| 283 |
+
payload = payload[1:]
|
| 284 |
+
elif kind in ("done", "failed"):
|
| 285 |
+
self._callbacks.pop(job, None)
|
| 286 |
+
for w, (j, _) in list(self._running.items()):
|
| 287 |
+
if j == job:
|
| 288 |
+
del self._running[w]
|
| 289 |
+
if kind == "done":
|
| 290 |
+
self._block_s += self._ewma * (payload[0] - self._block_s)
|
| 291 |
+
if cb is not None:
|
| 292 |
+
try:
|
| 293 |
+
cb(kind, payload)
|
| 294 |
+
except Exception: # a consumer's problem must not stop the reader
|
| 295 |
+
log.exception("simulation callback failed")
|
| 296 |
+
|
| 297 |
+
def _check_workers(self) -> None:
|
| 298 |
+
"""A worker that died (e.g. killed for memory) fails its block and is replaced."""
|
| 299 |
+
failed: list[Callback] = []
|
| 300 |
+
with self._lock:
|
| 301 |
+
for idx, p in list(self._procs.items()):
|
| 302 |
+
if p.is_alive() or self._closing:
|
| 303 |
+
continue
|
| 304 |
+
del self._procs[idx]
|
| 305 |
+
self._ready.discard(idx)
|
| 306 |
+
job_t0 = self._running.pop(idx, None)
|
| 307 |
+
if job_t0 is not None:
|
| 308 |
+
cb = self._callbacks.pop(job_t0[0], None)
|
| 309 |
+
if cb is not None:
|
| 310 |
+
failed.append(cb)
|
| 311 |
+
log.error("simulation worker %s died (exit %s); restarting", idx, p.exitcode)
|
| 312 |
+
self._spawn()
|
| 313 |
+
for cb in failed:
|
| 314 |
+
cb("failed", "simulation worker died")
|
flysim/src/flysim/live/service.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The live-run service: live or replay, and the message stream.
|
| 2 |
+
|
| 3 |
+
``LiveService.stream(request)`` yields JSON-ready dicts, one per message (for example
|
| 4 |
+
one WebSocket text message). The format is described in ``docs/live-sim.md``. In
|
| 5 |
+
short: ``queued`` (live only), ``start``, 60 ``chunk`` messages (10 ms each), then
|
| 6 |
+
``end``; or ``error``. Every message names the stimulus, its chain and the chain's
|
| 7 |
+
chain-test status (``validated`` or ``not_validated``), and whether it is ``live`` or a
|
| 8 |
+
``replay``.
|
| 9 |
+
|
| 10 |
+
**Live or replay.**
|
| 11 |
+
1. A recording of exactly this (stimulus, rounded rate, seed) exists and repeats are
|
| 12 |
+
served from the cache: replay (reason ``repeat``). It is the same computation, since a
|
| 13 |
+
block is a pure function of its key.
|
| 14 |
+
2. Otherwise, if a new block would wait at most ``max_wait_s`` for a worker: live.
|
| 15 |
+
3. Otherwise a recording of the same stimulus and rounded rate is replayed, the requested
|
| 16 |
+
seed if stored, else the lowest stored seed (reason ``busy``).
|
| 17 |
+
4. With no recording to fall back on, the block is queued live anyway (or refused when
|
| 18 |
+
the queue is full).
|
| 19 |
+
|
| 20 |
+
**Pacing.** Workers stream as fast as they compute; the stream runs ahead of the
|
| 21 |
+
display. ``start.pacing.stretch`` is ``max(min_stretch, compute_ratio x
|
| 22 |
+
1.2)``, where ``compute_ratio`` is the pool's running estimate of wall seconds per
|
| 23 |
+
simulated second. The display shows simulated time ``t`` at ``t x stretch`` after it
|
| 24 |
+
starts the block, so it never overtakes the stream. A replay has no compute to wait for:
|
| 25 |
+
its stretch is ``min_stretch``.
|
| 26 |
+
|
| 27 |
+
The stimulus and rate are inputs chosen by the client; the stream is a readout only.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
from __future__ import annotations
|
| 31 |
+
|
| 32 |
+
import asyncio
|
| 33 |
+
import contextlib
|
| 34 |
+
import math
|
| 35 |
+
import uuid
|
| 36 |
+
from collections.abc import AsyncIterator
|
| 37 |
+
from dataclasses import dataclass
|
| 38 |
+
from pathlib import Path
|
| 39 |
+
from typing import Any
|
| 40 |
+
|
| 41 |
+
from flysim.live.cache import Recording, ReplayCache
|
| 42 |
+
from flysim.live.model import (
|
| 43 |
+
BLOCK_S,
|
| 44 |
+
BLOCK_STEPS,
|
| 45 |
+
CHUNK_STEPS,
|
| 46 |
+
EXPERIMENT,
|
| 47 |
+
MAX_RATE_HZ,
|
| 48 |
+
MAX_SEED,
|
| 49 |
+
N_CHUNKS,
|
| 50 |
+
PARAMS,
|
| 51 |
+
STIM_STEPS,
|
| 52 |
+
STIMULI,
|
| 53 |
+
BlockSpec,
|
| 54 |
+
Chunk,
|
| 55 |
+
InvalidRequest,
|
| 56 |
+
ModelSource,
|
| 57 |
+
model_fingerprint,
|
| 58 |
+
round_rate,
|
| 59 |
+
)
|
| 60 |
+
from flysim.live.pool import PoolUnavailable, WorkerPool
|
| 61 |
+
|
| 62 |
+
MIN_STRETCH_RANGE = (1.0, 100.0)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@dataclass(frozen=True)
|
| 66 |
+
class LiveConfig:
|
| 67 |
+
#: Worker processes, one block each at a time ("one run per core"). 0: replay only.
|
| 68 |
+
workers: int = 1
|
| 69 |
+
#: Replay cache directory (compressed recordings); None: no cache.
|
| 70 |
+
cache_dir: Path | None = None
|
| 71 |
+
#: Directory for the unpacked, memory-mapped matrix; None: each worker decompresses.
|
| 72 |
+
unpack_dir: Path | None = None
|
| 73 |
+
#: Default slow motion for display (decided 2026-11-05, docs/live-sim.md).
|
| 74 |
+
min_stretch: float = 4.0
|
| 75 |
+
#: A live block that would wait longer than this for a worker falls back to a replay.
|
| 76 |
+
max_wait_s: float = 2.0
|
| 77 |
+
#: Requested rates are rounded to this grid; live and replay run the rounded rate.
|
| 78 |
+
rate_step_hz: float = 5.0
|
| 79 |
+
#: Wall seconds per simulated second before any block has been timed (`vec` kernel,
|
| 80 |
+
#: provisional benchmark, records/results/speed-vec.md).
|
| 81 |
+
compute_ratio_prior: float = 1.12
|
| 82 |
+
#: Replay cache size limit in bytes (least recently used go first); None: no limit.
|
| 83 |
+
cache_max_bytes: int | None = 1 << 30
|
| 84 |
+
#: Safety margin in the stretch formula.
|
| 85 |
+
stretch_margin: float = 1.2
|
| 86 |
+
#: Replay an exact recording instead of computing the same block again.
|
| 87 |
+
serve_repeats: bool = True
|
| 88 |
+
#: Blocks allowed to wait in the queue; more are refused when no replay exists.
|
| 89 |
+
max_queue: int = 8
|
| 90 |
+
#: Give up on a live block when no message arrives for this long.
|
| 91 |
+
event_timeout_s: float = 120.0
|
| 92 |
+
experiment: str = EXPERIMENT
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@dataclass(frozen=True)
|
| 96 |
+
class BlockRequest:
|
| 97 |
+
stimulus: str
|
| 98 |
+
rate_hz: float
|
| 99 |
+
seed: int
|
| 100 |
+
min_stretch: float | None = None
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class LiveService:
|
| 104 |
+
def __init__(self, source: ModelSource, config: LiveConfig,
|
| 105 |
+
pool: WorkerPool | None = None) -> None:
|
| 106 |
+
self.config = config
|
| 107 |
+
self.fingerprint = model_fingerprint(source, config.experiment)
|
| 108 |
+
self.cache = (ReplayCache(config.cache_dir, self.fingerprint, config.cache_max_bytes)
|
| 109 |
+
if config.cache_dir is not None else None)
|
| 110 |
+
if pool is None and config.workers > 0:
|
| 111 |
+
pool = WorkerPool(source, config.workers, experiment=config.experiment,
|
| 112 |
+
cache_root=config.cache_dir,
|
| 113 |
+
cache_max_bytes=config.cache_max_bytes,
|
| 114 |
+
compute_ratio_prior=config.compute_ratio_prior)
|
| 115 |
+
self.pool = pool
|
| 116 |
+
|
| 117 |
+
def start(self) -> None:
|
| 118 |
+
if self.pool is not None:
|
| 119 |
+
self.pool.start()
|
| 120 |
+
|
| 121 |
+
def close(self) -> None:
|
| 122 |
+
if self.pool is not None:
|
| 123 |
+
self.pool.close()
|
| 124 |
+
|
| 125 |
+
def info(self) -> dict[str, Any]:
|
| 126 |
+
"""What a client needs before asking for a block."""
|
| 127 |
+
pool = self.pool
|
| 128 |
+
return {
|
| 129 |
+
"live": pool is not None and pool.error is None,
|
| 130 |
+
"workers_ready": pool.ready if pool is not None else 0,
|
| 131 |
+
"stimuli": [{"stimulus": s.name, "chain": s.chain, "readout": s.readout,
|
| 132 |
+
"chain_status": s.status, "basis": s.basis}
|
| 133 |
+
for s in STIMULI.values()],
|
| 134 |
+
"rate_hz": {"min": 0.0, "max": MAX_RATE_HZ, "step": self.config.rate_step_hz},
|
| 135 |
+
"seed": {"min": 0, "max": MAX_SEED},
|
| 136 |
+
"min_stretch": {"default": self.config.min_stretch,
|
| 137 |
+
"min": MIN_STRETCH_RANGE[0], "max": MIN_STRETCH_RANGE[1]},
|
| 138 |
+
"block": _block_info(),
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
def resolve(self, req: BlockRequest) -> tuple[BlockSpec, float]:
|
| 142 |
+
"""Validate a request: the spec it runs (rounded rate) and its min_stretch."""
|
| 143 |
+
BlockSpec(req.stimulus, float(req.rate_hz), int(req.seed)).validate()
|
| 144 |
+
ms = self.config.min_stretch if req.min_stretch is None else float(req.min_stretch)
|
| 145 |
+
if not (math.isfinite(ms) and MIN_STRETCH_RANGE[0] <= ms <= MIN_STRETCH_RANGE[1]):
|
| 146 |
+
raise InvalidRequest(f"min_stretch must be in [{MIN_STRETCH_RANGE[0]:g}, "
|
| 147 |
+
f"{MIN_STRETCH_RANGE[1]:g}]")
|
| 148 |
+
rate = round_rate(float(req.rate_hz), self.config.rate_step_hz)
|
| 149 |
+
return BlockSpec(req.stimulus, rate, int(req.seed)), ms
|
| 150 |
+
|
| 151 |
+
async def stream(self, req: BlockRequest) -> AsyncIterator[dict[str, Any]]:
|
| 152 |
+
try:
|
| 153 |
+
spec, min_stretch = self.resolve(req)
|
| 154 |
+
except InvalidRequest as e:
|
| 155 |
+
yield {"type": "error", "detail": str(e)}
|
| 156 |
+
return
|
| 157 |
+
run = uuid.uuid4().hex[:12]
|
| 158 |
+
stim = STIMULI[spec.stimulus]
|
| 159 |
+
base = {"run": run, "stimulus": spec.stimulus, "chain": stim.chain,
|
| 160 |
+
"readout": stim.readout, "chain_status": stim.status}
|
| 161 |
+
cfg, pool, cache = self.config, self.pool, self.cache
|
| 162 |
+
|
| 163 |
+
exact = cache.get(spec) if cache is not None else None
|
| 164 |
+
if exact is not None and cfg.serve_repeats:
|
| 165 |
+
for m in _replay(exact, base, req, min_stretch, "repeat"):
|
| 166 |
+
yield m
|
| 167 |
+
return
|
| 168 |
+
live_ok = pool is not None and pool.error is None
|
| 169 |
+
wait = pool.expected_wait() if pool is not None and live_ok else math.inf
|
| 170 |
+
if wait > cfg.max_wait_s:
|
| 171 |
+
fallback = exact or (cache.find(spec) if cache is not None else None)
|
| 172 |
+
if fallback is not None:
|
| 173 |
+
for m in _replay(fallback, base, req, min_stretch, "busy"):
|
| 174 |
+
yield m
|
| 175 |
+
return
|
| 176 |
+
if pool is None or not live_ok:
|
| 177 |
+
why = pool.error if pool is not None and pool.error else "no simulation workers"
|
| 178 |
+
yield {**base, "type": "error", "source": "live",
|
| 179 |
+
"detail": f"live simulation unavailable ({why}) and no recording to replay"}
|
| 180 |
+
return
|
| 181 |
+
if pool.queued >= cfg.max_queue:
|
| 182 |
+
yield {**base, "type": "error", "source": "live",
|
| 183 |
+
"detail": "simulation queue is full; try again shortly"}
|
| 184 |
+
return
|
| 185 |
+
async for m in self._live(pool, spec, base, req, min_stretch, wait):
|
| 186 |
+
yield m
|
| 187 |
+
|
| 188 |
+
async def _live(self, pool: WorkerPool, spec: BlockSpec, base: dict[str, Any],
|
| 189 |
+
req: BlockRequest, min_stretch: float, wait: float
|
| 190 |
+
) -> AsyncIterator[dict[str, Any]]:
|
| 191 |
+
loop = asyncio.get_running_loop()
|
| 192 |
+
events: asyncio.Queue[tuple[str, Any]] = asyncio.Queue()
|
| 193 |
+
|
| 194 |
+
def deliver(kind: str, payload: Any) -> None:
|
| 195 |
+
with contextlib.suppress(RuntimeError): # the consumer's loop is gone
|
| 196 |
+
loop.call_soon_threadsafe(events.put_nowait, (kind, payload))
|
| 197 |
+
|
| 198 |
+
base = {**base, "source": "live"}
|
| 199 |
+
try:
|
| 200 |
+
pool.submit(spec, deliver)
|
| 201 |
+
except PoolUnavailable as e:
|
| 202 |
+
yield {**base, "type": "error", "detail": f"live simulation unavailable ({e})"}
|
| 203 |
+
return
|
| 204 |
+
yield {**base, "type": "queued", "queue_position": pool.queued,
|
| 205 |
+
"expected_wait_s": None if math.isinf(wait) else round(wait, 3)}
|
| 206 |
+
slots: tuple[tuple[str, str], ...] = ()
|
| 207 |
+
while True:
|
| 208 |
+
try:
|
| 209 |
+
kind, payload = await asyncio.wait_for(events.get(), self.config.event_timeout_s)
|
| 210 |
+
except TimeoutError:
|
| 211 |
+
yield {**base, "type": "error", "detail": "simulation timed out"}
|
| 212 |
+
return
|
| 213 |
+
if kind == "started":
|
| 214 |
+
n_neurons, slots = payload
|
| 215 |
+
ratio = pool.compute_ratio
|
| 216 |
+
yield _start(base, spec, req, n_neurons, slots, {
|
| 217 |
+
"stretch": round(max(min_stretch, ratio * self.config.stretch_margin), 3),
|
| 218 |
+
"min_stretch": min_stretch, "compute_ratio": round(ratio, 3),
|
| 219 |
+
"margin": self.config.stretch_margin}, None)
|
| 220 |
+
elif kind == "chunk":
|
| 221 |
+
yield _chunk(base, payload, slots)
|
| 222 |
+
elif kind == "done":
|
| 223 |
+
compute_s, summary = payload
|
| 224 |
+
yield {**base, "type": "end", "summary": summary,
|
| 225 |
+
"compute_s": round(compute_s, 3),
|
| 226 |
+
"compute_ratio": round(compute_s / BLOCK_S, 3)}
|
| 227 |
+
return
|
| 228 |
+
else:
|
| 229 |
+
yield {**base, "type": "error", "detail": str(payload)}
|
| 230 |
+
return
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# ----------------------------------------------------------------------------- messages
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _block_info() -> dict[str, Any]:
|
| 237 |
+
return {"dt_ms": PARAMS.dt, "steps": BLOCK_STEPS, "chunk_steps": CHUNK_STEPS,
|
| 238 |
+
"chunks": N_CHUNKS, "duration_ms": BLOCK_STEPS * PARAMS.dt,
|
| 239 |
+
"stimulus_ms": [0.0, STIM_STEPS * PARAMS.dt], "starts_from_rest": True}
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _readouts(slots: tuple[tuple[str, str], ...], counts: Any) -> dict[str, dict[str, int]]:
|
| 243 |
+
out: dict[str, dict[str, int]] = {}
|
| 244 |
+
for (r, side), c in zip(slots, counts, strict=True):
|
| 245 |
+
out.setdefault(r, {})[side] = int(c)
|
| 246 |
+
return out
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _start(base: dict[str, Any], spec: BlockSpec, req: BlockRequest, n_neurons: int,
|
| 250 |
+
slots: tuple[tuple[str, str], ...], pacing: dict[str, Any],
|
| 251 |
+
replay_reason: str | None) -> dict[str, Any]:
|
| 252 |
+
layout: dict[str, list[str]] = {}
|
| 253 |
+
for r, side in slots:
|
| 254 |
+
layout.setdefault(r, []).append(side)
|
| 255 |
+
return {**base, "type": "start", "replay_reason": replay_reason,
|
| 256 |
+
"rate_hz": spec.rate_hz, "rate_hz_requested": float(req.rate_hz),
|
| 257 |
+
"seed": spec.seed, "seed_requested": int(req.seed),
|
| 258 |
+
"status_basis": STIMULI[spec.stimulus].basis, "block": _block_info(),
|
| 259 |
+
"n_neurons": n_neurons, "readouts": layout, "pacing": pacing}
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def _chunk(base: dict[str, Any], c: Chunk, slots: tuple[tuple[str, str], ...]
|
| 263 |
+
) -> dict[str, Any]:
|
| 264 |
+
return {**base, "type": "chunk", "index": c.index,
|
| 265 |
+
"t0_ms": round(c.step0 * PARAMS.dt, 4), "t1_ms": round(c.step1 * PARAMS.dt, 4),
|
| 266 |
+
"neurons": c.neurons.tolist(), "steps": (c.steps - c.step0).tolist(),
|
| 267 |
+
"readouts": _readouts(slots, c.counts)}
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _replay(rec: Recording, base: dict[str, Any], req: BlockRequest, min_stretch: float,
|
| 271 |
+
reason: str) -> list[dict[str, Any]]:
|
| 272 |
+
base = {**base, "source": "replay"}
|
| 273 |
+
out = [_start(base, rec.spec, req, rec.n_neurons, rec.slots,
|
| 274 |
+
{"stretch": min_stretch, "min_stretch": min_stretch, "compute_ratio": 0.0,
|
| 275 |
+
"margin": None}, reason)]
|
| 276 |
+
out += [_chunk(base, c, rec.slots) for c in rec.chunks()]
|
| 277 |
+
out.append({**base, "type": "end", "summary": rec.summary(),
|
| 278 |
+
"compute_s": round(rec.compute_s, 3),
|
| 279 |
+
"compute_ratio": round(rec.compute_s / BLOCK_S, 3)})
|
| 280 |
+
return out
|
flysim/src/flysim/pipeline/__init__.py
ADDED
|
File without changes
|
flysim/src/flysim/pipeline/connectome.py
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build the signed sparse weight matrix artefact from MaleCNS v1.0.
|
| 2 |
+
|
| 3 |
+
Pipeline (see docs/connectome-artifact.md):
|
| 4 |
+
|
| 5 |
+
1. Fetch the public flat-connectome tables (annotations, transmitters, weights).
|
| 6 |
+
2. Keep bodies with ``status == "Traced"`` and give them a dense index, ordered
|
| 7 |
+
by (superclass, type, bodyId) so that neurons of one cell type sit together.
|
| 8 |
+
3. Sign each presynaptic neuron from its consensus transmitter:
|
| 9 |
+
ACh +1; GABA, glutamate, histamine -1; everything else 0.
|
| 10 |
+
4. Build ``W[post, pre] = sign(pre) * synapse_count`` and store it column-wise
|
| 11 |
+
by presynaptic neuron (CSC), so a simulation step only has to walk the
|
| 12 |
+
outgoing edges of the neurons that spiked. Edges from sign-0 neurons have
|
| 13 |
+
no fast effect in the model and are left out (their count is recorded).
|
| 14 |
+
5. int16 weights (lossless: the largest traced count is 2,591).
|
| 15 |
+
6. Variants keep edges with at least 1/2/3/5/10 synapses. Neurons are never
|
| 16 |
+
removed, so indices are identical across variants.
|
| 17 |
+
7. Write one ``neurons.parquet`` (shared), one ``matrix-<variant>.tar.zst`` per
|
| 18 |
+
variant, ``manifest.json`` and ``SHA256SUMS``.
|
| 19 |
+
|
| 20 |
+
Nothing here is fitted or trained: the weights are fixed by the data, and the
|
| 21 |
+
global weight scale is a model parameter applied by the engine, not stored here.
|
| 22 |
+
|
| 23 |
+
Usage::
|
| 24 |
+
|
| 25 |
+
python -m flysim.pipeline.connectome fetch-raw RAW_DIR
|
| 26 |
+
python -m flysim.pipeline.connectome build RAW_DIR OUT_DIR
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import argparse
|
| 32 |
+
import hashlib
|
| 33 |
+
import io
|
| 34 |
+
import json
|
| 35 |
+
import sys
|
| 36 |
+
import tarfile
|
| 37 |
+
import urllib.request
|
| 38 |
+
from pathlib import Path
|
| 39 |
+
|
| 40 |
+
import numpy as np
|
| 41 |
+
import pyarrow as pa
|
| 42 |
+
import pyarrow.compute as pc
|
| 43 |
+
import pyarrow.feather as feather
|
| 44 |
+
import pyarrow.ipc as ipc
|
| 45 |
+
import pyarrow.parquet as pq
|
| 46 |
+
import zstandard
|
| 47 |
+
|
| 48 |
+
DATASET = "MaleCNS v1.0"
|
| 49 |
+
SOURCE_BASE = "https://storage.googleapis.com/flyem-male-cns/v1.0/connectome-data/flat-connectome"
|
| 50 |
+
RAW_FILES = {
|
| 51 |
+
"annotations": "body-annotations-male-cns-v1.0-minconf-0.5.feather",
|
| 52 |
+
"transmitters": "body-neurotransmitters-male-cns-v1.0.feather",
|
| 53 |
+
"weights": "connectome-weights-male-cns-v1.0-minconf-0.5.feather",
|
| 54 |
+
}
|
| 55 |
+
SIGN_OF_NT = {"acetylcholine": 1, "gaba": -1, "glutamate": -1, "histamine": -1}
|
| 56 |
+
VARIANTS = {"full": 1, "min2": 2, "min3": 3, "min5": 5, "min10": 10}
|
| 57 |
+
SCHEMA_VERSION = "flysim.connectome/1"
|
| 58 |
+
ZSTD_LEVEL = 19
|
| 59 |
+
LICENSE = (
|
| 60 |
+
"Data: MaleCNS v1.0, FlyEM / Janelia Research Campus, CC-BY 4.0. "
|
| 61 |
+
"Cite: Berg, S. et al., Sexual dimorphism in the complete Drosophila male "
|
| 62 |
+
"central nervous system connectome, Cell (2026)."
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# ----------------------------------------------------------------------------- utils
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def sha256_file(path: Path) -> str:
|
| 70 |
+
h = hashlib.sha256()
|
| 71 |
+
with open(path, "rb") as f:
|
| 72 |
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
| 73 |
+
h.update(chunk)
|
| 74 |
+
return h.hexdigest()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def sha256_array(a: np.ndarray) -> str:
|
| 78 |
+
"""Hash of an array's dtype, shape and raw bytes (independent of file format)."""
|
| 79 |
+
h = hashlib.sha256()
|
| 80 |
+
h.update(f"{a.dtype.str}{a.shape}".encode())
|
| 81 |
+
h.update(np.ascontiguousarray(a).tobytes())
|
| 82 |
+
return h.hexdigest()
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def fetch_raw(raw_dir: Path) -> None:
|
| 86 |
+
raw_dir.mkdir(parents=True, exist_ok=True)
|
| 87 |
+
for name in RAW_FILES.values():
|
| 88 |
+
dest = raw_dir / name
|
| 89 |
+
if dest.exists():
|
| 90 |
+
print(f"have {name}")
|
| 91 |
+
continue
|
| 92 |
+
print(f"fetching {name}")
|
| 93 |
+
tmp = dest.with_suffix(".part")
|
| 94 |
+
urllib.request.urlretrieve(f"{SOURCE_BASE}/{name}", tmp)
|
| 95 |
+
tmp.rename(dest)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ----------------------------------------------------------------------------- neurons
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def load_neurons(raw_dir: Path) -> tuple[pa.Table, np.ndarray, list, list]:
|
| 102 |
+
"""Traced neurons in dense-index order, sorted bodyIds, and raw soma columns."""
|
| 103 |
+
ann = feather.read_table(
|
| 104 |
+
raw_dir / RAW_FILES["annotations"],
|
| 105 |
+
columns=["bodyId", "status", "type", "instance", "superclass", "class",
|
| 106 |
+
"somaSide", "rootSide", "somaLocation", "tosomaLocation"],
|
| 107 |
+
)
|
| 108 |
+
ann = ann.filter(pc.equal(ann["status"], "Traced")).drop(["status"])
|
| 109 |
+
|
| 110 |
+
nt = feather.read_table(
|
| 111 |
+
raw_dir / RAW_FILES["transmitters"], columns=["body", "consensus_nt"]
|
| 112 |
+
).to_pydict()
|
| 113 |
+
nt_of: dict[int, str] = {}
|
| 114 |
+
for body, cons in zip(nt["body"], nt["consensus_nt"], strict=True):
|
| 115 |
+
if body not in nt_of and cons is not None:
|
| 116 |
+
nt_of[body] = cons
|
| 117 |
+
|
| 118 |
+
body = np.asarray(ann["bodyId"].to_numpy(), dtype=np.int64)
|
| 119 |
+
superclass = ann["superclass"].to_pylist()
|
| 120 |
+
typ = ann["type"].to_pylist()
|
| 121 |
+
# Order: superclass, type, bodyId; missing strings sort last.
|
| 122 |
+
key_sc = np.array([s if s is not None else "" for s in superclass])
|
| 123 |
+
key_ty = np.array([t if t is not None else "" for t in typ])
|
| 124 |
+
order = np.lexsort((body, key_ty, key_sc))
|
| 125 |
+
ann = ann.take(pa.array(order))
|
| 126 |
+
body = body[order]
|
| 127 |
+
|
| 128 |
+
transmitter = [nt_of.get(int(b), "") for b in body]
|
| 129 |
+
sign = np.array([SIGN_OF_NT.get(t, 0) for t in transmitter], dtype=np.int8)
|
| 130 |
+
|
| 131 |
+
neurons = pa.table(
|
| 132 |
+
{
|
| 133 |
+
"idx": pa.array(np.arange(len(body), dtype=np.int32)),
|
| 134 |
+
"bodyId": pa.array(body),
|
| 135 |
+
"type": ann["type"],
|
| 136 |
+
"instance": ann["instance"],
|
| 137 |
+
"superclass": ann["superclass"],
|
| 138 |
+
"class": ann["class"],
|
| 139 |
+
"somaSide": ann["somaSide"],
|
| 140 |
+
"rootSide": ann["rootSide"],
|
| 141 |
+
"transmitter": pa.array([t or None for t in transmitter], pa.string()),
|
| 142 |
+
"sign": pa.array(sign),
|
| 143 |
+
}
|
| 144 |
+
)
|
| 145 |
+
soma = ann["somaLocation"].to_pylist()
|
| 146 |
+
tosoma = ann["tosomaLocation"].to_pylist()
|
| 147 |
+
sorted_ids = np.sort(body)
|
| 148 |
+
return neurons, sorted_ids, soma, tosoma
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# ----------------------------------------------------------------------------- edges
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def load_edges(raw_dir: Path, body_by_idx: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 155 |
+
"""Traced->traced edges as (pre_idx, post_idx, count), streamed batch by batch."""
|
| 156 |
+
sorter = np.argsort(body_by_idx)
|
| 157 |
+
sorted_ids = body_by_idx[sorter]
|
| 158 |
+
|
| 159 |
+
def to_idx(ids: np.ndarray) -> np.ndarray:
|
| 160 |
+
pos = np.searchsorted(sorted_ids, ids)
|
| 161 |
+
pos = np.clip(pos, 0, len(sorted_ids) - 1)
|
| 162 |
+
hit = sorted_ids[pos] == ids
|
| 163 |
+
out = np.full(ids.shape, -1, dtype=np.int64)
|
| 164 |
+
out[hit] = sorter[pos[hit]]
|
| 165 |
+
return out
|
| 166 |
+
|
| 167 |
+
pres, posts, counts = [], [], []
|
| 168 |
+
with ipc.open_file(raw_dir / RAW_FILES["weights"]) as reader:
|
| 169 |
+
for i in range(reader.num_record_batches):
|
| 170 |
+
b = reader.get_batch(i)
|
| 171 |
+
pre = to_idx(b.column("body_pre").to_numpy())
|
| 172 |
+
post = to_idx(b.column("body_post").to_numpy())
|
| 173 |
+
w = b.column("weight").to_numpy()
|
| 174 |
+
keep = (pre >= 0) & (post >= 0) & (w > 0)
|
| 175 |
+
pres.append(pre[keep].astype(np.int32))
|
| 176 |
+
posts.append(post[keep].astype(np.int32))
|
| 177 |
+
counts.append(w[keep])
|
| 178 |
+
pre = np.concatenate(pres)
|
| 179 |
+
post = np.concatenate(posts)
|
| 180 |
+
count = np.concatenate(counts)
|
| 181 |
+
if count.max() > np.iinfo(np.int16).max:
|
| 182 |
+
raise ValueError(f"count {count.max()} does not fit int16")
|
| 183 |
+
return pre, post, count.astype(np.int16)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def positions(neurons: pa.Table, soma: list, tosoma: list,
|
| 187 |
+
pre: np.ndarray, post: np.ndarray, count: np.ndarray) -> dict[str, np.ndarray]:
|
| 188 |
+
"""One 3D point per neuron, for display only.
|
| 189 |
+
|
| 190 |
+
soma location if annotated, else the 'to soma' location, else the
|
| 191 |
+
synapse-weighted mean of its partners' positions (an approximation, flagged
|
| 192 |
+
in ``pos_source``), else NaN. Units are the source table's voxel units.
|
| 193 |
+
"""
|
| 194 |
+
n = neurons.num_rows
|
| 195 |
+
xyz = np.full((n, 3), np.nan, dtype=np.float32)
|
| 196 |
+
src = np.zeros(n, dtype=np.int8) # 0 none, 1 soma, 2 tosoma, 3 partners
|
| 197 |
+
for i, (s, t) in enumerate(zip(soma, tosoma, strict=True)):
|
| 198 |
+
if s is not None:
|
| 199 |
+
xyz[i] = s
|
| 200 |
+
src[i] = 1
|
| 201 |
+
elif t is not None:
|
| 202 |
+
xyz[i] = t
|
| 203 |
+
src[i] = 2
|
| 204 |
+
known = src > 0
|
| 205 |
+
acc = np.zeros((n, 3), dtype=np.float64)
|
| 206 |
+
wsum = np.zeros(n, dtype=np.float64)
|
| 207 |
+
c = count.astype(np.float64)
|
| 208 |
+
for a, b in ((pre, post), (post, pre)): # partners in both directions
|
| 209 |
+
m = known[b] & ~known[a]
|
| 210 |
+
np.add.at(acc, a[m], xyz[b[m]] * c[m, None])
|
| 211 |
+
np.add.at(wsum, a[m], c[m])
|
| 212 |
+
fill = (~known) & (wsum > 0)
|
| 213 |
+
xyz[fill] = (acc[fill] / wsum[fill, None]).astype(np.float32)
|
| 214 |
+
src[fill] = 3
|
| 215 |
+
return {"x": xyz[:, 0], "y": xyz[:, 1], "z": xyz[:, 2], "pos_source": src}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# ----------------------------------------------------------------------------- matrix
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def to_csc(n: int, pre: np.ndarray, post: np.ndarray, weight: np.ndarray):
|
| 222 |
+
"""Column-compressed by presynaptic neuron; rows sorted within each column."""
|
| 223 |
+
order = np.lexsort((post, pre))
|
| 224 |
+
pre, post, weight = pre[order], post[order], weight[order]
|
| 225 |
+
indptr = np.zeros(n + 1, dtype=np.int64)
|
| 226 |
+
np.cumsum(np.bincount(pre, minlength=n), out=indptr[1:])
|
| 227 |
+
return indptr, post.astype(np.int32), weight.astype(np.int16)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def write_tar_zst(path: Path, arrays: dict[str, np.ndarray]) -> None:
|
| 231 |
+
"""Deterministic tar of .npy members, zstd-compressed."""
|
| 232 |
+
buf = io.BytesIO()
|
| 233 |
+
with tarfile.open(fileobj=buf, mode="w", format=tarfile.USTAR_FORMAT) as tar:
|
| 234 |
+
for name in sorted(arrays):
|
| 235 |
+
data = io.BytesIO()
|
| 236 |
+
np.save(data, arrays[name], allow_pickle=False)
|
| 237 |
+
info = tarfile.TarInfo(f"{name}.npy")
|
| 238 |
+
info.size = data.tell()
|
| 239 |
+
info.mtime = 0
|
| 240 |
+
info.mode = 0o644
|
| 241 |
+
data.seek(0)
|
| 242 |
+
tar.addfile(info, data)
|
| 243 |
+
cctx = zstandard.ZstdCompressor(level=ZSTD_LEVEL, threads=0, write_checksum=True)
|
| 244 |
+
path.write_bytes(cctx.compress(buf.getvalue()))
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def build(raw_dir: Path, out_dir: Path) -> dict:
|
| 248 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 249 |
+
neurons, _, soma, tosoma = load_neurons(raw_dir)
|
| 250 |
+
body_by_idx = neurons["bodyId"].to_numpy()
|
| 251 |
+
n = neurons.num_rows
|
| 252 |
+
print(f"traced neurons: {n}")
|
| 253 |
+
|
| 254 |
+
pre, post, count = load_edges(raw_dir, body_by_idx)
|
| 255 |
+
print(f"traced->traced edges: {len(count)}, synapses: {int(count.sum(dtype=np.int64))}")
|
| 256 |
+
|
| 257 |
+
pos = positions(neurons, soma, tosoma, pre, post, count)
|
| 258 |
+
for k, v in pos.items():
|
| 259 |
+
neurons = neurons.append_column(k, pa.array(v))
|
| 260 |
+
pq.write_table(neurons, out_dir / "neurons.parquet", compression="zstd")
|
| 261 |
+
|
| 262 |
+
sign = neurons["sign"].to_numpy()
|
| 263 |
+
s = sign[pre]
|
| 264 |
+
nonzero = s != 0
|
| 265 |
+
dropped = {
|
| 266 |
+
"edges_from_sign0_neurons": int((~nonzero).sum()),
|
| 267 |
+
"synapses_from_sign0_neurons": int(count[~nonzero].sum(dtype=np.int64)),
|
| 268 |
+
}
|
| 269 |
+
pre, post, count, s = pre[nonzero], post[nonzero], count[nonzero], s[nonzero]
|
| 270 |
+
signed = (count.astype(np.int32) * s).astype(np.int16)
|
| 271 |
+
total_syn = int(count.sum(dtype=np.int64))
|
| 272 |
+
|
| 273 |
+
variants = {}
|
| 274 |
+
for name, min_count in VARIANTS.items():
|
| 275 |
+
m = count >= min_count
|
| 276 |
+
indptr, indices, weights = to_csc(n, pre[m], post[m], signed[m])
|
| 277 |
+
path = out_dir / f"matrix-{name}.tar.zst"
|
| 278 |
+
write_tar_zst(path, {"indptr": indptr, "indices": indices, "weights": weights})
|
| 279 |
+
variants[name] = {
|
| 280 |
+
"file": path.name,
|
| 281 |
+
"min_synapses": min_count,
|
| 282 |
+
"edges": int(len(indices)),
|
| 283 |
+
"edge_fraction": round(len(indices) / len(count), 4),
|
| 284 |
+
"synapse_fraction": round(int(np.abs(weights).sum(dtype=np.int64)) / total_syn, 4),
|
| 285 |
+
"excitatory_edges": int((weights > 0).sum()),
|
| 286 |
+
"inhibitory_edges": int((weights < 0).sum()),
|
| 287 |
+
"array_sha256": {
|
| 288 |
+
"indptr": sha256_array(indptr),
|
| 289 |
+
"indices": sha256_array(indices),
|
| 290 |
+
"weights": sha256_array(weights),
|
| 291 |
+
},
|
| 292 |
+
"file_bytes": path.stat().st_size,
|
| 293 |
+
}
|
| 294 |
+
print(f"{name}: {len(indices)} edges, {path.stat().st_size / 1e6:.1f} MB")
|
| 295 |
+
|
| 296 |
+
manifest = {
|
| 297 |
+
"schema": SCHEMA_VERSION,
|
| 298 |
+
"dataset": DATASET,
|
| 299 |
+
"license": LICENSE,
|
| 300 |
+
"sources": {
|
| 301 |
+
k: {"url": f"{SOURCE_BASE}/{v}", "sha256": sha256_file(raw_dir / v)}
|
| 302 |
+
for k, v in RAW_FILES.items()
|
| 303 |
+
},
|
| 304 |
+
"rules": {
|
| 305 |
+
"neurons": "annotations.status == 'Traced'; never culled; same index in every variant",
|
| 306 |
+
"order": "lexicographic (superclass, type, bodyId); missing strings last",
|
| 307 |
+
"sign": "from body-neurotransmitters.consensus_nt of the presynaptic neuron: "
|
| 308 |
+
"acetylcholine +1; gaba, glutamate, histamine -1; anything else or missing 0",
|
| 309 |
+
"matrix": "W[post, pre] = sign(pre) * synapse_count; CSC by presynaptic neuron "
|
| 310 |
+
"(column = pre, row = post, rows ascending); edges from sign-0 neurons omitted", # noqa: E501
|
| 311 |
+
"dtype": "indptr int64, indices int32, weights int16 (lossless)",
|
| 312 |
+
"variants": "keep edges with synapse_count >= min_synapses",
|
| 313 |
+
"weight_scale": "not stored; the engine multiplies by a global w_syn",
|
| 314 |
+
"positions": "somaLocation, else tosomaLocation, else synapse-weighted mean of "
|
| 315 |
+
"partner positions (pos_source 3), else NaN; source voxel units",
|
| 316 |
+
},
|
| 317 |
+
"neurons": {
|
| 318 |
+
"count": n,
|
| 319 |
+
"sign_counts": {str(k): int((sign == k).sum()) for k in (1, -1, 0)},
|
| 320 |
+
"pos_source_counts": {
|
| 321 |
+
name: int((pos["pos_source"] == code).sum())
|
| 322 |
+
for code, name in enumerate(["none", "soma", "tosoma", "partners"])
|
| 323 |
+
},
|
| 324 |
+
"file": "neurons.parquet",
|
| 325 |
+
},
|
| 326 |
+
"edges_traced": int(len(pre) + dropped["edges_from_sign0_neurons"]),
|
| 327 |
+
"omitted": dropped,
|
| 328 |
+
"variants": variants,
|
| 329 |
+
}
|
| 330 |
+
(out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
| 331 |
+
|
| 332 |
+
files = sorted(p for p in out_dir.iterdir() if p.name != "SHA256SUMS")
|
| 333 |
+
(out_dir / "SHA256SUMS").write_text(
|
| 334 |
+
"".join(f"{sha256_file(p)} {p.name}\n" for p in files)
|
| 335 |
+
)
|
| 336 |
+
return manifest
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def main(argv: list[str] | None = None) -> int:
|
| 340 |
+
p = argparse.ArgumentParser(prog="python -m flysim.pipeline.connectome")
|
| 341 |
+
sub = p.add_subparsers(dest="cmd", required=True)
|
| 342 |
+
f = sub.add_parser("fetch-raw", help="download the MaleCNS flat-connectome tables")
|
| 343 |
+
f.add_argument("raw_dir", type=Path)
|
| 344 |
+
b = sub.add_parser("build", help="build the artefact from downloaded tables")
|
| 345 |
+
b.add_argument("raw_dir", type=Path)
|
| 346 |
+
b.add_argument("out_dir", type=Path)
|
| 347 |
+
a = p.parse_args(argv)
|
| 348 |
+
if a.cmd == "fetch-raw":
|
| 349 |
+
fetch_raw(a.raw_dir)
|
| 350 |
+
else:
|
| 351 |
+
build(a.raw_dir, a.out_dir)
|
| 352 |
+
return 0
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
if __name__ == "__main__":
|
| 356 |
+
sys.exit(main())
|
flysim/src/flysim/validation/__init__.py
ADDED
|
File without changes
|
flysim/src/flysim/validation/cases.json
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"source": "https://github.com/philshiu/Drosophila_brain_model/tree/91bdd1e7dcf193f3e7ca5a8933497fcef63b7960: example.ipynb (neu_sugar, id_mn9) and figures.ipynb (neu_water, neu_bitter, neu_JON_CE, id_aBN1)",
|
| 3 |
+
"dataset": "FlyWire v630 root IDs",
|
| 4 |
+
"groups": {
|
| 5 |
+
"sugar": [
|
| 6 |
+
720575940624963786,
|
| 7 |
+
720575940630233916,
|
| 8 |
+
720575940637568838,
|
| 9 |
+
720575940638202345,
|
| 10 |
+
720575940617000768,
|
| 11 |
+
720575940630797113,
|
| 12 |
+
720575940632889389,
|
| 13 |
+
720575940621754367,
|
| 14 |
+
720575940621502051,
|
| 15 |
+
720575940640649691,
|
| 16 |
+
720575940639332736,
|
| 17 |
+
720575940616885538,
|
| 18 |
+
720575940639198653,
|
| 19 |
+
720575940620900446,
|
| 20 |
+
720575940617937543,
|
| 21 |
+
720575940632425919,
|
| 22 |
+
720575940633143833,
|
| 23 |
+
720575940612670570,
|
| 24 |
+
720575940628853239,
|
| 25 |
+
720575940629176663,
|
| 26 |
+
720575940611875570
|
| 27 |
+
],
|
| 28 |
+
"water": [
|
| 29 |
+
720575940612950568,
|
| 30 |
+
720575940631898285,
|
| 31 |
+
720575940606002609,
|
| 32 |
+
720575940612579053,
|
| 33 |
+
720575940622902535,
|
| 34 |
+
720575940616177458,
|
| 35 |
+
720575940660292225,
|
| 36 |
+
720575940622486922,
|
| 37 |
+
720575940613786774,
|
| 38 |
+
720575940629852866,
|
| 39 |
+
720575940625861168,
|
| 40 |
+
720575940613996959,
|
| 41 |
+
720575940617857694,
|
| 42 |
+
720575940644965399,
|
| 43 |
+
720575940625203504,
|
| 44 |
+
720575940630553415,
|
| 45 |
+
720575940635172191,
|
| 46 |
+
720575940634796536
|
| 47 |
+
],
|
| 48 |
+
"bitter": [
|
| 49 |
+
720575940621778381,
|
| 50 |
+
720575940602353632,
|
| 51 |
+
720575940617094208,
|
| 52 |
+
720575940619197093,
|
| 53 |
+
720575940626287336,
|
| 54 |
+
720575940618600651,
|
| 55 |
+
720575940627692048,
|
| 56 |
+
720575940630195909,
|
| 57 |
+
720575940646212996,
|
| 58 |
+
720575940610483162,
|
| 59 |
+
720575940645743412,
|
| 60 |
+
720575940627578156,
|
| 61 |
+
720575940622298631,
|
| 62 |
+
720575940621008895,
|
| 63 |
+
720575940629146711,
|
| 64 |
+
720575940610259370,
|
| 65 |
+
720575940610481370,
|
| 66 |
+
720575940619028208,
|
| 67 |
+
720575940614281266,
|
| 68 |
+
720575940613061118,
|
| 69 |
+
720575940604027168
|
| 70 |
+
],
|
| 71 |
+
"jo_ce": [
|
| 72 |
+
720575940619341105,
|
| 73 |
+
720575940630122015,
|
| 74 |
+
720575940611061526,
|
| 75 |
+
720575940615848788,
|
| 76 |
+
720575940628444667,
|
| 77 |
+
720575940627941431,
|
| 78 |
+
720575940632449619,
|
| 79 |
+
720575940650244342,
|
| 80 |
+
720575940631866508,
|
| 81 |
+
720575940638681845,
|
| 82 |
+
720575940628978450,
|
| 83 |
+
720575940609522461,
|
| 84 |
+
720575940621442224,
|
| 85 |
+
720575940602506208,
|
| 86 |
+
720575940629022149,
|
| 87 |
+
720575940627109991,
|
| 88 |
+
720575940630020111,
|
| 89 |
+
720575940615986459,
|
| 90 |
+
720575940618684481,
|
| 91 |
+
720575940620382889,
|
| 92 |
+
720575940630080071,
|
| 93 |
+
720575940626565455,
|
| 94 |
+
720575940630319671,
|
| 95 |
+
720575940602720940,
|
| 96 |
+
720575940630564179,
|
| 97 |
+
720575940637632419,
|
| 98 |
+
720575940615809349,
|
| 99 |
+
720575940626042149,
|
| 100 |
+
720575940637054835,
|
| 101 |
+
720575940602132509,
|
| 102 |
+
720575940614188149,
|
| 103 |
+
720575940616951124,
|
| 104 |
+
720575940628101126,
|
| 105 |
+
720575940629055721,
|
| 106 |
+
720575940616589878,
|
| 107 |
+
720575940622449388,
|
| 108 |
+
720575940614427195,
|
| 109 |
+
720575940625797617,
|
| 110 |
+
720575940638664437,
|
| 111 |
+
720575940618467195,
|
| 112 |
+
720575940621729757,
|
| 113 |
+
720575940613971485,
|
| 114 |
+
720575940627585688,
|
| 115 |
+
720575940629650997,
|
| 116 |
+
720575940630059847,
|
| 117 |
+
720575940608742409,
|
| 118 |
+
720575940614351477,
|
| 119 |
+
720575940633153375,
|
| 120 |
+
720575940622937528,
|
| 121 |
+
720575940604753437,
|
| 122 |
+
720575940611783464,
|
| 123 |
+
720575940618599872,
|
| 124 |
+
720575940609541917,
|
| 125 |
+
720575940637410869,
|
| 126 |
+
720575940630070343,
|
| 127 |
+
720575940621397417,
|
| 128 |
+
720575940614035485,
|
| 129 |
+
720575940610018266,
|
| 130 |
+
720575940626307902,
|
| 131 |
+
720575940634634606,
|
| 132 |
+
720575940614060829,
|
| 133 |
+
720575940624799290,
|
| 134 |
+
720575940641921421,
|
| 135 |
+
720575940623298559,
|
| 136 |
+
720575940625559358,
|
| 137 |
+
720575940629138959,
|
| 138 |
+
720575940621625597,
|
| 139 |
+
720575940625962568,
|
| 140 |
+
720575940632767383,
|
| 141 |
+
720575940624915230
|
| 142 |
+
]
|
| 143 |
+
},
|
| 144 |
+
"readouts": {
|
| 145 |
+
"MN9": 720575940660219265,
|
| 146 |
+
"aBN1": 720575940630907434
|
| 147 |
+
}
|
| 148 |
+
}
|
flysim/src/flysim/validation/chain_controls.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"rules": "records/preregistration.md, section 4.1", "seed": 20261103, "pool": "visual_projection, somaSide R, sign +1, type not in LC4, LC16, LC9, LPLC1, LPLC2", "pool_size": 3533, "sets": {"55": [[18579, 20618, 21352, 23210, 24027, 25369, 25742, 26207, 26599, 28118, 29596, 30017, 33397, 33574, 34275, 34883, 35284, 36017, 36405, 38017, 39750, 40552, 41256, 41461, 42622, 46288, 47677, 49423, 50473, 52628, 54781, 55108, 55800, 56180, 56836, 58900, 61544, 63286, 63745, 66129, 66155, 66278, 68559, 70291, 70682, 72162, 80497, 88101, 89903, 93011, 94414, 98468, 106185, 107446, 544069], [11161, 12764, 12973, 13663, 17786, 24164, 25445, 26788, 29061, 32594, 33142, 33527, 35549, 37160, 37493, 38802, 39207, 40726, 41256, 45508, 46033, 46735, 47234, 48166, 48799, 49244, 49734, 50318, 50545, 51332, 55499, 56803, 58400, 59031, 60334, 61502, 63658, 65682, 67657, 68158, 68772, 68871, 70519, 72162, 77406, 85828, 86341, 86502, 88033, 101152, 104623, 107259, 139914, 526785, 545828], [13190, 13931, 18701, 23716, 24197, 26058, 26352, 28357, 28873, 29315, 29954, 29993, 31755, 32175, 32349, 33397, 35250, 35779, 35898, 38507, 38625, 38854, 38881, 44341, 45817, 48317, 50318, 50493, 51828, 52736, 54517, 58216, 58437, 58775, 58880, 59381, 60068, 63611, 64432, 64618, 65476, 66905, 67740, 68589, 68871, 72451, 73966, 75139, 75432, 81198, 86609, 98152, 98561, 102447, 103617], [10012, 10037, 10076, 10284, 11161, 12439, 12764, 18631, 21120, 23738, 25055, 29633, 31538, 32104, 32530, 33688, 37789, 38000, 38543, 39281, 39359, 40873, 41071, 43047, 43913, 45508, 46435, 47163, 48927, 49715, 49749, 50001, 51006, 51086, 51693, 52102, 52928, 53963, 54896, 55006, 58493, 59127, 67413, 68541, 70134, 70397, 72713, 72791, 75324, 77629, 78377, 82836, 89662, 97430, 100514], [11161, 11473, 21199, 23377, 23867, 24492, 27067, 28424, 29793, 30970, 31006, 31634, 33756, 33757, 36832, 37418, 37772, 39207, 41769, 42076, 42084, 42300, 42851, 43910, 44267, 44427, 44656, 45943, 46934, 46938, 46987, 47077, 47200, 47975, 50181, 51133, 51657, 54041, 54987, 55005, 55041, 55125, 57009, 60190, 62902, 66093, 68724, 69990, 70149, 72214, 72873, 75316, 77753, 85070, 550055], [15334, 15832, 15943, 22248, 23087, 23716, 24044, 28273, 29896, 30393, 30657, 30942, 31900, 33001, 33558, 34092, 34654, 35825, 42076, 42655, 42884, 43877, 43913, 43970, 45226, 46880, 48726, 50181, 53110, 53225, 53573, 54171, 56836, 57709, 57904, 58459, 59954, 61884, 62680, 63044, 67136, 70182, 71221, 71974, 71989, 73582, 74565, 76717, 80577, 85709, 86507, 98468, 111584, 139878, 544069], [11690, 11887, 14929, 15943, 20778, 21350, 22783, 23848, 24759, 25472, 27731, 30993, 35000, 36287, 37885, 38003, 38881, 39207, 41848, 43651, 43748, 44642, 45710, 46930, 47377, 48799, 52597, 52941, 54781, 55376, 55940, 57913, 58332, 59764, 60851, 63742, 64988, 65584, 66880, 67649, 68284, 69072, 74825, 75439, 78210, 83629, 87221, 88129, 89903, 91261, 95675, 98447, 98959, 104201, 111293], [11690, 14882, 15422, 17978, 22810, 25458, 25641, 26058, 26956, 27455, 30838, 33620, 34651, 36692, 40372, 40614, 42624, 43342, 45009, 46923, 47463, 48685, 48871, 51006, 52643, 52895, 52941, 53573, 54299, 54801, 55499, 55743, 56940, 57254, 58995, 60898, 61337, 61546, 62261, 63980, 64109, 64174, 71221, 73582, 74769, 78110, 82115, 83824, 85070, 85251, 88413, 93624, 99454, 107446, 125843], [10403, 13931, 20481, 20979, 25008, 25200, 25445, 25893, 26008, 29865, 30237, 30510, 33085, 34846, 36865, 37661, 39156, 41012, 42897, 44067, 44559, 46608, 47709, 49169, 51376, 51850, 52118, 53345, 53346, 53918, 53986, 54039, 54488, 54673, 57439, 59661, 59724, 60137, 60277, 60347, 61337, 62651, 63235, 63678, 64658, 65144, 65335, 72147, 73420, 75190, 78660, 78755, 81539, 109885, 518732], [14929, 15656, 15688, 17978, 21607, 23149, 25276, 25602, 26955, 28500, 30853, 31858, 32277, 33085, 36779, 40729, 40973, 41996, 42662, 42811, 43240, 43566, 46012, 46811, 48234, 50153, 51271, 52628, 53440, 54497, 54821, 55404, 58915, 59894, 61664, 63111, 64372, 64840, 66685, 67502, 68284, 68859, 69663, 70080, 70954, 71665, 72995, 84827, 91089, 91715, 94376, 97486, 99781, 114723, 549223], [10012, 13298, 13941, 18462, 22279, 24647, 25372, 25602, 26162, 27925, 28273, 28614, 28776, 29219, 29904, 30993, 31193, 31874, 32782, 33707, 36211, 38003, 41325, 42305, 42638, 42832, 43428, 43468, 44387, 47685, 48234, 48307, 50328, 52274, 53449, 56550, 58509, 58807, 59537, 59655, 59990, 60230, 60597, 61502, 62932, 64162, 65587, 66256, 68724, 69932, 71998, 78816, 84827, 84958, 85817], [10023, 12382, 15422, 19539, 20210, 20979, 24208, 26274, 26362, 27000, 27424, 28387, 29102, 29682, 31456, 34731, 35029, 36693, 39220, 41045, 41214, 41506, 41744, 42475, 42638, 44542, 45804, 46813, 48923, 49801, 51080, 51133, 51513, 53339, 53897, 54308, 54414, 55829, 58025, 58668, 59911, 62627, 65444, 65551, 69663, 71989, 74186, 74386, 77255, 82174, 97034, 101549, 112134, 150743, 511987], [10335, 11609, 11901, 17831, 19827, 24071, 25191, 26028, 26723, 28153, 28199, 28510, 29453, 29865, 30440, 33478, 37418, 38940, 39042, 43342, 43630, 43668, 44320, 44642, 47704, 48164, 50963, 51768, 51950, 55447, 56062, 56141, 56550, 57573, 57795, 57894, 59814, 61248, 65045, 65232, 65733, 67177, 67501, 70034, 70696, 71974, 76897, 80680, 81466, 82421, 88101, 91715, 112131, 112804, 171682], [12428, 15007, 15593, 24071, 25665, 25729, 26788, 27026, 27211, 29061, 31254, 31767, 34821, 35295, 36421, 36791, 37298, 39276, 41814, 42080, 42911, 45710, 46256, 49512, 49662, 51288, 51377, 51819, 52059, 52149, 53339, 54522, 54682, 54697, 55066, 56919, 57264, 57894, 59067, 59322, 59724, 60338, 62518, 67342, 69324, 70904, 75904, 77507, 78738, 79845, 86669, 100702, 107120, 141967, 543485], [10372, 12094, 19526, 22148, 22435, 22550, 30457, 30506, 30585, 31319, 34814, 35598, 37418, 37835, 41124, 41456, 44504, 44641, 45609, 46094, 46648, 47192, 48094, 48317, 49089, 49093, 49749, 50437, 51080, 51288, 51349, 51840, 52515, 54153, 56919, 57270, 61546, 61771, 63730, 64348, 64764, 66869, 70166, 72064, 73462, 74566, 77015, 80577, 82174, 84460, 84518, 93770, 106652, 110835, 150743], [10025, 15400, 19233, 23210, 25298, 25952, 27349, 28437, 29119, 31456, 33456, 33756, 34702, 35352, 36081, 36692, 38507, 38744, 39276, 40829, 42076, 42265, 44185, 45009, 46063, 46077, 48891, 49792, 50789, 50900, 52149, 53426, 53674, 54617, 55743, 55952, 56577, 59322, 59764, 61328, 61386, 62766, 63121, 67145, 67779, 71801, 72367, 73420, 73832, 73968, 74890, 77015, 84397, 94104, 544069], [11435, 15348, 15363, 18311, 21426, 21984, 22279, 24492, 24854, 25772, 26976, 29103, 29600, 31931, 32244, 32990, 33135, 33353, 36768, 36943, 37246, 38665, 39552, 40264, 40785, 42631, 42878, 42980, 43630, 43734, 43835, 45254, 45611, 48591, 52068, 52669, 53170, 53419, 57681, 58332, 58400, 59024, 61818, 63769, 64490, 66639, 66888, 67405, 69932, 70149, 74995, 83824, 111104, 117796, 542276], [12979, 13196, 13285, 15593, 16609, 18384, 18661, 19605, 19806, 21249, 21737, 23463, 24566, 26246, 29757, 33495, 33579, 34009, 34275, 35508, 35529, 37913, 38199, 38890, 39125, 40298, 40973, 41461, 41989, 41996, 42524, 43458, 43692, 46813, 48271, 51821, 52268, 53345, 53666, 54801, 56728, 58799, 58953, 60059, 60269, 60347, 60659, 63745, 64064, 67240, 75654, 94135, 98959, 100747, 112131], [10387, 12145, 12640, 14416, 14586, 22279, 26863, 26956, 27300, 29315, 30657, 31319, 32614, 34993, 35465, 36088, 37370, 41321, 42288, 42351, 42829, 42956, 44068, 44228, 45943, 48606, 49963, 51331, 52628, 54269, 55376, 56175, 57681, 59511, 60812, 62199, 62360, 64157, 65144, 65985, 66410, 66924, 67193, 68158, 68315, 70511, 71221, 72607, 74217, 78660, 80955, 98029, 98538, 101209, 107120], [10372, 11055, 11522, 17610, 17677, 18632, 20481, 20778, 20979, 24759, 25742, 30151, 30898, 31319, 31598, 32839, 34009, 35241, 35250, 36779, 37059, 39105, 39552, 42358, 44631, 44756, 45314, 46937, 46945, 49295, 49436, 50437, 50724, 51423, 52258, 52471, 53096, 54220, 54998, 55587, 55832, 55954, 59595, 60641, 63890, 64109, 66082, 66905, 69728, 72158, 77166, 82193, 84470, 85705, 89475]], "94": [[15334, 15737, 16469, 16996, 17786, 20700, 24162, 25569, 27579, 27726, 28390, 28504, 31391, 32118, 32180, 32391, 32782, 32917, 33797, 35529, 36017, 39097, 39105, 39174, 39551, 40263, 40829, 41241, 41409, 41970, 42096, 42149, 42153, 42288, 42508, 42851, 42956, 43970, 43985, 44033, 44068, 45943, 46146, 46945, 46956, 46963, 48333, 48685, 49911, 50001, 50545, 50643, 50719, 50900, 52059, 52736, 54364, 55238, 55312, 55326, 55491, 57439, 58402, 58403, 60019, 60082, 60413, 61208, 62441, 62870, 63452, 64764, 64851, 65240, 69172, 69990, 70682, 70696, 72107, 72759, 75861, 76174, 79568, 79629, 80253, 80621, 80835, 86375, 100179, 102028, 105333, 111584, 542952, 543332], [11579, 15586, 16512, 18462, 18635, 18943, 22550, 22672, 23738, 23830, 24034, 24545, 27300, 27755, 28357, 28551, 28776, 31116, 31319, 31456, 31471, 31742, 32336, 33381, 38625, 38940, 39356, 39540, 41196, 42084, 42103, 42475, 42878, 43035, 43417, 44299, 45241, 46233, 46811, 46844, 47599, 47975, 48857, 48866, 48907, 49212, 49963, 50001, 51842, 51847, 52319, 52621, 53440, 54488, 54540, 55442, 55958, 56268, 57041, 57557, 58459, 58880, 58886, 59730, 60146, 60490, 60567, 61818, 62932, 63087, 65476, 66072, 66942, 69533, 70397, 72107, 72367, 74890, 75841, 79475, 80527, 81198, 82103, 82562, 82743, 83480, 84592, 84827, 88321, 94747, 101209, 105333, 107259, 143239], [10235, 12328, 16606, 20874, 21782, 22510, 23128, 23271, 24044, 24272, 25088, 25369, 25729, 26058, 26132, 28208, 28424, 29092, 29619, 29865, 30384, 30719, 32749, 34398, 39058, 39317, 42358, 42406, 44239, 44267, 44600, 44641, 44987, 45034, 46718, 46854, 47238, 48203, 48317, 49904, 50473, 50974, 51769, 53443, 54182, 54335, 56180, 56279, 56576, 57467, 57672, 58063, 58689, 59131, 59222, 59511, 60463, 60680, 61664, 62651, 62685, 63286, 63745, 64382, 65232, 65682, 66269, 66368, 69463, 72791, 73893, 74505, 74565, 75502, 75654, 75967, 76432, 76576, 77521, 77711, 78210, 80621, 89366, 89751, 89989, 90593, 91436, 92410, 96404, 97586, 101044, 118070, 132767, 171682], [13076, 14754, 15688, 16570, 21734, 23128, 23848, 24132, 24810, 26159, 26268, 27726, 28422, 28424, 30876, 31184, 31250, 31471, 33332, 33712, 34993, 35098, 35451, 35618, 37485, 40682, 41348, 41469, 41996, 42655, 42737, 42971, 43342, 43518, 43913, 46046, 46146, 46608, 46646, 46648, 46937, 48221, 48297, 48317, 48901, 49795, 49809, 50164, 50789, 51850, 52319, 52604, 52929, 53225, 54150, 54668, 54692, 56826, 58004, 58332, 58943, 59131, 59563, 59811, 62458, 62518, 62685, 62766, 63135, 63155, 64382, 64432, 64772, 65503, 68378, 68445, 68871, 69159, 70229, 70549, 75139, 79568, 80432, 84051, 88596, 94185, 94448, 107064, 108070, 114723, 150743, 155098, 533367, 546795], [10012, 10076, 11077, 16474, 20210, 20481, 20700, 22248, 23062, 23421, 23761, 24309, 24592, 24951, 25569, 25617, 25961, 26243, 27168, 28541, 28944, 30142, 30600, 30719, 30941, 31634, 32508, 33429, 34416, 34600, 34756, 34858, 37059, 37766, 37767, 37913, 39462, 40729, 40805, 40810, 40948, 42884, 43342, 43534, 43668, 44547, 44987, 46985, 47453, 48208, 48229, 48429, 48889, 48951, 49792, 50001, 50971, 51828, 53422, 53493, 54299, 55208, 56392, 56626, 56638, 59118, 59576, 60142, 60160, 61544, 62766, 62804, 63961, 64348, 64372, 64840, 66880, 66942, 67284, 67637, 69741, 70166, 72064, 72268, 73832, 74452, 75145, 75492, 79075, 86507, 102447, 108285, 112388, 112757], [11117, 11696, 12202, 12440, 17123, 17226, 18420, 18507, 20175, 23317, 23413, 24197, 24464, 25806, 26078, 28243, 28877, 29103, 29219, 29853, 29896, 30585, 31878, 31931, 32118, 33157, 33161, 33650, 33707, 34859, 35587, 35891, 36107, 36693, 37870, 38246, 38557, 39359, 39513, 40785, 41881, 42980, 43254, 44267, 44387, 44547, 44956, 46646, 47482, 47872, 48059, 49050, 49503, 51166, 52311, 52471, 52628, 53422, 53929, 54103, 54152, 54821, 55128, 55176, 55671, 55735, 56277, 58063, 59393, 60088, 61853, 62458, 62518, 64435, 65587, 66587, 67240, 67720, 68534, 69427, 73269, 75743, 80560, 82193, 83102, 84104, 85823, 93624, 98561, 103043, 111584, 118684, 122013, 128140], [10231, 11551, 13941, 16390, 17226, 23719, 23781, 23936, 26379, 26560, 26827, 28599, 29049, 29386, 29402, 29757, 31254, 31512, 31673, 31874, 32175, 33539, 34289, 35029, 35974, 37216, 38199, 38269, 39803, 39808, 42622, 42884, 43301, 43656, 43769, 44638, 46012, 46146, 46292, 46854, 46874, 46992, 47192, 47688, 47714, 48799, 49773, 49792, 49918, 50336, 51950, 52268, 52956, 53422, 54253, 55565, 57230, 57987, 58402, 58632, 58775, 59486, 59497, 59663, 60641, 61337, 61617, 61884, 62209, 62787, 63135, 63980, 65084, 68724, 70462, 71867, 72995, 73667, 74205, 82115, 82421, 83653, 84592, 89366, 92197, 94747, 97729, 106967, 113693, 115355, 129919, 171682, 540405, 546795], [10016, 10403, 15771, 18605, 19806, 22670, 23134, 23664, 23848, 24647, 25423, 26560, 27424, 28199, 28204, 28219, 28403, 29406, 30732, 31900, 31931, 32820, 33240, 34654, 35029, 36804, 37182, 37418, 38862, 39840, 40155, 40613, 41209, 43534, 46004, 47032, 47463, 48394, 49962, 50164, 50473, 50604, 51180, 51237, 51392, 51845, 52311, 52604, 52741, 54975, 55489, 55981, 56139, 56194, 56220, 57347, 58216, 58858, 59024, 59381, 60217, 61148, 61242, 61743, 61780, 62257, 62360, 63111, 63135, 63351, 63745, 64065, 64988, 65084, 66880, 68282, 70134, 74264, 82048, 82421, 85817, 89925, 94798, 96680, 102944, 103617, 107259, 112918, 113042, 122608, 172286, 176056, 542891, 543332], [12973, 12979, 13326, 18420, 20176, 21448, 22248, 24483, 24784, 25742, 26162, 26955, 27168, 28199, 29112, 29682, 30657, 30965, 31036, 31184, 31193, 34456, 35780, 35981, 36791, 37411, 38082, 38625, 38940, 39125, 39281, 39462, 39808, 40800, 42032, 42076, 42355, 42754, 42980, 43877, 44185, 44559, 46813, 47725, 49278, 49911, 49992, 50181, 50971, 51293, 53630, 55472, 55601, 56283, 56576, 56968, 58267, 58303, 58695, 58807, 58886, 59175, 59537, 60190, 60673, 62835, 63301, 63802, 63956, 64505, 64988, 66521, 66880, 69272, 69404, 70548, 73163, 74217, 77942, 78273, 81198, 81319, 81466, 82421, 84392, 85709, 85975, 88033, 88101, 91261, 101121, 104201, 104623, 110835], [11293, 13874, 17945, 19202, 20634, 21632, 22070, 22189, 22944, 25641, 26162, 27165, 27189, 28862, 29893, 31456, 31514, 31598, 31623, 32106, 32118, 32180, 32341, 33001, 33074, 38572, 38744, 39190, 39317, 39422, 41930, 41970, 42624, 43463, 43579, 43734, 44267, 44320, 45228, 46256, 46414, 46646, 46811, 46841, 48143, 48907, 49795, 49918, 50050, 50545, 51105, 51182, 51293, 51757, 52519, 52669, 52741, 52891, 52929, 53449, 53794, 54497, 54741, 55087, 55743, 56618, 56892, 57264, 61148, 61208, 61303, 62101, 64571, 66521, 67003, 70262, 70904, 71973, 72162, 73379, 73667, 78645, 80597, 82193, 83629, 84051, 87585, 89255, 97586, 102944, 112077, 112134, 113476, 146570], [12254, 12957, 16468, 18227, 18605, 18661, 21065, 21186, 21648, 22435, 23087, 23677, 23716, 24405, 24947, 25167, 25458, 25961, 26349, 26362, 27461, 27913, 29899, 30580, 30585, 30853, 32305, 32420, 33161, 33186, 33707, 34237, 35455, 35480, 35689, 35873, 35975, 37267, 37870, 38039, 38940, 39125, 39137, 39434, 39481, 39544, 39808, 42330, 42359, 43534, 44979, 46028, 46256, 46408, 46850, 46987, 47504, 48230, 48606, 48679, 49055, 49244, 49381, 50627, 54929, 55639, 57580, 59028, 59459, 59563, 59879, 63036, 63665, 64648, 64745, 66656, 68378, 69172, 70166, 70256, 70519, 71017, 71199, 72162, 73269, 74565, 77214, 80722, 93178, 95075, 99480, 112131, 116021, 130514], [10439, 10766, 11690, 11773, 11926, 13326, 14300, 16373, 16469, 18079, 18942, 21350, 22754, 24283, 29793, 30204, 30457, 30566, 31728, 31858, 32118, 33353, 33650, 34043, 34666, 34783, 35086, 35242, 35348, 36017, 36804, 36805, 36862, 38246, 38913, 39190, 40884, 42631, 42897, 43769, 44033, 44600, 45306, 46219, 46796, 46930, 47709, 48333, 48480, 48605, 48645, 49423, 50297, 51278, 51791, 52604, 54182, 54975, 55194, 57393, 57679, 58621, 58807, 59954, 61124, 61142, 61627, 62634, 62932, 63135, 63315, 63959, 64064, 64065, 66155, 67240, 68559, 69159, 72139, 74452, 79462, 80253, 80504, 80955, 86184, 87221, 92163, 92216, 96453, 98447, 100901, 146570, 171682, 537004], [13285, 15870, 19529, 22997, 24464, 25276, 25711, 26078, 26379, 26560, 26825, 27142, 28065, 28207, 28424, 28500, 28776, 29453, 30388, 30993, 35598, 36693, 36791, 37870, 37926, 39544, 39614, 40613, 42516, 42524, 43240, 44068, 44228, 44716, 45394, 46046, 46145, 46742, 46937, 47239, 47963, 48230, 48737, 49206, 50130, 50592, 51271, 51842, 52928, 53894, 54157, 55312, 55483, 55601, 56180, 56392, 57230, 57299, 58092, 58216, 58671, 60413, 61796, 62199, 63200, 65793, 67413, 67649, 68772, 68778, 69048, 69990, 70462, 71150, 71493, 73073, 73243, 74452, 74845, 75184, 77521, 79754, 83215, 88413, 89751, 94414, 94798, 95082, 95834, 95896, 98561, 106967, 116021, 132767], [11435, 14499, 15021, 19160, 21734, 22279, 22307, 23503, 24954, 25862, 27616, 27705, 27731, 28387, 28476, 29382, 29954, 29959, 30965, 31162, 31540, 32277, 32754, 32782, 32828, 32839, 33728, 33797, 34844, 35250, 35860, 36107, 37246, 37871, 39190, 39574, 43518, 46033, 46267, 46443, 46659, 47725, 50318, 51058, 51717, 52585, 52604, 54267, 54517, 54606, 54748, 54786, 55885, 57105, 58459, 58482, 58859, 59443, 59814, 59844, 60828, 61242, 62634, 63111, 63745, 64423, 64490, 64758, 65985, 66269, 66521, 67340, 68284, 69253, 70134, 72384, 72616, 74505, 77473, 79409, 79754, 80432, 80546, 83228, 84051, 94937, 97729, 103726, 104440, 107064, 110911, 112918, 122013, 124317], [10076, 10250, 17945, 17985, 22402, 22428, 23757, 24044, 24066, 24283, 25339, 28401, 29112, 29249, 29993, 30440, 30965, 31332, 33865, 34266, 34289, 34783, 34839, 35508, 35907, 35938, 37182, 37298, 38217, 38324, 39073, 39105, 40155, 41325, 41930, 43491, 44067, 44086, 44504, 44930, 45804, 46842, 46934, 47118, 47482, 47677, 48142, 48591, 48737, 48923, 48927, 49094, 49359, 49809, 49904, 49918, 50243, 50875, 51349, 51377, 53244, 53493, 54000, 54335, 54476, 56141, 56700, 57393, 58402, 58409, 59127, 59663, 59764, 60334, 60851, 61789, 62257, 63802, 64331, 66798, 70408, 70425, 72064, 72406, 74128, 75399, 76432, 76947, 77507, 90593, 99821, 101152, 114291, 511987], [11435, 11579, 12236, 12416, 18942, 23210, 23936, 24283, 25088, 26274, 26599, 26788, 26976, 26991, 27322, 27709, 27882, 28387, 29359, 30247, 30898, 31116, 31677, 32106, 33885, 34081, 34266, 34662, 34838, 35549, 36464, 37103, 38980, 39297, 39483, 41528, 41663, 41867, 42069, 42662, 43668, 44299, 45083, 46854, 47390, 47400, 47900, 48321, 49206, 50789, 51239, 51343, 53001, 53346, 53894, 54730, 55087, 56279, 56909, 58459, 58864, 58880, 58900, 59059, 59511, 60659, 60889, 61793, 62441, 62627, 63648, 63802, 64644, 64676, 65900, 67193, 67413, 69493, 70511, 70519, 70738, 71017, 72107, 76039, 76326, 77942, 84518, 94135, 98152, 101209, 107120, 115744, 128586, 154125], [10206, 10766, 11769, 12764, 14416, 17302, 17515, 18579, 18661, 18970, 21983, 23686, 25008, 25423, 25733, 25952, 26362, 26899, 27334, 28382, 29600, 30838, 30941, 30970, 31036, 33094, 33222, 34702, 35029, 35348, 36539, 37245, 38810, 39427, 39606, 40036, 40155, 40800, 41512, 41775, 41814, 42754, 44927, 45145, 46012, 46584, 47738, 48271, 48429, 49295, 49346, 49715, 49832, 51769, 52319, 53170, 54038, 54199, 54267, 55954, 56161, 56265, 56585, 57009, 59576, 59829, 59940, 60079, 61212, 61546, 61771, 62199, 62261, 63785, 64162, 66685, 66705, 67402, 67729, 71017, 71867, 75324, 78558, 78645, 80590, 86502, 88101, 89469, 92197, 100493, 104132, 115394, 124425, 511987], [10723, 14300, 14929, 16474, 16570, 19202, 22750, 23128, 23317, 24034, 24035, 24545, 24769, 26598, 27300, 27349, 27579, 29553, 30142, 31894, 32790, 32990, 33520, 33620, 34009, 34175, 35240, 35766, 37847, 38360, 39105, 39137, 39624, 40477, 40726, 41263, 41312, 41970, 42265, 42963, 42980, 43979, 45209, 45494, 45714, 45774, 46288, 49206, 49346, 51847, 52621, 53365, 54182, 54801, 54975, 56194, 56265, 56728, 56772, 57742, 57822, 59814, 59894, 60113, 60641, 61148, 61884, 63351, 63678, 64758, 65240, 65451, 66647, 69404, 70790, 75492, 75999, 78210, 79754, 81459, 82581, 82695, 83653, 88189, 89469, 90507, 91436, 97188, 98468, 105155, 107144, 122013, 128140, 550411], [10206, 11887, 12236, 15771, 16153, 16461, 21632, 24027, 24647, 25446, 25661, 26207, 26379, 27175, 27424, 28206, 28500, 28614, 28868, 30719, 30970, 32349, 32990, 33397, 33456, 33620, 34121, 34600, 34639, 34859, 34986, 35709, 35898, 36075, 36555, 37160, 38021, 38861, 40287, 41744, 41839, 42305, 42903, 43769, 44427, 44454, 44756, 44979, 45609, 46256, 46644, 46651, 46937, 47032, 48333, 48341, 48866, 48896, 49212, 49244, 50724, 50890, 52377, 52604, 52863, 53098, 54279, 54335, 54804, 55800, 58333, 59345, 60786, 62596, 65240, 65767, 66630, 67342, 67779, 67866, 69617, 73080, 77177, 81408, 82348, 82581, 82743, 83500, 95631, 98959, 106223, 107120, 108618, 112804], [10206, 11169, 14179, 15870, 16366, 20210, 20700, 20801, 20979, 21164, 25010, 26825, 28420, 28476, 29303, 29596, 30017, 31261, 32167, 33048, 33085, 33235, 34416, 34931, 35508, 35779, 36469, 38082, 39520, 39642, 40613, 40672, 40805, 43154, 43333, 44783, 45075, 46063, 46292, 47183, 47377, 48429, 48960, 49449, 50405, 50724, 50741, 51278, 52386, 52553, 52741, 53131, 53286, 53986, 54457, 54730, 55691, 56059, 56220, 58582, 58775, 58908, 59046, 59819, 59911, 61468, 61502, 61741, 62849, 63890, 63956, 64648, 66129, 67367, 68541, 69463, 70462, 71124, 71989, 73667, 73832, 75999, 81172, 85850, 87523, 88591, 89797, 90306, 90593, 93090, 94262, 96141, 98191, 516882]], "115": [[10025, 10372, 11435, 11696, 14233, 18746, 18970, 21234, 23087, 23115, 24071, 25276, 25369, 26028, 26075, 26262, 27435, 28375, 29358, 31514, 31607, 32257, 32334, 32614, 33332, 33397, 33707, 33712, 33796, 34228, 34289, 34450, 34582, 34662, 34694, 34993, 36164, 36469, 37245, 38862, 39297, 39664, 40672, 41996, 42147, 42150, 43333, 44800, 45027, 45444, 45776, 45897, 47077, 47400, 47532, 48234, 48363, 49809, 50994, 51693, 51922, 52194, 52648, 53666, 54123, 54253, 54421, 54540, 54673, 54778, 55436, 56062, 56577, 56919, 58025, 58228, 58267, 58680, 59862, 60068, 60269, 60680, 63730, 63961, 66072, 67658, 67740, 70084, 70397, 70549, 71221, 71527, 71913, 71989, 72213, 73038, 73379, 75190, 77214, 80432, 82923, 83483, 84710, 85070, 85251, 86123, 86681, 87976, 92216, 99781, 100368, 102925, 103726, 111750, 115098], [11690, 14882, 15363, 18420, 19887, 20874, 21295, 22754, 24909, 26037, 26059, 27131, 27709, 28510, 29308, 29315, 30134, 30485, 30657, 31193, 31767, 31894, 31976, 32104, 33756, 34931, 35284, 35317, 35321, 35508, 35559, 35595, 35766, 35876, 36211, 37103, 37958, 38458, 38940, 40597, 41099, 41214, 42956, 43333, 43548, 44927, 46219, 46850, 47309, 47714, 48409, 48566, 48871, 50900, 50902, 51288, 51331, 51967, 52588, 53980, 54308, 54786, 55081, 56277, 56379, 56591, 57270, 57348, 58025, 58632, 58807, 59046, 59175, 59345, 59511, 59537, 60659, 60719, 62693, 62870, 63036, 64618, 65584, 65978, 66082, 66639, 67240, 67413, 69493, 69617, 74040, 74816, 75527, 75743, 75904, 77538, 78377, 79080, 80967, 81172, 81580, 83500, 86669, 94413, 94747, 95075, 103331, 108070, 113128, 115744, 122742, 122923, 172286, 518732, 555651], [16366, 18282, 20175, 21249, 22211, 22428, 22886, 23716, 24211, 24759, 25873, 25952, 26075, 27579, 27705, 28243, 28273, 28422, 28500, 28877, 29219, 29315, 29793, 29959, 30838, 30942, 32614, 33456, 34502, 34731, 34859, 34877, 34883, 34990, 36405, 36469, 37493, 37766, 40150, 41240, 41409, 42041, 42076, 42638, 43035, 43877, 44281, 44299, 44360, 44871, 44987, 45158, 45710, 46063, 46727, 46813, 46844, 46956, 48606, 49326, 49593, 49809, 50181, 50466, 50686, 51105, 51332, 51840, 53345, 53419, 53611, 53692, 54157, 54292, 54673, 55128, 55238, 55266, 55436, 56141, 56220, 56226, 57987, 58493, 58671, 59322, 59563, 59764, 60889, 61386, 62542, 63121, 65028, 68663, 70134, 70901, 72616, 72772, 72873, 74063, 74264, 74477, 75145, 77074, 78043, 80008, 81459, 83500, 85850, 93011, 95631, 99821, 106967, 113128, 511987], [10381, 11346, 15074, 17336, 18227, 18942, 20618, 23734, 23936, 24309, 24483, 25400, 25670, 26008, 26825, 26827, 27731, 28422, 28476, 28654, 29125, 29896, 30204, 30506, 30695, 31118, 31598, 31931, 32106, 32828, 32929, 33397, 33478, 33728, 33793, 34228, 35250, 35981, 36150, 37766, 39263, 39276, 39540, 39851, 40500, 40983, 43877, 44542, 44598, 45804, 46046, 46850, 46854, 48685, 48810, 49093, 49292, 49664, 49764, 49789, 50974, 52258, 52580, 53085, 53440, 53918, 54123, 56194, 57009, 57964, 59171, 59175, 59269, 59894, 60428, 60782, 61617, 62257, 62261, 63015, 63184, 63315, 63678, 65247, 65793, 66292, 66869, 67612, 67662, 70080, 70562, 70904, 71527, 71989, 72158, 72607, 74477, 74689, 75527, 77942, 78716, 80955, 82103, 86669, 88413, 90110, 91239, 93624, 95359, 99821, 101152, 103043, 109404, 127011, 155098], [10121, 10915, 12328, 13174, 15007, 16461, 17123, 19645, 20778, 21249, 24691, 26811, 27000, 27533, 28100, 28256, 29036, 29660, 30580, 32749, 32946, 33074, 33139, 33480, 33527, 33695, 33712, 34123, 34542, 34821, 34838, 35284, 36779, 37926, 38890, 40613, 41222, 41996, 42624, 42918, 43518, 43579, 44709, 44849, 45115, 45241, 45300, 45306, 45508, 46004, 46014, 46292, 46796, 46842, 46855, 46956, 47090, 47738, 49163, 49292, 50396, 50592, 51915, 52149, 52197, 52774, 52895, 53286, 53345, 56194, 56265, 56836, 57136, 57254, 58451, 58799, 58819, 59131, 59297, 59802, 60059, 60371, 61212, 61818, 64676, 66013, 66587, 67628, 69345, 70682, 71150, 71527, 72376, 73379, 74689, 76326, 77507, 78110, 80590, 85707, 86314, 88268, 89375, 91762, 93178, 98152, 99740, 101055, 102174, 104132, 110911, 124425, 138940, 529228, 593158], [10121, 13196, 14416, 17985, 18462, 18631, 19202, 19623, 21483, 21832, 22181, 22279, 24066, 25952, 26028, 26334, 27427, 27544, 27731, 28375, 28605, 28960, 29049, 29893, 30017, 30510, 31607, 32281, 32420, 34671, 34726, 34814, 34858, 35317, 35348, 35455, 36832, 36903, 37290, 37671, 38881, 40183, 40805, 40948, 41769, 42851, 42936, 43518, 44086, 45508, 45755, 45774, 45817, 46034, 46063, 46077, 46267, 46648, 46946, 47738, 47963, 47975, 48755, 49734, 50164, 50627, 51180, 51847, 52597, 54041, 54801, 54868, 55266, 56194, 57517, 58012, 58419, 59067, 59118, 59131, 59322, 59393, 59576, 60113, 60490, 60597, 60641, 63200, 65084, 66905, 66924, 67240, 67402, 67958, 69617, 70256, 71801, 77255, 79251, 80560, 80740, 82870, 86507, 89797, 89925, 94448, 95631, 96680, 101044, 101082, 104132, 107144, 112077, 112757, 112804], [11551, 12640, 16512, 17302, 21238, 21448, 21737, 22750, 23757, 24854, 24951, 25423, 25569, 26132, 26955, 27000, 27932, 28420, 29092, 29538, 29865, 29942, 31162, 31842, 31894, 32635, 33336, 33707, 33760, 33979, 34277, 34481, 34774, 34834, 35791, 36081, 36805, 37216, 37418, 37871, 38082, 38681, 38862, 40500, 40614, 40772, 41214, 41325, 41814, 41930, 42032, 42041, 42360, 42525, 42655, 44559, 44600, 46718, 47032, 47037, 47109, 47326, 48142, 49171, 49221, 49395, 49734, 49955, 49988, 50299, 50328, 50405, 50875, 50926, 51349, 53918, 54252, 54292, 55735, 55856, 56638, 56838, 57060, 57573, 58333, 59471, 59819, 59829, 63162, 64490, 64644, 66292, 67706, 68284, 68559, 68696, 70532, 71913, 72269, 73243, 74769, 74989, 75904, 78377, 78613, 79462, 81466, 82695, 90321, 93520, 94262, 94414, 99981, 106223, 117796], [10121, 11551, 14179, 15062, 15870, 18631, 18895, 23317, 24482, 24734, 25055, 25388, 26167, 26560, 27334, 28191, 28260, 29172, 29209, 29308, 29954, 30942, 31040, 31116, 31184, 31526, 31793, 32104, 32256, 32661, 34651, 34877, 35559, 36397, 36539, 37525, 37721, 37766, 37835, 38665, 38691, 39434, 39667, 40873, 40973, 42017, 42475, 42849, 42980, 43534, 43569, 43910, 44656, 45609, 45710, 46233, 46874, 46923, 47183, 48271, 48384, 49593, 50493, 51166, 51180, 52850, 52891, 53734, 53797, 54638, 54786, 55634, 56827, 57557, 57672, 57850, 59940, 60082, 60084, 60160, 60889, 61286, 61627, 61741, 64157, 64432, 64658, 65088, 67136, 67372, 68445, 68589, 69404, 70397, 70883, 74128, 74271, 74769, 75502, 77538, 77681, 80590, 80680, 82695, 83629, 84392, 85268, 90507, 94747, 95082, 95675, 100493, 111122, 132767, 518732], [10266, 11435, 13663, 14499, 15688, 20700, 22279, 24034, 24951, 25167, 25445, 26124, 26268, 26274, 26379, 26599, 26866, 27334, 27726, 28035, 28153, 29103, 31118, 31456, 32749, 32828, 33796, 33797, 34029, 35458, 35746, 36150, 36693, 36805, 37050, 37926, 38017, 38039, 38802, 38881, 38899, 39840, 40477, 41012, 41411, 41814, 42076, 42150, 43491, 44122, 44927, 45670, 45956, 46443, 48679, 49258, 49326, 49381, 49740, 49773, 49904, 50297, 50545, 51067, 51681, 52314, 52377, 52628, 53422, 53426, 54269, 54517, 55066, 55125, 55573, 55735, 55954, 56892, 59280, 59322, 59542, 60088, 60428, 60567, 60680, 61155, 61386, 61743, 61780, 63235, 64906, 65335, 65682, 68331, 68488, 68541, 70462, 72607, 72616, 74040, 76339, 78716, 79075, 80621, 86502, 87379, 90593, 94104, 94376, 95082, 107064, 112757, 122608, 141967, 555651], [11346, 12640, 12973, 13663, 14499, 14586, 16468, 16819, 21234, 22211, 25339, 25806, 26246, 26274, 26723, 26788, 26811, 26944, 27334, 29303, 29596, 30142, 30299, 30440, 30510, 30585, 30970, 31254, 31677, 31752, 31767, 33222, 33666, 34654, 35181, 35432, 35451, 35454, 35689, 36795, 36872, 38729, 39105, 39664, 39795, 40500, 40829, 41272, 41461, 41469, 41930, 42069, 42103, 42359, 42737, 42911, 43734, 44086, 44304, 44559, 44642, 46033, 46841, 49055, 49423, 49449, 49614, 50437, 52515, 52580, 54153, 54299, 54730, 56052, 56836, 57681, 57753, 57904, 58228, 59045, 59655, 60211, 60786, 61212, 61242, 63956, 65064, 65444, 66256, 67658, 69172, 70831, 71324, 71878, 72873, 73243, 73269, 73741, 74649, 75184, 75345, 77473, 79376, 79462, 85251, 85975, 86681, 89989, 90720, 96404, 99821, 100402, 109885, 110754, 122742], [10012, 12740, 13881, 16512, 18227, 19050, 19599, 21448, 21734, 21737, 22505, 22989, 23171, 24071, 24211, 25641, 26124, 26808, 27006, 27291, 28208, 29119, 30247, 30601, 30694, 30714, 31202, 31456, 33336, 33796, 34416, 35098, 35148, 35295, 35598, 36986, 37160, 37830, 38164, 38862, 39750, 40628, 41397, 42911, 43671, 44454, 44504, 44642, 44716, 45003, 45209, 45306, 46012, 46034, 46735, 47878, 47900, 48384, 48761, 51674, 52515, 52648, 52929, 53150, 53311, 54150, 54277, 54812, 55312, 55386, 55639, 55981, 56226, 56379, 56826, 57041, 57060, 57136, 57517, 58092, 58216, 58548, 59046, 61242, 62227, 62257, 62902, 62932, 63611, 63802, 64162, 64236, 64618, 65247, 66647, 66656, 67742, 69551, 70519, 70790, 72651, 74802, 77406, 79883, 82539, 83088, 85251, 85254, 88591, 89375, 105476, 107583, 518732, 542952, 545828], [10121, 16367, 17786, 18809, 19599, 19887, 20303, 21984, 22750, 23317, 23848, 23890, 24164, 24482, 26373, 26714, 27449, 27579, 27884, 27925, 28329, 28497, 28836, 29518, 30098, 30714, 32082, 33353, 33539, 33707, 33793, 34266, 34433, 34694, 34783, 34993, 35455, 35559, 35746, 36847, 36872, 37182, 39513, 40263, 41208, 41241, 41300, 42566, 42624, 42829, 43311, 43342, 46855, 46945, 47183, 47239, 47714, 47870, 48297, 50318, 50415, 51687, 52197, 52580, 52626, 53244, 53443, 54730, 55201, 55208, 55436, 55735, 56220, 56667, 57009, 57232, 57439, 57846, 57964, 58680, 58943, 60463, 61212, 63351, 63730, 66292, 66905, 68805, 69663, 70256, 70262, 70904, 71324, 73582, 73680, 73966, 76897, 78716, 79260, 79462, 80590, 83088, 89989, 90987, 91158, 93460, 95075, 95834, 101152, 112077, 113693, 116079, 124081, 126713, 146570], [11551, 11769, 12640, 14179, 14882, 15007, 15363, 19645, 20700, 21065, 21238, 21570, 23471, 23729, 24283, 24951, 25446, 26162, 26808, 27334, 27544, 27709, 27731, 28422, 28424, 29382, 29518, 30585, 30838, 31319, 32820, 33026, 33620, 33752, 33760, 35432, 35772, 38164, 39520, 39544, 40036, 42029, 42103, 42351, 42706, 42865, 42903, 43333, 43651, 43692, 43766, 44122, 44136, 44284, 45902, 46718, 46850, 46855, 47038, 47238, 47390, 47677, 47875, 48576, 48923, 49499, 49740, 51632, 51840, 51922, 51950, 52850, 54039, 54235, 54812, 56161, 57009, 57679, 57794, 59738, 60217, 60696, 61303, 61337, 61386, 61780, 61796, 61948, 63111, 63745, 64851, 65088, 65845, 66129, 68243, 68331, 70291, 70425, 71221, 73037, 73893, 78110, 79754, 80835, 83102, 86184, 86798, 87327, 93090, 105155, 109704, 122013, 513435, 533367, 533520], [11926, 12440, 12521, 13881, 15908, 17605, 18579, 22189, 22648, 22944, 24211, 24283, 24405, 24784, 25202, 25445, 25458, 26574, 26863, 27682, 28204, 28207, 28437, 28836, 29186, 29335, 30134, 30566, 31193, 32257, 32400, 32990, 33161, 33294, 34092, 35975, 36405, 37267, 37290, 37830, 38021, 38269, 39042, 39614, 39803, 40597, 41905, 41970, 42041, 42406, 42818, 42980, 43734, 44639, 44656, 44666, 45228, 46004, 46414, 46718, 46844, 46942, 47872, 48317, 48363, 48685, 48866, 48923, 49036, 49436, 49738, 50724, 50840, 51006, 51086, 51392, 52258, 52319, 52928, 53897, 53965, 54038, 54804, 58121, 58689, 59546, 59954, 61544, 64505, 65232, 65389, 66358, 66685, 66888, 68213, 68282, 68315, 69533, 70901, 72929, 74186, 74565, 74890, 77711, 78660, 78816, 80621, 83226, 86502, 87976, 99740, 108285, 112757, 115098, 536307], [10693, 12957, 14499, 15348, 20634, 25008, 25372, 25490, 25641, 25665, 25704, 25733, 25873, 26008, 26154, 26944, 27168, 27175, 27189, 27461, 28065, 28243, 28476, 29942, 29959, 30142, 30751, 30890, 31677, 31874, 32180, 32585, 33381, 33478, 33527, 33760, 34204, 34694, 34708, 34733, 35876, 38576, 40500, 40672, 41172, 41397, 41461, 41775, 42300, 42990, 45209, 45278, 45329, 45649, 47037, 48059, 48394, 49034, 49050, 49359, 50963, 51202, 51239, 51791, 53367, 53816, 53965, 54199, 54414, 54781, 55081, 55386, 55634, 55639, 56277, 56913, 57393, 58188, 58333, 58621, 59576, 59724, 59777, 60334, 60336, 61337, 63611, 64423, 64840, 65800, 66368, 67866, 68442, 69272, 69342, 70134, 70954, 72064, 72147, 72376, 73420, 75432, 75753, 79050, 80834, 82048, 83085, 86184, 87733, 95631, 98468, 107259, 141967, 169810, 543485], [10771, 12416, 12973, 12979, 15363, 18579, 20176, 21565, 23890, 24566, 25339, 27396, 27544, 27884, 28500, 28954, 29538, 29942, 29959, 31116, 31457, 33492, 33809, 34694, 34726, 35907, 36373, 37525, 37835, 38507, 38881, 39042, 39174, 39289, 40613, 40973, 41256, 41848, 41905, 42305, 42732, 42737, 43184, 43254, 43296, 43630, 44304, 44430, 45003, 45120, 46811, 47061, 47187, 47390, 47798, 48221, 48566, 48863, 48951, 49381, 49497, 49512, 49732, 51022, 51278, 52268, 52580, 52880, 53419, 53734, 53894, 54267, 54877, 54896, 55041, 55087, 55129, 55829, 56483, 56728, 57136, 57439, 57467, 57514, 57913, 58864, 59345, 60638, 61286, 62523, 62849, 62938, 63301, 64157, 66412, 66646, 66869, 68315, 68630, 68871, 69253, 70007, 70738, 72759, 72995, 74404, 75139, 76339, 76855, 77473, 81150, 82165, 88413, 88820, 104440], [10231, 10693, 12145, 12416, 13326, 13532, 19529, 22505, 24027, 24469, 24954, 25372, 26111, 27027, 28357, 29358, 29669, 29744, 29865, 31006, 31040, 32118, 32640, 33979, 34081, 34731, 35451, 36088, 36857, 37321, 37411, 37493, 39042, 40287, 40298, 40805, 41321, 42903, 42990, 43518, 44800, 44950, 45145, 45278, 45394, 45817, 46014, 46292, 46435, 46443, 47652, 47778, 48726, 48960, 49169, 49395, 49503, 49732, 49832, 49878, 50493, 51288, 51768, 51821, 52110, 52311, 52498, 52783, 53422, 54668, 54801, 56379, 57270, 57881, 59393, 60889, 61328, 62199, 62458, 62787, 64505, 64644, 66036, 67628, 67720, 68213, 68243, 68693, 68724, 69741, 70084, 70347, 70536, 71759, 74250, 77753, 79075, 80597, 80680, 80722, 83242, 83653, 85823, 88101, 91436, 92584, 93460, 93770, 97430, 100702, 103331, 104201, 107144, 117796, 511987], [10025, 10335, 15400, 16461, 17610, 17978, 18635, 21199, 21249, 21565, 22997, 23503, 24309, 24469, 25372, 25952, 26207, 26334, 26373, 26944, 30965, 30970, 31040, 31116, 32021, 33074, 33527, 34237, 34289, 34566, 34839, 35086, 35456, 36612, 37050, 38729, 38810, 39481, 40021, 41117, 41272, 42355, 42730, 42865, 42956, 43211, 43790, 44122, 44299, 44800, 45003, 45027, 45120, 45956, 47041, 48864, 51086, 51825, 51997, 52783, 53894, 54150, 54804, 55005, 55081, 56012, 56068, 56772, 56824, 58004, 58092, 58178, 58509, 58895, 58974, 59025, 59084, 59197, 59879, 59894, 60137, 61337, 61789, 62257, 64162, 64658, 65476, 65985, 66080, 67177, 67402, 70549, 70593, 71124, 71527, 71867, 72616, 74593, 77942, 78160, 79845, 80560, 84392, 85251, 85503, 85709, 88321, 91261, 99560, 101121, 104132, 106185, 118684, 171682, 593158], [10381, 11901, 12094, 13547, 14499, 17985, 18507, 20778, 21164, 22510, 23781, 23890, 24197, 24464, 25661, 25733, 27027, 28823, 28954, 28956, 32299, 32833, 34502, 35241, 36297, 36768, 36795, 37772, 37881, 38245, 39552, 40682, 40729, 40766, 40873, 41409, 42017, 42069, 42150, 42662, 42818, 42829, 44148, 44267, 44871, 45034, 45116, 45949, 46956, 47394, 47975, 48645, 48889, 48901, 49087, 49423, 49499, 49749, 49765, 50789, 51067, 51135, 51423, 52843, 52941, 52956, 53897, 54153, 54199, 54617, 55596, 56052, 56546, 56576, 57980, 58815, 59142, 60079, 60807, 60828, 61410, 61743, 62227, 62529, 62596, 62946, 64109, 64764, 65033, 65450, 67958, 68282, 70080, 70347, 70730, 71324, 72995, 73038, 74063, 74505, 78210, 80835, 82165, 83824, 85823, 85828, 89751, 89925, 91762, 105476, 129919, 533367, 537004, 549223, 551781], [10266, 12382, 12440, 12740, 14586, 17123, 17226, 19529, 21164, 23134, 24117, 24405, 24592, 24784, 25167, 25296, 26352, 28166, 29049, 30388, 30732, 30942, 31858, 32256, 32642, 33539, 33650, 33795, 34654, 34846, 34901, 36555, 36779, 36791, 36862, 37885, 39999, 41253, 41769, 42017, 42971, 42979, 43211, 43301, 43491, 43668, 43771, 44716, 46292, 46963, 47394, 47900, 47907, 47963, 48230, 48600, 49050, 50153, 50368, 50724, 51006, 51239, 51397, 51632, 52149, 53225, 54150, 54414, 54668, 54758, 56033, 56068, 56398, 56667, 56861, 57682, 57795, 57980, 58063, 58459, 58482, 59471, 59954, 60562, 60828, 62766, 63184, 66533, 67662, 68008, 69764, 70738, 71989, 72995, 74593, 75139, 75492, 75841, 80145, 80253, 80421, 80577, 80740, 81172, 87379, 88189, 94448, 100368, 100747, 102028, 104623, 105476, 127011, 137450, 549223]], "251": [[10764, 10901, 11473, 11690, 11773, 12957, 13941, 14882, 15586, 15737, 15771, 15908, 16837, 16936, 17978, 18635, 18746, 19404, 19580, 19605, 21426, 21737, 22028, 23002, 23154, 23503, 24041, 24405, 24483, 24592, 24759, 25008, 25327, 25602, 26078, 26207, 26262, 26714, 26769, 26991, 27424, 27435, 27455, 27616, 28065, 28382, 28401, 28608, 29112, 29186, 29219, 29348, 29865, 30299, 30853, 31162, 31183, 31391, 32063, 32180, 32259, 32833, 32994, 33186, 33222, 33349, 33520, 33795, 34043, 35250, 35432, 36405, 36779, 36857, 36986, 37661, 37789, 37885, 37926, 38159, 38824, 39125, 39207, 39388, 39483, 41124, 41152, 41196, 41431, 41528, 42485, 42566, 42829, 42956, 43249, 43308, 43468, 43569, 43656, 44380, 44716, 44950, 45329, 46014, 46094, 46718, 46814, 46823, 46842, 46963, 46985, 47239, 47390, 47677, 48138, 48229, 48394, 48414, 48511, 48597, 48737, 48761, 49169, 49792, 49940, 50153, 50328, 50405, 50437, 50875, 51612, 51674, 51757, 51997, 52197, 52258, 52498, 52519, 52628, 52999, 53157, 53160, 53367, 53419, 53443, 53864, 54152, 54171, 54182, 54220, 54252, 54267, 54308, 54896, 55116, 55266, 55472, 55478, 55587, 55640, 55860, 55974, 56012, 56059, 56228, 56265, 56576, 56681, 56803, 56973, 57264, 57753, 57846, 58178, 58216, 58267, 58347, 58947, 59024, 59486, 59546, 59576, 60059, 60490, 60673, 61099, 61372, 61410, 61502, 61512, 62651, 62680, 63959, 64331, 65354, 66639, 68245, 68819, 70149, 70256, 71801, 71998, 72025, 72929, 73073, 74217, 74582, 74768, 75084, 75190, 75861, 76065, 77074, 77300, 77521, 77538, 77902, 78816, 78827, 79075, 79754, 79872, 80590, 80843, 81172, 82695, 84185, 84392, 85308, 85503, 86123, 87379, 89925, 90523, 92584, 97188, 98152, 99781, 101039, 101055, 103331, 103726, 108070, 108297, 109885, 111750, 113128, 115098, 141967, 143239, 152763], [10284, 10723, 10764, 12295, 12973, 13285, 13842, 14199, 15021, 16819, 18464, 19526, 19645, 20303, 20634, 21295, 21406, 22181, 22397, 22550, 22672, 22886, 23128, 23134, 23463, 23867, 24272, 24482, 24734, 24784, 24951, 25290, 25298, 25327, 25423, 25490, 25729, 25840, 26059, 26685, 26955, 26976, 27704, 27946, 28065, 28208, 28401, 28500, 28836, 28877, 29453, 29553, 29600, 29865, 30299, 30710, 30719, 31040, 31842, 31976, 32103, 33332, 33397, 33492, 34237, 34275, 34481, 34694, 35534, 35689, 35791, 35860, 35974, 36397, 36612, 37871, 38374, 39150, 39372, 39422, 39483, 39513, 39544, 39574, 39999, 40983, 41240, 41263, 41411, 41449, 41562, 42150, 42884, 42897, 42971, 43242, 43296, 43311, 43468, 43742, 44068, 44427, 44454, 44871, 45949, 46014, 46443, 46796, 46811, 46873, 46874, 46987, 47642, 47704, 47875, 48256, 48363, 48726, 48810, 48896, 49034, 49089, 49182, 49395, 49643, 49904, 49992, 50310, 50336, 50396, 50405, 50604, 50994, 51105, 51166, 51632, 51640, 51687, 51840, 51842, 51850, 52311, 52929, 52999, 53419, 53440, 53572, 53573, 53666, 53986, 54076, 54182, 54279, 54896, 54998, 55194, 55330, 55472, 55573, 55596, 55671, 55735, 56268, 56521, 56772, 57753, 58004, 58321, 58400, 58815, 58895, 59127, 59486, 59497, 59663, 59730, 59808, 60079, 60084, 60338, 60413, 60490, 60782, 60806, 61212, 61621, 61948, 64432, 64648, 64772, 64950, 65308, 65354, 66080, 66269, 66639, 66647, 66685, 66924, 67405, 67662, 68559, 68696, 69427, 70462, 70519, 70593, 70790, 71527, 72451, 72759, 73080, 73667, 75345, 75654, 75698, 75999, 76717, 77590, 77681, 78043, 79080, 79260, 80477, 80504, 81594, 82836, 84185, 86158, 91261, 92584, 93839, 94547, 95049, 96453, 97486, 97604, 104440, 104623, 112918, 113128, 115394, 115744, 119769, 122923, 125843, 128586, 131476, 138940, 152763, 543485], [11153, 12764, 13532, 15400, 16609, 16996, 17985, 19160, 19623, 21983, 22028, 22211, 22831, 23002, 23128, 23413, 23471, 23664, 23830, 24117, 24162, 24197, 24647, 24947, 25008, 25067, 25372, 25698, 25815, 25902, 26811, 27396, 28118, 28204, 28208, 28401, 29119, 29219, 29438, 29979, 30457, 30695, 30993, 31040, 31173, 31250, 31623, 32082, 32103, 32614, 32763, 32969, 33492, 33539, 34471, 34502, 34838, 34986, 35240, 35300, 35689, 35709, 35876, 35905, 36805, 36936, 37661, 37941, 38458, 38625, 38729, 39042, 39299, 39317, 39372, 39520, 39574, 39670, 39803, 40829, 41241, 41397, 41409, 41506, 42076, 42080, 42288, 42655, 42865, 42903, 43035, 43066, 43463, 43484, 43569, 43766, 43769, 43913, 44016, 44122, 44454, 44510, 44542, 44950, 45158, 45611, 46077, 46288, 46408, 46735, 46877, 46938, 46948, 47688, 47798, 48473, 48506, 48511, 48591, 49212, 49221, 49553, 49593, 49792, 49878, 49918, 49963, 50405, 51347, 51717, 51872, 51950, 51967, 52110, 52377, 52471, 52597, 52626, 52737, 52929, 53170, 53440, 53457, 54267, 54668, 54730, 54877, 54896, 55108, 55386, 55436, 55596, 55940, 56300, 56838, 56908, 57070, 57850, 57964, 58092, 58267, 58437, 58621, 59222, 59319, 59563, 59661, 59844, 60084, 60137, 60190, 60371, 60567, 60597, 61303, 61796, 62409, 62529, 62625, 62764, 62934, 63351, 63962, 64080, 64287, 65028, 65033, 65308, 65354, 65584, 65793, 66685, 67136, 67177, 67557, 69324, 69476, 70229, 70593, 71150, 71801, 71913, 72213, 72269, 72616, 72782, 73323, 73420, 73799, 73966, 74217, 74866, 75184, 75399, 75502, 76560, 77214, 78012, 78210, 78273, 79321, 79872, 80527, 80835, 81026, 81580, 82421, 85503, 85817, 86123, 88268, 88591, 89366, 89469, 90987, 91239, 92853, 93090, 93624, 95082, 99981, 103331, 105333, 110325, 118684, 126713, 128140, 138940, 143239, 526785, 529228], [10015, 10016, 10693, 11291, 14199, 14819, 15029, 15074, 15422, 15870, 16552, 16606, 17515, 17610, 17945, 17978, 18314, 18683, 19160, 21129, 21406, 21734, 21737, 22944, 22989, 22990, 22997, 23062, 23134, 23154, 23210, 24272, 24784, 24810, 24909, 25167, 25665, 26028, 26154, 26560, 26808, 27000, 27168, 27449, 28134, 28199, 28228, 28420, 28541, 29103, 29596, 29757, 30262, 30309, 30440, 30601, 32530, 32640, 33142, 33222, 33545, 33676, 33756, 34043, 34694, 34708, 34731, 34821, 34901, 34990, 35458, 35587, 36164, 36481, 36555, 36872, 37200, 37321, 37525, 37645, 37871, 37913, 38681, 39150, 39156, 39281, 39840, 40372, 40394, 40477, 40614, 40767, 40973, 41012, 41663, 41848, 42047, 42149, 42706, 42811, 42956, 43184, 43548, 43579, 43913, 44057, 44086, 44228, 44284, 44427, 44979, 45120, 45399, 45508, 46050, 46140, 46233, 46260, 46669, 47058, 47077, 47500, 47875, 48889, 48891, 48907, 49171, 49278, 49643, 49662, 49740, 49773, 49789, 49792, 50299, 50328, 50473, 50604, 50890, 50900, 50959, 51215, 51288, 51343, 51447, 51513, 51640, 51693, 51757, 52274, 52386, 53085, 53311, 53611, 53980, 54150, 54153, 54220, 54252, 54299, 54358, 54929, 55006, 55129, 55436, 55472, 55671, 55952, 55954, 56226, 56392, 56919, 56985, 57254, 57766, 58347, 58815, 58915, 59031, 59131, 59297, 59879, 60021, 60230, 60463, 61208, 62257, 62514, 62518, 62835, 63286, 63490, 63636, 63749, 64618, 65088, 65552, 65733, 65767, 66155, 66269, 66534, 67413, 67502, 67729, 67958, 68266, 69764, 70548, 73968, 74817, 75439, 76614, 76717, 76855, 77225, 77661, 77753, 79050, 79075, 80843, 81580, 82695, 84518, 87221, 87327, 88083, 88101, 89773, 90856, 90960, 95082, 95834, 97188, 97604, 98447, 98561, 99740, 99981, 102944, 107821, 109704, 113013, 113042, 120860, 150743, 176056, 513435, 516882, 533520, 546795], [10015, 10231, 10266, 10729, 12202, 12428, 12440, 13285, 13326, 14179, 15400, 15422, 15688, 15771, 17307, 17610, 18282, 18970, 21120, 21159, 21570, 22248, 22550, 23002, 23413, 23448, 23463, 23830, 24208, 24647, 24854, 25088, 25200, 25276, 25298, 25327, 25388, 25617, 26349, 27006, 27189, 27579, 27705, 28382, 28403, 28497, 29049, 29402, 29553, 29853, 30017, 30309, 30393, 30535, 30890, 30951, 31184, 31254, 31471, 31540, 31999, 32508, 32969, 33026, 33539, 33793, 34123, 34237, 34931, 34993, 35000, 36164, 36612, 36805, 36903, 37050, 37103, 37216, 37418, 37612, 37727, 38017, 38148, 38245, 38507, 38691, 39299, 39551, 39750, 40263, 40682, 40805, 41348, 42358, 42475, 42794, 43035, 43254, 43311, 43484, 43877, 44454, 44563, 44925, 44927, 45009, 45120, 45254, 45278, 45466, 45508, 45609, 45670, 45897, 46651, 46718, 46814, 46938, 47056, 47725, 48229, 48234, 48271, 49244, 49643, 50153, 50181, 50328, 50336, 50686, 50900, 51058, 51067, 51464, 51768, 52118, 52197, 52327, 52498, 52519, 53085, 53244, 53419, 53422, 53457, 53630, 53734, 53864, 53963, 54000, 54364, 54522, 54617, 54801, 54812, 55005, 55281, 55573, 56228, 56626, 56836, 56909, 56940, 56985, 57060, 57070, 57254, 57264, 57270, 57557, 57766, 57913, 57964, 58012, 58493, 58858, 58900, 59031, 59563, 59879, 60088, 60597, 60673, 61124, 61410, 61574, 61621, 61866, 61948, 62835, 62849, 62870, 63155, 63749, 64065, 64174, 64490, 64658, 65091, 65476, 65985, 66080, 66269, 66533, 66869, 66924, 67324, 67367, 68854, 69072, 69272, 69476, 70134, 70536, 71913, 72995, 75753, 75967, 76614, 77214, 77507, 78103, 78110, 79756, 80008, 80253, 80394, 80527, 81408, 82562, 85268, 86798, 88596, 88982, 91158, 93839, 93910, 95170, 95780, 96303, 98561, 101152, 106967, 107821, 110325, 112131, 112757, 115394, 132767, 511987, 550411], [10682, 11031, 11812, 12236, 12328, 12979, 13196, 13532, 15007, 15062, 17302, 18635, 18883, 19623, 19645, 22307, 22662, 23087, 23317, 23664, 23729, 24469, 25327, 25708, 26059, 26070, 26111, 26124, 26207, 26268, 26450, 26769, 27533, 28031, 28207, 28356, 28476, 28510, 28877, 29406, 29506, 29600, 29703, 29866, 29896, 29942, 30142, 30393, 30838, 31391, 31842, 31900, 31931, 32063, 32277, 32722, 33177, 33294, 33728, 33756, 33796, 33870, 34450, 34481, 34756, 34986, 34990, 35149, 35181, 35284, 35432, 35458, 35559, 35689, 36081, 36211, 36555, 36693, 36847, 36936, 37370, 38360, 38374, 38681, 38810, 38913, 39427, 39606, 39670, 40672, 40772, 40799, 40800, 40805, 41506, 41852, 41930, 42047, 42406, 42642, 42903, 43015, 43790, 44185, 44454, 44709, 44871, 45087, 45093, 45444, 45606, 45649, 46414, 46659, 46844, 46985, 47670, 47900, 47982, 48166, 48256, 48327, 48333, 48363, 48591, 48600, 48606, 48726, 48799, 48871, 49163, 49206, 49258, 49801, 49955, 49988, 50161, 50415, 50643, 50693, 51392, 51693, 52628, 52643, 52737, 53121, 53150, 53170, 53965, 54235, 54692, 54804, 55126, 55176, 55330, 55829, 55832, 56059, 56188, 56638, 56803, 56973, 57232, 57672, 57794, 58459, 58509, 58535, 58548, 58668, 59118, 59222, 59661, 60146, 60269, 60562, 60786, 61212, 61866, 62064, 62257, 62523, 62625, 62634, 62764, 62835, 63399, 63785, 63802, 64435, 65682, 65900, 66262, 66521, 66630, 67502, 67657, 67779, 67958, 68315, 68589, 68805, 69072, 69345, 69427, 69533, 69932, 70149, 70347, 70549, 70883, 72376, 73696, 74144, 74404, 74768, 74890, 75018, 75316, 75324, 77015, 77017, 78738, 79080, 80404, 81172, 82348, 86184, 86241, 86314, 87733, 88129, 89662, 93425, 93520, 93839, 94413, 99781, 100179, 100368, 106050, 106967, 107064, 112134, 112388, 113476, 124182, 130534, 132767, 139914, 171682], [10311, 10381, 10439, 10729, 11153, 12979, 15007, 15074, 15422, 15586, 15908, 16373, 16512, 17610, 17942, 19459, 19513, 21120, 21249, 21352, 21737, 21983, 22248, 22648, 23757, 23867, 24272, 24469, 24810, 25423, 25729, 26070, 26274, 26349, 26599, 26685, 27455, 27709, 27726, 28031, 28166, 28207, 28273, 28954, 29172, 29249, 29406, 29744, 29896, 30134, 30309, 30485, 32103, 32244, 32642, 33177, 33186, 33478, 33752, 34123, 34774, 34834, 35148, 35348, 35500, 35529, 35907, 35975, 36211, 36865, 37727, 37885, 38913, 39876, 40264, 40641, 40682, 40738, 40979, 41071, 41461, 41989, 42032, 42076, 42300, 42359, 42406, 42485, 42525, 42622, 42624, 42794, 42884, 43035, 43548, 43769, 43910, 43913, 44068, 44320, 44600, 44756, 44927, 45314, 45670, 45943, 46014, 46644, 46648, 46699, 46742, 46814, 46841, 46985, 47099, 47878, 48506, 49182, 49295, 49593, 49940, 49962, 50153, 50303, 50604, 50697, 50875, 50900, 51202, 51343, 51423, 51657, 51842, 52118, 52360, 52401, 52643, 52736, 52741, 52774, 53121, 53157, 53630, 54252, 54497, 54697, 55108, 55208, 55261, 55412, 55533, 55856, 56141, 56194, 56300, 56320, 56638, 56836, 56902, 57766, 57795, 58188, 58281, 58582, 58680, 59175, 59322, 59345, 59819, 59894, 60334, 60347, 61124, 61284, 61813, 62680, 63235, 63490, 63658, 64174, 64236, 64348, 64382, 64618, 64658, 64764, 64851, 65551, 66646, 67193, 67501, 68331, 69272, 70549, 70954, 71867, 72616, 72713, 72772, 73680, 73832, 74505, 74649, 75345, 75753, 75904, 76576, 76805, 78273, 78738, 79251, 79475, 80253, 81408, 81580, 82743, 82901, 84185, 84392, 84963, 85308, 85709, 86844, 87327, 87385, 88413, 90507, 91762, 92163, 92584, 95605, 95834, 96453, 97188, 98468, 100901, 102929, 103784, 105476, 106185, 107583, 108297, 115098, 119769, 122013, 124081, 127011, 128586, 138940, 139878, 555651], [10682, 11291, 11435, 12295, 12428, 12440, 14819, 16153, 17307, 17610, 18079, 18632, 18661, 18809, 18895, 19122, 19233, 19623, 19887, 20874, 21249, 22070, 22148, 23154, 23471, 23503, 23738, 23868, 24208, 24272, 24483, 24775, 25010, 25276, 25308, 25372, 25641, 25665, 25772, 26006, 26028, 26510, 27131, 27378, 27427, 27882, 28329, 28387, 28437, 29092, 29125, 29249, 29619, 29669, 29942, 30247, 31184, 31900, 31999, 32014, 32277, 32990, 33688, 34471, 35451, 35595, 35766, 36469, 36768, 36779, 36791, 36847, 37721, 37871, 37941, 38003, 38927, 38953, 39073, 39097, 39276, 39356, 39434, 39552, 39646, 39999, 40597, 40772, 40785, 40863, 41431, 41562, 42525, 42990, 43242, 43249, 43566, 44430, 44504, 44510, 44542, 44631, 44642, 44856, 44950, 45494, 46046, 46292, 46669, 46814, 46857, 46923, 46930, 46956, 47038, 47061, 47109, 47532, 47872, 47963, 47979, 48221, 48333, 49036, 49278, 49395, 49643, 49734, 49740, 49765, 50693, 50697, 50902, 50924, 51180, 51293, 51825, 52149, 52311, 52386, 52498, 52597, 52941, 52956, 52986, 53098, 53365, 54347, 54364, 54697, 55266, 55386, 55447, 55829, 55981, 56161, 57165, 57264, 57348, 57850, 57964, 58632, 58895, 59084, 59197, 59663, 59811, 60019, 60428, 60638, 60806, 61155, 61574, 61818, 62458, 62804, 63121, 63184, 63452, 63785, 63802, 63956, 64034, 64676, 64758, 65552, 66278, 66370, 66587, 66888, 67740, 68213, 68534, 68559, 68589, 68819, 68852, 69345, 70034, 70511, 70831, 71878, 71973, 71986, 72139, 73799, 74205, 74271, 74404, 74452, 75502, 76039, 77538, 78043, 79080, 80597, 80801, 81433, 83215, 83242, 83357, 83629, 84051, 84827, 86184, 88591, 88982, 89925, 90110, 92216, 93624, 93770, 95605, 97034, 97604, 98152, 98959, 100402, 100572, 101082, 102174, 104132, 106050, 107120, 107259, 112131, 112134, 125034, 128586, 513435, 593158], [10439, 11169, 11522, 11696, 12382, 12428, 12957, 12979, 14300, 15062, 15593, 17978, 18246, 18507, 18683, 20618, 21734, 22990, 23716, 23867, 24027, 24211, 24734, 25008, 25290, 25648, 25862, 26008, 26059, 26246, 27175, 28260, 28628, 29049, 29315, 29553, 29633, 29703, 29993, 30098, 30376, 30510, 30566, 30710, 30732, 30890, 30942, 31036, 31250, 31598, 31607, 31677, 31900, 32104, 32175, 32256, 32277, 33135, 33177, 33756, 34266, 34289, 34433, 34443, 34481, 34542, 34733, 35375, 35587, 35873, 36405, 36464, 36647, 36768, 36791, 36804, 36832, 36943, 37485, 37525, 37767, 37830, 37913, 38039, 38899, 39512, 39606, 39795, 40155, 40552, 40682, 41099, 41117, 41456, 41848, 41926, 41970, 42516, 42525, 42566, 42730, 42956, 42990, 43656, 43910, 43913, 44153, 44299, 44387, 44631, 44656, 46077, 46146, 46292, 46651, 46857, 46874, 47347, 47377, 47448, 47555, 47778, 48094, 48307, 48871, 49359, 49449, 49773, 50001, 50328, 50396, 50678, 51392, 51640, 51768, 52377, 52850, 53417, 53419, 53734, 54150, 54267, 54421, 54479, 54682, 55958, 56139, 56279, 56618, 56985, 57794, 57805, 57894, 58012, 58216, 58228, 58509, 58727, 58807, 58900, 59118, 59121, 59381, 59738, 60068, 60338, 60490, 60659, 61351, 61372, 61741, 61796, 61884, 62053, 62634, 62764, 62902, 62934, 63200, 63769, 63802, 63959, 64065, 64423, 64618, 64668, 64676, 64764, 65476, 65552, 65733, 65887, 66013, 66358, 66410, 66869, 67003, 67367, 67662, 68442, 68465, 68630, 68772, 68805, 69172, 69990, 70084, 70256, 70730, 71324, 71759, 72162, 72560, 73073, 74217, 74386, 74452, 74565, 74689, 74866, 75492, 75502, 76855, 78377, 80145, 81459, 81594, 83226, 84397, 86837, 89751, 90856, 93011, 94185, 94376, 97483, 98152, 99480, 99560, 101044, 105333, 110754, 110835, 113128, 115394, 119769, 125034, 126713, 146570, 545828, 557250], [10025, 11055, 11169, 11609, 13285, 15334, 15868, 15870, 16461, 17605, 17978, 18246, 18311, 18683, 18701, 19404, 19539, 21164, 21199, 22070, 22189, 22428, 22505, 22750, 22783, 22997, 23317, 23686, 24034, 24405, 24464, 24769, 24775, 25574, 25840, 26008, 26574, 26863, 27026, 27027, 27946, 28031, 28599, 29660, 29993, 31250, 31439, 31976, 32005, 32106, 32259, 32277, 32281, 32954, 33026, 33135, 33235, 33520, 33527, 33707, 33865, 33948, 33979, 34092, 34277, 34502, 34859, 34901, 34993, 35000, 35148, 35242, 35458, 36242, 36287, 36464, 36481, 36612, 36794, 36832, 37182, 37485, 37830, 38862, 39574, 39664, 40552, 40597, 40767, 40785, 40884, 41172, 41219, 41240, 41312, 41409, 42360, 42801, 42832, 43240, 43242, 43311, 43316, 43692, 44284, 44454, 44542, 44633, 45228, 45897, 46077, 46844, 47041, 47200, 47448, 47504, 47599, 47677, 47688, 47900, 48143, 48208, 48857, 48923, 48951, 49089, 49093, 49244, 49512, 49593, 49963, 50001, 50729, 50900, 50926, 51271, 51332, 51588, 51632, 51674, 51950, 52102, 52197, 52329, 52648, 52891, 53110, 54000, 54522, 54741, 54929, 55087, 55116, 55404, 55472, 55834, 56161, 57060, 57264, 57753, 57805, 58267, 58479, 58626, 58654, 59280, 59426, 59497, 59802, 59814, 59819, 60230, 60338, 60807, 61212, 61468, 62199, 62360, 62458, 62634, 62809, 63036, 63962, 64034, 64064, 64080, 64162, 64174, 64505, 64676, 64950, 65232, 65552, 65978, 66410, 66507, 66656, 67145, 67372, 67649, 67657, 67662, 68266, 68663, 69617, 70080, 70149, 70790, 71221, 71822, 72214, 72616, 74817, 75492, 75904, 75967, 75999, 76432, 76560, 77225, 77538, 77976, 80421, 80432, 81539, 82539, 83653, 89255, 89469, 92163, 97486, 98029, 98959, 100747, 101039, 101055, 101694, 106223, 107144, 108285, 110325, 110613, 110911, 111519, 111584, 114704, 119919, 129919, 172286, 516882, 533520], [10231, 10235, 10284, 10439, 11077, 11551, 12416, 12440, 12521, 13727, 14199, 15737, 15908, 17123, 18079, 18970, 20733, 21129, 21159, 21632, 22189, 22307, 22505, 23087, 23503, 23677, 23716, 23729, 24469, 24753, 25008, 25873, 25893, 26167, 26685, 26714, 26955, 27704, 28100, 28243, 28420, 28823, 28890, 29359, 29904, 29954, 30017, 30204, 30309, 30506, 30510, 30585, 30600, 30942, 31162, 31540, 32175, 33026, 33048, 33381, 33547, 33574, 33885, 34043, 34443, 34774, 34834, 34846, 35465, 35549, 35618, 35860, 35975, 36211, 36421, 36647, 37493, 37612, 37871, 38003, 38021, 38082, 38164, 38572, 38881, 39097, 39137, 39190, 39263, 39299, 40500, 40614, 41045, 41071, 41253, 41312, 41411, 41431, 41512, 41562, 41893, 41970, 42452, 42524, 42624, 42631, 42655, 43468, 43548, 43671, 43979, 44136, 44641, 45116, 45606, 45956, 46063, 46408, 46608, 47234, 47394, 47482, 47500, 47982, 48327, 48341, 48429, 49050, 49087, 49093, 49163, 49171, 49765, 49992, 50130, 50545, 50724, 50890, 50971, 51086, 51105, 51202, 51215, 51376, 52274, 52498, 52519, 52621, 52891, 52895, 53085, 53162, 53986, 54562, 54998, 55108, 55208, 55483, 55601, 55981, 56339, 56667, 57264, 57439, 57682, 58409, 58727, 59131, 59175, 59269, 59503, 59990, 60059, 60079, 60146, 60211, 60638, 60895, 61124, 61134, 61386, 61544, 61627, 62693, 62972, 63155, 63184, 64432, 64648, 64764, 66705, 66869, 66924, 67604, 67658, 68442, 68534, 68657, 68819, 69272, 69342, 69741, 69932, 70134, 70166, 70347, 70561, 71324, 72995, 74217, 74505, 74593, 74866, 75018, 75509, 75698, 77942, 78043, 78087, 78179, 78738, 80722, 80801, 80834, 81292, 82695, 82901, 84051, 85709, 85828, 86681, 86798, 89797, 90321, 93090, 93597, 94414, 97586, 100572, 101121, 106185, 110613, 111519, 112757, 113476, 150743, 518732, 542891, 543072, 543485, 555651], [10231, 10372, 11551, 12254, 14179, 15363, 15377, 16552, 17123, 18462, 18635, 19050, 19160, 19513, 20303, 20618, 21249, 22112, 22181, 22656, 22754, 23134, 23867, 24211, 24409, 24483, 24784, 24947, 25389, 25472, 25490, 25698, 25952, 26006, 26037, 26070, 26075, 26111, 26598, 26881, 26944, 27211, 27349, 27449, 27755, 28541, 28776, 28877, 29348, 29660, 29669, 29993, 30566, 30659, 30710, 31084, 31116, 31162, 31526, 31607, 31623, 32640, 32994, 33222, 33558, 34009, 34123, 34671, 34839, 35098, 35242, 35898, 36107, 36242, 36943, 36981, 37870, 38164, 38557, 39220, 39263, 39574, 39606, 39664, 39851, 40263, 40799, 40810, 40873, 40999, 41325, 41348, 41663, 42076, 43254, 43333, 43656, 43742, 43970, 44016, 44086, 44153, 44267, 44341, 44800, 44849, 45003, 45508, 45611, 45817, 45897, 45902, 46033, 46558, 46608, 46742, 46823, 46987, 46992, 47090, 47238, 47453, 47798, 47872, 48230, 48409, 48566, 48597, 48863, 49169, 49295, 49359, 50130, 50152, 50405, 51202, 51674, 52626, 52683, 52741, 52783, 53225, 53443, 53573, 53980, 54335, 54748, 54942, 55006, 55404, 55489, 55832, 55856, 55940, 55957, 56177, 56626, 56913, 57041, 57136, 57557, 57679, 58025, 58621, 58819, 58864, 58880, 58915, 58953, 59142, 59297, 59319, 59345, 59537, 59862, 61208, 62766, 62972, 63135, 63802, 64065, 64109, 64505, 64764, 65066, 65682, 66155, 66256, 66410, 66521, 66647, 67637, 67658, 67740, 70229, 70347, 70462, 70536, 71017, 71221, 72616, 73037, 73893, 74649, 74816, 75018, 75084, 75139, 76312, 77061, 77166, 77214, 77406, 77681, 77976, 78645, 78716, 78816, 79568, 79629, 80680, 82193, 82421, 82695, 85254, 86669, 89903, 90987, 91762, 93011, 93090, 93624, 94128, 94937, 95605, 95896, 96453, 98468, 99161, 99560, 100702, 103021, 109897, 112388, 113476, 115336, 128586, 131476, 543072, 551781, 593158], [10206, 12202, 12640, 12973, 14499, 15377, 16153, 16474, 17329, 18311, 19539, 20700, 21234, 21352, 21983, 22670, 22990, 23271, 23729, 23848, 24132, 24405, 24769, 24954, 25369, 25574, 25670, 25772, 26070, 26111, 27946, 28207, 28228, 28608, 28776, 28956, 29125, 29209, 29633, 29866, 30151, 30440, 30485, 30499, 30714, 30890, 31006, 31162, 31254, 31332, 31512, 32256, 32281, 32642, 32946, 33048, 33139, 33142, 33161, 33906, 34175, 34499, 34566, 34645, 34651, 35284, 35375, 35559, 35587, 35766, 35873, 35981, 36555, 36692, 36693, 37246, 38000, 38504, 39125, 39642, 39803, 40150, 40726, 40767, 40829, 40999, 41152, 41214, 42069, 42096, 42147, 42351, 42360, 42485, 42622, 42638, 42801, 42832, 43066, 43094, 43671, 44228, 44299, 44598, 44633, 44756, 45956, 46233, 46651, 46823, 46842, 46850, 46923, 46948, 47238, 47347, 47388, 47504, 47532, 47709, 47738, 47907, 48276, 48394, 48576, 48923, 48951, 49050, 49163, 49295, 50001, 50604, 50678, 50959, 51180, 51376, 52110, 52386, 52850, 52863, 52999, 53131, 53284, 53493, 54000, 54244, 54358, 54457, 54497, 54517, 54606, 54741, 54821, 55472, 55533, 55565, 55587, 55743, 56772, 57299, 57742, 57753, 57794, 58333, 58582, 58668, 58864, 58943, 58974, 59028, 59127, 59175, 59280, 59345, 59511, 59546, 59745, 59777, 59940, 60059, 61099, 61142, 61212, 61284, 61303, 61386, 61743, 62409, 62685, 62972, 63111, 63962, 63980, 64034, 65308, 65335, 65682, 65915, 66798, 67136, 67729, 67742, 68266, 68852, 69172, 69342, 69345, 70034, 70561, 70738, 71801, 71878, 72213, 72469, 72508, 72995, 74128, 74566, 74768, 74995, 75139, 75999, 77214, 77662, 77711, 78827, 79260, 79754, 80394, 80504, 80577, 82348, 86798, 89375, 90523, 91158, 94135, 96404, 97430, 97486, 99981, 100368, 100493, 101152, 107064, 111519, 112077, 118684, 138845, 522475, 540405], [10771, 10915, 13881, 13941, 14179, 14499, 15868, 16552, 17302, 17610, 19503, 21352, 21426, 21832, 22547, 22656, 22810, 23062, 23463, 23848, 24164, 24405, 24464, 24469, 24691, 25167, 25388, 25711, 25862, 25893, 26006, 26545, 27334, 27396, 27616, 27884, 27913, 28954, 29348, 29402, 29866, 30510, 31874, 31894, 31976, 32299, 32585, 32640, 32722, 32994, 33139, 33157, 33397, 33495, 33620, 33752, 34009, 34204, 34266, 34433, 34502, 34666, 34877, 34901, 35086, 35241, 35317, 36220, 36397, 36943, 37493, 38000, 38319, 38360, 39388, 39462, 39797, 39803, 39840, 40183, 40264, 40863, 40999, 41152, 41222, 41253, 41416, 41839, 42508, 42990, 43491, 43566, 43692, 43748, 44016, 44067, 44228, 44284, 44871, 44927, 45209, 45606, 45710, 45776, 45804, 45817, 46050, 46219, 46669, 46811, 46946, 46992, 47388, 47482, 47975, 48327, 48901, 48960, 49050, 49171, 49643, 49715, 49732, 49904, 50152, 50926, 51343, 51447, 51588, 51687, 51840, 51847, 51915, 51939, 51967, 52588, 52604, 53085, 53864, 53897, 53963, 53965, 54041, 54199, 55330, 55533, 55634, 55983, 56012, 56180, 56277, 56585, 58307, 58332, 58680, 58807, 59045, 59084, 59121, 59137, 59222, 59471, 59576, 59879, 59894, 60019, 60413, 60786, 60828, 61101, 61248, 61286, 61512, 61544, 62053, 62441, 62764, 62766, 63665, 64034, 64287, 64676, 64906, 65354, 65444, 65551, 65843, 65900, 66269, 66410, 66534, 67010, 67720, 68243, 68536, 68778, 68859, 68871, 69253, 69345, 70291, 70462, 70511, 71986, 72214, 73073, 74386, 74825, 76065, 76614, 76717, 78110, 78660, 78755, 79321, 80421, 80722, 81292, 82103, 82901, 82923, 83102, 83483, 83824, 86158, 86681, 87585, 87733, 88129, 89475, 89751, 90292, 90306, 92163, 93178, 93839, 94185, 95605, 96453, 96680, 98152, 100179, 107446, 109897, 111519, 112077, 112757, 112804, 139878, 529228, 543072], [10284, 10311, 11551, 11690, 12328, 13881, 14499, 15110, 15377, 16512, 16996, 17329, 18227, 18683, 18701, 19577, 19887, 19939, 20778, 20801, 21295, 21483, 21565, 21734, 21782, 22662, 23463, 23867, 23936, 24211, 24283, 24469, 24592, 24759, 25472, 25661, 25862, 25873, 26006, 26352, 26723, 26808, 26863, 26944, 27291, 27579, 27709, 27946, 28118, 28134, 28375, 28510, 28944, 29553, 29619, 29866, 30151, 30388, 30499, 30585, 30751, 30853, 30876, 31173, 31456, 31540, 31767, 32170, 32614, 32635, 32820, 33539, 34121, 34266, 34450, 34456, 34502, 34566, 34662, 34671, 34814, 34821, 34846, 35149, 35242, 35375, 35451, 36211, 36421, 36693, 36779, 36862, 36903, 37465, 37485, 37913, 38039, 38217, 38246, 38881, 38953, 39058, 39137, 39165, 39264, 39434, 39483, 39795, 39876, 40287, 40973, 41222, 41348, 41409, 41989, 42041, 42305, 42330, 42516, 43316, 43428, 44656, 44666, 44927, 45116, 45306, 45466, 45494, 45943, 46443, 46742, 46937, 46987, 47017, 47041, 47099, 47390, 47463, 48317, 48799, 48863, 48907, 49094, 49163, 49715, 49749, 49904, 50398, 50678, 50890, 51840, 52194, 53078, 53284, 53419, 53440, 53692, 53864, 54199, 54269, 54347, 54778, 56177, 56220, 56268, 57681, 57682, 57731, 57881, 57894, 58409, 58668, 58807, 58864, 59025, 59546, 59655, 59808, 59954, 60347, 60428, 60567, 60807, 60812, 61148, 61477, 61512, 61934, 62514, 62523, 62764, 63121, 63745, 64618, 65091, 65451, 65503, 65793, 66013, 66473, 67502, 68282, 68378, 68445, 68589, 69272, 69342, 69932, 70511, 71017, 71493, 72064, 72469, 72651, 72679, 72713, 72782, 73532, 75654, 76174, 76576, 76614, 77177, 77507, 77629, 78521, 79754, 79845, 81150, 82103, 82836, 84592, 84958, 86341, 87385, 88129, 91261, 92247, 93910, 94104, 97486, 99981, 103331, 110325, 117796, 118070, 124182, 125681, 131476, 169810, 550055], [10372, 10723, 10803, 11077, 11690, 12145, 12202, 12295, 12382, 12639, 12973, 13326, 13565, 13874, 14416, 16390, 17123, 17677, 17831, 17942, 19160, 20175, 21065, 21164, 21249, 22148, 22944, 24132, 24774, 25569, 25729, 27322, 27334, 27533, 27616, 28259, 29102, 29865, 30017, 30134, 30151, 30309, 30566, 30853, 30941, 31162, 31456, 31623, 31878, 31976, 32244, 32281, 32299, 32640, 32754, 33048, 33222, 33235, 33349, 33353, 33429, 33495, 33904, 34029, 34651, 34774, 34838, 35240, 35534, 35746, 36088, 36164, 36211, 36405, 36539, 36981, 37525, 37727, 37767, 37789, 38374, 38557, 38572, 38810, 39097, 39422, 39808, 40607, 40799, 40829, 40973, 41209, 41214, 41663, 41970, 42017, 42032, 42041, 42305, 42359, 42525, 42794, 42829, 43066, 43316, 43428, 43458, 43790, 44598, 44638, 44639, 44716, 44849, 44979, 45300, 45611, 45956, 46077, 46219, 46435, 46946, 47077, 47500, 47878, 48799, 48951, 49221, 49326, 49381, 49940, 50243, 51331, 51399, 51825, 51840, 51845, 52386, 52588, 52596, 52737, 52741, 52850, 53572, 53611, 53797, 54152, 54668, 54673, 54692, 55194, 55208, 55634, 55671, 55952, 56279, 56300, 56320, 56521, 56772, 56826, 56908, 56983, 57067, 57299, 57517, 57557, 57766, 57964, 58121, 58680, 58689, 59191, 59940, 60079, 60113, 60680, 60786, 61148, 61257, 61372, 61884, 63155, 63184, 63301, 64348, 65028, 65091, 65188, 65444, 65551, 65793, 66013, 66358, 66368, 66587, 67010, 67706, 68331, 68630, 68724, 70084, 70291, 70570, 72469, 73080, 73582, 74144, 74566, 75316, 76339, 76614, 78645, 78816, 79430, 79475, 79845, 80597, 80680, 80722, 82743, 82870, 83085, 83102, 84147, 85070, 86341, 86375, 87585, 88820, 89475, 89751, 90987, 92247, 95675, 95896, 96404, 98191, 98722, 100572, 102028, 103021, 104132, 104623, 105333, 108285, 112388, 113693, 114704, 169810, 518732, 593158], [10915, 11291, 11346, 12202, 12295, 13565, 13941, 15334, 15688, 16512, 17329, 17515, 17942, 17978, 17985, 18464, 18631, 18895, 19827, 21234, 21426, 22248, 23848, 24117, 24954, 25088, 25202, 25394, 25661, 26163, 26262, 26379, 26598, 26617, 26714, 27027, 27165, 27168, 27349, 27705, 28357, 28608, 28944, 29518, 29793, 29899, 29959, 30309, 30388, 30600, 30601, 30710, 30714, 30876, 31540, 31782, 31931, 32508, 32594, 32722, 33495, 33570, 33752, 34433, 34471, 34666, 34733, 34859, 35284, 35766, 35891, 36088, 36211, 36242, 36397, 36692, 36903, 37160, 37418, 37870, 38164, 38576, 38927, 39105, 39207, 39289, 39434, 39520, 39851, 39900, 40672, 41209, 41411, 41663, 41881, 42153, 42801, 42818, 42963, 43015, 43174, 43211, 43240, 43569, 43734, 43790, 44067, 44122, 44430, 44510, 44950, 45075, 45083, 45114, 45329, 45609, 46140, 46963, 47109, 47187, 47377, 47500, 47685, 47900, 47975, 48600, 48645, 49171, 49244, 49614, 49740, 49765, 49795, 49809, 50181, 50396, 50405, 50545, 50974, 51067, 51080, 51271, 51580, 51657, 51950, 52386, 53965, 54041, 54497, 54741, 55194, 55491, 55829, 56188, 56824, 57232, 57264, 57492, 57573, 58121, 58339, 58402, 58680, 58815, 58859, 58947, 59031, 59191, 59197, 59269, 59764, 59777, 60019, 60059, 60217, 60338, 60597, 60638, 60807, 61410, 61477, 61780, 61796, 61948, 62227, 62523, 62651, 62938, 63036, 63962, 65308, 66262, 66656, 67342, 67729, 68158, 68266, 68282, 68442, 68819, 69324, 70034, 70084, 72268, 72269, 72713, 72791, 73073, 73269, 74271, 74505, 74802, 75492, 75502, 75967, 76897, 77538, 77590, 78179, 78827, 79883, 80404, 80432, 81466, 83085, 83102, 83215, 83500, 85705, 85707, 85817, 87733, 87976, 89989, 90987, 91715, 94798, 95834, 96680, 97430, 101044, 101152, 103784, 107144, 110835, 111293, 112388, 118684, 542276, 544069, 593158], [10025, 11291, 12328, 13174, 13326, 15110, 15586, 15593, 16461, 16468, 16606, 17329, 17831, 17985, 18315, 18683, 21159, 21406, 21448, 23719, 24208, 24211, 24647, 24759, 24775, 25290, 25423, 26131, 26362, 26956, 27211, 27291, 27300, 27913, 28153, 28273, 28476, 28890, 29112, 29209, 29438, 29893, 29959, 30440, 30499, 30941, 30993, 31332, 31540, 31872, 31999, 32391, 33161, 33177, 33222, 33707, 33870, 34228, 34566, 34582, 34839, 34844, 35348, 35456, 35981, 36211, 37050, 37661, 38003, 38217, 38824, 39276, 39434, 39481, 39540, 39574, 39642, 39872, 40036, 40298, 40552, 41071, 41241, 41775, 41848, 42017, 42360, 42452, 42624, 43184, 43311, 43428, 43979, 44015, 44281, 44341, 44639, 45115, 45116, 45394, 45943, 46014, 46033, 46331, 46558, 46727, 46814, 46873, 47037, 47377, 47738, 47923, 48094, 48138, 48166, 48327, 48546, 48606, 48799, 48907, 48951, 49034, 49304, 49436, 49773, 49863, 50243, 50297, 50643, 50890, 51180, 51202, 51288, 51331, 51343, 51349, 51612, 51717, 51791, 51967, 52152, 52401, 52585, 52741, 52928, 53078, 53449, 53630, 53674, 53734, 53783, 54000, 54076, 54252, 54668, 54758, 55483, 55491, 55564, 55856, 56033, 56209, 56283, 56618, 56824, 56838, 56940, 57009, 57230, 57492, 57573, 57794, 58063, 58188, 58451, 58995, 59059, 59121, 59297, 59497, 59844, 60190, 60696, 61248, 61286, 61328, 61372, 61477, 61743, 62625, 62651, 62693, 64124, 64308, 64423, 64571, 64745, 65045, 65091, 65354, 66080, 66370, 66533, 67612, 67729, 68046, 68772, 68805, 68871, 69172, 70246, 71199, 71822, 73038, 73526, 73960, 76805, 77017, 77473, 77590, 77976, 78160, 78273, 78521, 79321, 80541, 83088, 84392, 85709, 87221, 88033, 89662, 92163, 92410, 92584, 93839, 94937, 95359, 98631, 103726, 106050, 107446, 113013, 114291, 116021, 124081, 124425, 128586, 129919, 169810, 533520], [10284, 11346, 11887, 12254, 12979, 14754, 16366, 16461, 16837, 19459, 19513, 20618, 20979, 21065, 21426, 21737, 22997, 23171, 23317, 23757, 23830, 24071, 24759, 24854, 24918, 25290, 25902, 25952, 26811, 27334, 27913, 28256, 28960, 29315, 30204, 30710, 30714, 31006, 31040, 31162, 31184, 31254, 31538, 31874, 32106, 32244, 32259, 32349, 32969, 33001, 33048, 33177, 33294, 34228, 34416, 34774, 34986, 35348, 35432, 35454, 35500, 35779, 35975, 36373, 37059, 37321, 37411, 37485, 37885, 37941, 38802, 38854, 38890, 39073, 39388, 39427, 39481, 39520, 39876, 39900, 39999, 40150, 40481, 40628, 40738, 41099, 41416, 41839, 41893, 41930, 42047, 42525, 42801, 42818, 42956, 43428, 43692, 44067, 44153, 44633, 44950, 45034, 45087, 45158, 45226, 45300, 45444, 45606, 45865, 46145, 46233, 46698, 46850, 47041, 47099, 47163, 47326, 47394, 47677, 47709, 47923, 47963, 48384, 48506, 48643, 49304, 50336, 50415, 50480, 51271, 51588, 51632, 51681, 52068, 52149, 52309, 52669, 52736, 52880, 52891, 52999, 53797, 54123, 54267, 54299, 54347, 54517, 54606, 54673, 54692, 55126, 55194, 55421, 55952, 55954, 56320, 56392, 56550, 56892, 56909, 57105, 57439, 57580, 58281, 58479, 58621, 58632, 58654, 58815, 58974, 58995, 59127, 59990, 60211, 60338, 61257, 61544, 62441, 62870, 63036, 64106, 64382, 64764, 64840, 65240, 66410, 66869, 67612, 68243, 68245, 68284, 68465, 68534, 69617, 69999, 70149, 70408, 70549, 71150, 71878, 72213, 72257, 72269, 72560, 72679, 74593, 74845, 74989, 75999, 76065, 76312, 76560, 76576, 77061, 77074, 77521, 77661, 78507, 80497, 81408, 82562, 82695, 84518, 85268, 86123, 86158, 86798, 88413, 88820, 89773, 89797, 90716, 95780, 98029, 98468, 98722, 99821, 104440, 106050, 106223, 109704, 110835, 124081, 124317, 130514, 131476, 146570, 169810, 171682, 516882, 549223], [10025, 10250, 10284, 10915, 11473, 11609, 11690, 12428, 12521, 12973, 14819, 15943, 17610, 18809, 19122, 20210, 21120, 21632, 21983, 22435, 22510, 23448, 23778, 23830, 25010, 25067, 25388, 25641, 25708, 25742, 26243, 26352, 26560, 26769, 27682, 27925, 28204, 28256, 28375, 28403, 28476, 28836, 28877, 29186, 29453, 29566, 29744, 29979, 30188, 30596, 30657, 30714, 30751, 31116, 31118, 31752, 32391, 32508, 33186, 33579, 33676, 34277, 34398, 34588, 34654, 34708, 34883, 35181, 35321, 35348, 35975, 36150, 36804, 37059, 37182, 37767, 37941, 38324, 38861, 39155, 39165, 39263, 39372, 39520, 40155, 40183, 40800, 41989, 42032, 42096, 42622, 42638, 42832, 42865, 42897, 42971, 43316, 43326, 43333, 43463, 43569, 43630, 43835, 44015, 44267, 44430, 44666, 44979, 45075, 45115, 45346, 46021, 46256, 46718, 46854, 46855, 47394, 47532, 47670, 47975, 48059, 48394, 48480, 48597, 48600, 48679, 48799, 48891, 48960, 49278, 49423, 49503, 49992, 50153, 50303, 50592, 50678, 50900, 50994, 51293, 51331, 51681, 51967, 52258, 52596, 53440, 53986, 54244, 54299, 54358, 54522, 54804, 54896, 54929, 55208, 55891, 55954, 56033, 56320, 56386, 56483, 57070, 57254, 57517, 57731, 57964, 58419, 58482, 58509, 58689, 58794, 59297, 59319, 59503, 59663, 59894, 60137, 60217, 60334, 60490, 60641, 60659, 60680, 61502, 62809, 63015, 66533, 66705, 67342, 67413, 67502, 68331, 68663, 68819, 69476, 69764, 70084, 70730, 70831, 71221, 72214, 72607, 73420, 73532, 73741, 74404, 74452, 75432, 75492, 76947, 77008, 77681, 77753, 78337, 78645, 79260, 80394, 80404, 81150, 81172, 81539, 82743, 83483, 84710, 85308, 87733, 88129, 88268, 88820, 90292, 90306, 92584, 93425, 95631, 96404, 97586, 98538, 99161, 100493, 103021, 104440, 105333, 110754, 112134, 113013, 115098, 121639, 137450, 176056, 537004, 540405]]}}
|
flysim/src/flysim/validation/chains.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Chain tests on MaleCNS (records/preregistration.md, section 4).
|
| 2 |
+
|
| 3 |
+
# draw the 20 control sets per size once (committed as chain_controls.json)
|
| 4 |
+
python -m flysim.validation.chains draw-controls --connectome DIR
|
| 5 |
+
# run the primary chains and their controls (or --group lc16-alt, section 4.3)
|
| 6 |
+
python -m flysim.validation.chains run --connectome DIR --out runs/chains [--jobs 4]
|
| 7 |
+
# per-trial summary (committed) and the report
|
| 8 |
+
python -m flysim.validation.chains summarize --runs runs/chains \
|
| 9 |
+
--out records/results/chain-tests-trials.json
|
| 10 |
+
python -m flysim.validation.chains judge --trials records/results/chain-tests-trials.json \
|
| 11 |
+
--out report.md
|
| 12 |
+
|
| 13 |
+
DIR is a fetched ``connectome-v1`` (``python -m flysim.artifact fetch --variant full``).
|
| 14 |
+
|
| 15 |
+
Choices section 4 leaves open are fixed here, before any chain run, and listed in
|
| 16 |
+
``records/validation-log.md`` (2026-11-04, chain-test harness):
|
| 17 |
+
|
| 18 |
+
- **Keys.** Stimulus condition ``<stimulus>/<rate>Hz``; control set *k* of size *n*
|
| 19 |
+
``control-<n>/<k>`` (k = 00..19). Seeds follow section 1:
|
| 20 |
+
``trial_rng("chain-tests", key, trial)``.
|
| 21 |
+
- **Control sets** are drawn by :func:`draw_controls`: the pool sorted by
|
| 22 |
+
``bodyId``, one generator per size from ``SeedSequence(20261103, spawn_key=(key(c),
|
| 23 |
+
size))`` with ``c`` the hashed condition string of ``"control-draw"`` in the
|
| 24 |
+
``"chain-tests"`` seed namespace (:func:`flysim.engine.inputs.seed_strings`), then 20
|
| 25 |
+
``choice(replace=False)`` calls.
|
| 26 |
+
- **Latency:** the first spike of any body of the readout at or after onset, over
|
| 27 |
+
the whole 600 ms trial.
|
| 28 |
+
- **C4, "no readout spikes":** none of the three readouts' 8 bodies spikes in
|
| 29 |
+
[400, 600) ms. **Network rate:** every neuron, stimulated ones included, pooled
|
| 30 |
+
over the trials; the same ratio without the stimulated neurons is reported.
|
| 31 |
+
- **Trials judged:** seed set A (trials 0-29). Set B (trials 30-59, 100 Hz) is run
|
| 32 |
+
only for the noise floors of the culling-equivalence test.
|
| 33 |
+
- **Tests:** ``scipy.stats`` defaults: ``mannwhitneyu(..., alternative="greater")``
|
| 34 |
+
and ``wilcoxon(x - y, alternative="greater")``. A test that cannot be computed
|
| 35 |
+
(e.g. all differences zero) fails. Spearman ρ uses average ranks; a constant
|
| 36 |
+
series gives NaN and fails.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
from __future__ import annotations
|
| 40 |
+
|
| 41 |
+
import argparse
|
| 42 |
+
import json
|
| 43 |
+
import multiprocessing as mp
|
| 44 |
+
import sys
|
| 45 |
+
import time
|
| 46 |
+
from dataclasses import dataclass
|
| 47 |
+
from pathlib import Path
|
| 48 |
+
|
| 49 |
+
import numpy as np
|
| 50 |
+
import pyarrow.parquet as pq
|
| 51 |
+
from scipy import stats
|
| 52 |
+
|
| 53 |
+
from flysim import artifact
|
| 54 |
+
from flysim.engine import CpuEngine, ModelParams, SynapseMatrix, poisson_schedule, trial_rng
|
| 55 |
+
from flysim.engine.inputs import seed_strings, string_key
|
| 56 |
+
from flysim.engine.params import W_SYN_MALE
|
| 57 |
+
from flysim.validation.manifest import SET_A, SET_B
|
| 58 |
+
from flysim.validation.metrics import spearman
|
| 59 |
+
from flysim.validation.runs import RunSet
|
| 60 |
+
|
| 61 |
+
EXPERIMENT = "chain-tests"
|
| 62 |
+
VARIANT = "full"
|
| 63 |
+
PARAMS = ModelParams(w_syn=W_SYN_MALE) # input weight stays 0.275 x 250 mV (section 1)
|
| 64 |
+
TRIAL_STEPS = 6000 # 600 ms
|
| 65 |
+
STIM_STEPS = 3000 # stimulus over [0, 300) ms
|
| 66 |
+
LATE = (4000, 6000) # [400, 600) ms
|
| 67 |
+
STIM_S = STIM_STEPS * PARAMS.dt * 1e-3
|
| 68 |
+
LATE_S = (LATE[1] - LATE[0]) * PARAMS.dt * 1e-3
|
| 69 |
+
|
| 70 |
+
RATES = (25.0, 50.0, 100.0, 150.0, 200.0)
|
| 71 |
+
PRIMARY_RATE = 100.0
|
| 72 |
+
READOUTS = ("DNp01", "MDN", "DNp09")
|
| 73 |
+
|
| 74 |
+
CONTROL_SETS = 20
|
| 75 |
+
CONTROL_TRIALS = range(0, 10) # seed set A, trials 0-9
|
| 76 |
+
CONTROL_DRAW_SEED = 20261103
|
| 77 |
+
CONTROL_EXCLUDE = ("LC4", "LC16", "LC9", "LPLC1", "LPLC2")
|
| 78 |
+
CONTROLS_JSON = Path(__file__).with_name("chain_controls.json")
|
| 79 |
+
|
| 80 |
+
C1_MIN_HZ = 2.0
|
| 81 |
+
C3_MIN_RHO = 0.9
|
| 82 |
+
P_MAX = 0.01
|
| 83 |
+
C4_QUIET = 0.95
|
| 84 |
+
C4_RATIO = 0.01
|
| 85 |
+
|
| 86 |
+
#: stimulus name -> source types (right side, somaSide == "R")
|
| 87 |
+
STIMULI = {
|
| 88 |
+
"LC4": ("LC4",),
|
| 89 |
+
"LC16": ("LC16",),
|
| 90 |
+
"LC9": ("LC9",),
|
| 91 |
+
"LC16+LPLC1+LPLC2": ("LC16", "LPLC1", "LPLC2"), # section 4.3, LC16 step 1
|
| 92 |
+
}
|
| 93 |
+
#: run group -> stimuli; a group's controls are the sizes of its stimuli
|
| 94 |
+
GROUPS = {"primary": ("LC4", "LC16", "LC9"), "lc16-alt": ("LC16+LPLC1+LPLC2",)}
|
| 95 |
+
#: stimulus -> size, from sections 4 and 4.3 (checked against the data at run time)
|
| 96 |
+
SIZES = {"LC4": 55, "LC16": 94, "LC9": 115, "LC16+LPLC1+LPLC2": 251}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@dataclass(frozen=True)
|
| 100 |
+
class Chain:
|
| 101 |
+
name: str
|
| 102 |
+
source: str
|
| 103 |
+
readout: str
|
| 104 |
+
beats: tuple[str, ...] # C5: the intended readout must beat these
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
CHAINS = (
|
| 108 |
+
Chain("escape", "LC4", "DNp01", ()),
|
| 109 |
+
Chain("back away", "LC16", "MDN", ("DNp09",)),
|
| 110 |
+
Chain("approach", "LC9", "DNp09", ("DNp01", "MDN")),
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def stim_key(stimulus: str, rate: float) -> str:
|
| 115 |
+
return f"{stimulus}/{rate:g}Hz"
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def control_key(size: int, k: int) -> str:
|
| 119 |
+
return f"control-{size}/{k:02d}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def file_stem(key: str) -> str:
|
| 123 |
+
return key.replace("/", "__").replace("+", "_")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def tasks_of(group: str, set_b: bool = True) -> list[tuple[str, int]]:
|
| 127 |
+
"""Every (condition key, trial) of a run group, in a fixed order.
|
| 128 |
+
|
| 129 |
+
``set_b=False`` leaves out seed set B at 100 Hz (the culling-equivalence runs use
|
| 130 |
+
set A only, section 5).
|
| 131 |
+
"""
|
| 132 |
+
out: list[tuple[str, int]] = []
|
| 133 |
+
for s in GROUPS[group]:
|
| 134 |
+
for r in RATES:
|
| 135 |
+
trials = [*SET_A, *SET_B] if r == PRIMARY_RATE and set_b else list(SET_A)
|
| 136 |
+
out += [(stim_key(s, r), t) for t in trials]
|
| 137 |
+
for s in GROUPS[group]:
|
| 138 |
+
for k in range(CONTROL_SETS):
|
| 139 |
+
out += [(control_key(SIZES[s], k), t) for t in CONTROL_TRIALS]
|
| 140 |
+
return out
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# ----------------------------------------------------------------------------- neurons
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@dataclass(frozen=True)
|
| 147 |
+
class Neurons:
|
| 148 |
+
body: np.ndarray # int64, index -> bodyId
|
| 149 |
+
type: np.ndarray # object
|
| 150 |
+
side: np.ndarray # object (somaSide)
|
| 151 |
+
superclass: np.ndarray # object
|
| 152 |
+
sign: np.ndarray # int8
|
| 153 |
+
|
| 154 |
+
@classmethod
|
| 155 |
+
def load(cls, directory: Path) -> Neurons:
|
| 156 |
+
t = pq.read_table(directory / "neurons.parquet",
|
| 157 |
+
columns=["idx", "bodyId", "type", "somaSide", "superclass", "sign"])
|
| 158 |
+
if not np.array_equal(t["idx"].to_numpy(), np.arange(t.num_rows)):
|
| 159 |
+
raise ValueError("neurons.parquet is not in index order")
|
| 160 |
+
obj = lambda c: np.asarray(t[c].to_pylist(), dtype=object) # noqa: E731
|
| 161 |
+
return cls(t["bodyId"].to_numpy().astype(np.int64), obj("type"), obj("somaSide"),
|
| 162 |
+
obj("superclass"), t["sign"].to_numpy().astype(np.int8))
|
| 163 |
+
|
| 164 |
+
def of_types(self, types: tuple[str, ...], side: str | None = None) -> np.ndarray:
|
| 165 |
+
m = np.isin(self.type, list(types))
|
| 166 |
+
if side is not None:
|
| 167 |
+
m &= self.side == side
|
| 168 |
+
return np.flatnonzero(m).astype(np.int32)
|
| 169 |
+
|
| 170 |
+
def index_of(self, bodies: list[int] | np.ndarray) -> np.ndarray:
|
| 171 |
+
bodies = np.asarray(bodies, dtype=np.int64)
|
| 172 |
+
order = np.argsort(self.body)
|
| 173 |
+
pos = order[np.searchsorted(self.body, bodies, sorter=order)]
|
| 174 |
+
if not np.array_equal(self.body[pos], bodies):
|
| 175 |
+
raise KeyError("bodyId not in neurons.parquet")
|
| 176 |
+
return np.sort(pos).astype(np.int32)
|
| 177 |
+
|
| 178 |
+
def control_pool(self) -> np.ndarray:
|
| 179 |
+
"""bodyIds of right-side, sign +1 visual projection neurons outside the chains
|
| 180 |
+
(section 4.1)."""
|
| 181 |
+
m = ((self.superclass == "visual_projection") & (self.side == "R") & (self.sign == 1)
|
| 182 |
+
& ~np.isin(self.type, list(CONTROL_EXCLUDE)))
|
| 183 |
+
return np.sort(self.body[m])
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def draw_controls(neurons: Neurons) -> dict:
|
| 187 |
+
pool = neurons.control_pool()
|
| 188 |
+
sets: dict[str, list[list[int]]] = {}
|
| 189 |
+
for size in sorted(set(SIZES.values())):
|
| 190 |
+
rng = np.random.default_rng(np.random.SeedSequence(
|
| 191 |
+
CONTROL_DRAW_SEED,
|
| 192 |
+
spawn_key=(string_key(seed_strings(EXPERIMENT, "control-draw")[1]), size)))
|
| 193 |
+
sets[str(size)] = [sorted(int(b) for b in rng.choice(pool, size, replace=False))
|
| 194 |
+
for _ in range(CONTROL_SETS)]
|
| 195 |
+
return {"rules": "records/preregistration.md, section 4.1", "seed": CONTROL_DRAW_SEED,
|
| 196 |
+
"pool": "visual_projection, somaSide R, sign +1, type not in "
|
| 197 |
+
+ ", ".join(CONTROL_EXCLUDE),
|
| 198 |
+
"pool_size": len(pool), "sets": sets}
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def load_controls() -> dict:
|
| 202 |
+
return json.loads(CONTROLS_JSON.read_text())
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def targets_of(key: str, neurons: Neurons, controls: dict) -> np.ndarray:
|
| 206 |
+
what, last = key.split("/")
|
| 207 |
+
if what.startswith("control-"):
|
| 208 |
+
return neurons.index_of(controls["sets"][what.removeprefix("control-")][int(last)])
|
| 209 |
+
t = neurons.of_types(STIMULI[what], side="R")
|
| 210 |
+
if len(t) != SIZES[what]:
|
| 211 |
+
raise ValueError(f"{what}: {len(t)} right-side neurons, "
|
| 212 |
+
f"the preregistration says {SIZES[what]}")
|
| 213 |
+
return t
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def rate_of_key(key: str) -> float:
|
| 217 |
+
what, last = key.split("/")
|
| 218 |
+
return PRIMARY_RATE if what.startswith("control-") else float(last.removesuffix("Hz"))
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# ----------------------------------------------------------------------------- run
|
| 222 |
+
|
| 223 |
+
_w: dict = {}
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _init(connectome: str, variant: str = VARIANT) -> None:
|
| 227 |
+
d = Path(connectome)
|
| 228 |
+
eng = CpuEngine(np.float32, skip_rest=False) # the reference kernel the gate ran on
|
| 229 |
+
eng.load(SynapseMatrix.from_connectome(artifact.load(d, variant)), PARAMS)
|
| 230 |
+
_w.update(engine=eng, neurons=Neurons.load(d), controls=load_controls())
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def run_trial(key: str, trial: int, engine: CpuEngine, neurons: Neurons, controls: dict
|
| 234 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 235 |
+
targets = targets_of(key, neurons, controls)
|
| 236 |
+
rng = trial_rng(EXPERIMENT, key, trial)
|
| 237 |
+
engine.reset()
|
| 238 |
+
engine.schedule_inputs(poisson_schedule(rng, targets, rate_of_key(key), 0, STIM_STEPS,
|
| 239 |
+
PARAMS.dt))
|
| 240 |
+
engine.advance_to(TRIAL_STEPS)
|
| 241 |
+
return engine.spikes_since(0)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def _task(a: tuple[str, int]) -> tuple[str, int, np.ndarray, np.ndarray, float]:
|
| 245 |
+
t0 = time.perf_counter()
|
| 246 |
+
s, n = run_trial(a[0], a[1], _w["engine"], _w["neurons"], _w["controls"])
|
| 247 |
+
return a[0], a[1], s, n, time.perf_counter() - t0
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def cmd_run(a: argparse.Namespace) -> int:
|
| 251 |
+
tasks = tasks_of(a.group, set_b=not a.no_set_b)
|
| 252 |
+
if a.only:
|
| 253 |
+
tasks = [t for t in tasks if t[0] in a.only]
|
| 254 |
+
want: dict[str, int] = {}
|
| 255 |
+
for k, _ in tasks:
|
| 256 |
+
want[k] = want.get(k, 0) + 1
|
| 257 |
+
done: dict[str, list] = {k: [] for k in want}
|
| 258 |
+
n_neurons = len(Neurons.load(a.connectome).body)
|
| 259 |
+
meta = {"engine": "flysim-cpu", "numerics": "float32", "variant": a.variant,
|
| 260 |
+
"params": PARAMS.to_dict(), "experiment": EXPERIMENT}
|
| 261 |
+
print(f"{len(tasks)} trials in {len(want)} conditions, {a.jobs} workers", flush=True)
|
| 262 |
+
secs: list[float] = []
|
| 263 |
+
with mp.get_context("fork").Pool(a.jobs, initializer=_init,
|
| 264 |
+
initargs=(str(a.connectome), a.variant)) as pool:
|
| 265 |
+
for key, trial, s, n, dt in pool.imap_unordered(_task, tasks, chunksize=2):
|
| 266 |
+
done[key].append((trial, s, n))
|
| 267 |
+
secs.append(dt)
|
| 268 |
+
if len(done[key]) == want[key]:
|
| 269 |
+
RunSet.from_trials(done[key], n_neurons, TRIAL_STEPS, PARAMS.dt,
|
| 270 |
+
{**meta, "key": key}).save(a.out / f"{file_stem(key)}.npz")
|
| 271 |
+
print(f" {key}: {sum(len(x[1]) for x in done[key])} spikes, "
|
| 272 |
+
f"median {np.median(secs):.2f} s/trial", flush=True)
|
| 273 |
+
return 0
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# ----------------------------------------------------------------------------- summary
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def summarize_runset(rs: RunSet, key: str, neurons: Neurons, controls: dict) -> dict:
|
| 280 |
+
"""Per trial: readout body counts in [0, 300), first readout spike, late activity."""
|
| 281 |
+
bodies = {r: neurons.of_types((r,)) for r in READOUTS}
|
| 282 |
+
all_ro = np.concatenate(list(bodies.values()))
|
| 283 |
+
stim = targets_of(key, neurons, controls)
|
| 284 |
+
out: dict = {"key": key, "trials": rs.trials.tolist(),
|
| 285 |
+
"bodies": {r: [int(neurons.body[i]) for i in b] for r, b in bodies.items()},
|
| 286 |
+
"sides": {r: [neurons.side[i] for i in b] for r, b in bodies.items()},
|
| 287 |
+
"counts": {r: [] for r in READOUTS}, "first_ms": {r: [] for r in READOUTS},
|
| 288 |
+
"late_readout": [], "net_stim": [], "net_late": [],
|
| 289 |
+
"net_stim_nonstim": [], "net_late_nonstim": []}
|
| 290 |
+
for k in range(len(rs.trials)):
|
| 291 |
+
s, n = rs.trial_spikes(k)
|
| 292 |
+
early, late = s < STIM_STEPS, (s >= LATE[0]) & (s < LATE[1])
|
| 293 |
+
nonstim = ~np.isin(n, stim)
|
| 294 |
+
for r, b in bodies.items():
|
| 295 |
+
out["counts"][r].append([int(np.sum(early & (n == i))) for i in b])
|
| 296 |
+
hit = s[np.isin(n, b)]
|
| 297 |
+
out["first_ms"][r].append(round(float(hit.min()) * PARAMS.dt, 4) if len(hit)
|
| 298 |
+
else None)
|
| 299 |
+
out["late_readout"].append(bool(np.any(late & np.isin(n, all_ro))))
|
| 300 |
+
out["net_stim"].append(int(early.sum()))
|
| 301 |
+
out["net_late"].append(int(late.sum()))
|
| 302 |
+
out["net_stim_nonstim"].append(int((early & nonstim).sum()))
|
| 303 |
+
out["net_late_nonstim"].append(int((late & nonstim).sum()))
|
| 304 |
+
return out
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def cmd_summarize(a: argparse.Namespace) -> int:
|
| 308 |
+
neurons, controls = Neurons.load(a.connectome), load_controls()
|
| 309 |
+
conds = {}
|
| 310 |
+
variants = set()
|
| 311 |
+
for p in sorted(a.runs.glob("*.npz")):
|
| 312 |
+
rs = RunSet.load(p)
|
| 313 |
+
key = rs.meta["key"]
|
| 314 |
+
variants.add(rs.meta.get("variant", VARIANT))
|
| 315 |
+
conds[key] = summarize_runset(rs, key, neurons, controls)
|
| 316 |
+
if len(variants) > 1:
|
| 317 |
+
raise ValueError(f"runs mix matrix variants: {sorted(variants)}")
|
| 318 |
+
out = {"rules": "records/preregistration.md, section 4", "conditions": conds}
|
| 319 |
+
if variants and variants != {VARIANT}:
|
| 320 |
+
out["variant"] = variants.pop()
|
| 321 |
+
a.out.write_text(json.dumps(out) + "\n")
|
| 322 |
+
print(f"{len(conds)} conditions -> {a.out}")
|
| 323 |
+
return 0
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# ----------------------------------------------------------------------------- judge
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@dataclass
|
| 330 |
+
class Crit:
|
| 331 |
+
name: str
|
| 332 |
+
value: str
|
| 333 |
+
rule: str
|
| 334 |
+
passed: bool
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class Trials:
|
| 338 |
+
"""The committed per-trial summary, with the measures of section 4."""
|
| 339 |
+
|
| 340 |
+
def __init__(self, data: dict):
|
| 341 |
+
self.c = data["conditions"]
|
| 342 |
+
|
| 343 |
+
def has(self, key: str) -> bool:
|
| 344 |
+
return key in self.c
|
| 345 |
+
|
| 346 |
+
def _idx(self, key: str, trials: range | None) -> np.ndarray:
|
| 347 |
+
tr = np.asarray(self.c[key]["trials"])
|
| 348 |
+
return np.flatnonzero(np.isin(tr, list(trials))) if trials is not None \
|
| 349 |
+
else np.arange(len(tr))
|
| 350 |
+
|
| 351 |
+
def rates(self, key: str, readout: str, trials: range | None = SET_A,
|
| 352 |
+
side: str | None = None) -> np.ndarray:
|
| 353 |
+
"""Per trial: spikes over [0, 300) / 0.3 s / number of bodies (of that side)."""
|
| 354 |
+
cnt = np.asarray(self.c[key]["counts"][readout], dtype=float)[self._idx(key, trials)]
|
| 355 |
+
if side is not None:
|
| 356 |
+
cnt = cnt[:, np.asarray(self.c[key]["sides"][readout]) == side]
|
| 357 |
+
return cnt.sum(axis=1) / STIM_S / cnt.shape[1]
|
| 358 |
+
|
| 359 |
+
def latency(self, key: str, readout: str, trials: range | None = SET_A) -> float:
|
| 360 |
+
f = [self.c[key]["first_ms"][readout][i] for i in self._idx(key, trials)]
|
| 361 |
+
f = [x for x in f if x is not None]
|
| 362 |
+
return float(np.median(f)) if f else float("nan")
|
| 363 |
+
|
| 364 |
+
def stability(self, key: str, trials: range | None = SET_A) -> tuple[float, float, float]:
|
| 365 |
+
i = self._idx(key, trials)
|
| 366 |
+
c = self.c[key]
|
| 367 |
+
quiet = 1.0 - float(np.mean(np.asarray(c["late_readout"])[i]))
|
| 368 |
+
|
| 369 |
+
def ratio(a: str, b: str) -> float:
|
| 370 |
+
late = np.sum(np.asarray(c[b])[i]) / LATE_S
|
| 371 |
+
early = np.sum(np.asarray(c[a])[i]) / STIM_S
|
| 372 |
+
return float(late / early) if early else float("nan")
|
| 373 |
+
|
| 374 |
+
return quiet, ratio("net_stim", "net_late"), ratio("net_stim_nonstim", "net_late_nonstim")
|
| 375 |
+
|
| 376 |
+
def control_q95(self, size: int, readout: str) -> tuple[float, int]:
|
| 377 |
+
means = [self.rates(control_key(size, k), readout, CONTROL_TRIALS).mean()
|
| 378 |
+
for k in range(CONTROL_SETS) if self.has(control_key(size, k))]
|
| 379 |
+
return (float(np.quantile(means, 0.95)) if len(means) == CONTROL_SETS
|
| 380 |
+
else float("nan")), len(means)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _p(test, *args) -> float:
|
| 384 |
+
try:
|
| 385 |
+
p = float(test(*args, alternative="greater").pvalue)
|
| 386 |
+
except ValueError:
|
| 387 |
+
return float("nan")
|
| 388 |
+
return p
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def judge_chain(t: Trials, chain: Chain, stimulus: str, *, relative: bool = False
|
| 392 |
+
) -> list[Crit]:
|
| 393 |
+
"""Section 4.2 criteria for one chain and stimulus. ``relative``: the section 4.3
|
| 394 |
+
relative reading."""
|
| 395 |
+
k100 = stim_key(stimulus, PRIMARY_RATE)
|
| 396 |
+
ro = chain.readout
|
| 397 |
+
r100 = t.rates(k100, ro).mean()
|
| 398 |
+
out: list[Crit] = []
|
| 399 |
+
if not relative:
|
| 400 |
+
out.append(Crit("C1 activation", f"{r100:.2f} Hz", f"≥ {C1_MIN_HZ:g} Hz",
|
| 401 |
+
bool(r100 >= C1_MIN_HZ)))
|
| 402 |
+
q95, n = t.control_q95(SIZES[stimulus], ro)
|
| 403 |
+
c2 = bool(r100 > q95) and (not relative or r100 > 0)
|
| 404 |
+
out.append(Crit("C2 beats control", f"{r100:.2f} Hz",
|
| 405 |
+
f"> {q95:.2f} Hz (95th pct of {n} control sets)"
|
| 406 |
+
+ (" and > 0" if relative else ""), c2))
|
| 407 |
+
means = [t.rates(stim_key(stimulus, r), ro).mean() for r in RATES]
|
| 408 |
+
rho = spearman(np.asarray(RATES), np.asarray(means))
|
| 409 |
+
p_mw = _p(stats.mannwhitneyu, t.rates(stim_key(stimulus, 200.0), ro),
|
| 410 |
+
t.rates(stim_key(stimulus, 25.0), ro))
|
| 411 |
+
out.append(Crit("C3 dose response",
|
| 412 |
+
f"ρ = {rho:.3f}; rates " + ", ".join(f"{m:.2f}" for m in means)
|
| 413 |
+
+ f" Hz; MWU p = {p_mw:.2g}",
|
| 414 |
+
f"ρ ≥ {C3_MIN_RHO}, p < {P_MAX}",
|
| 415 |
+
bool(rho >= C3_MIN_RHO) and bool(p_mw < P_MAX)))
|
| 416 |
+
quiet, ratio, ratio_ns = t.stability(k100)
|
| 417 |
+
out.append(Crit("C4 stability",
|
| 418 |
+
f"quiet {quiet:.0%} of trials; network {ratio:.4f} "
|
| 419 |
+
f"(non-stimulated only: {ratio_ns:.4f})",
|
| 420 |
+
f"quiet ≥ {C4_QUIET:.0%}, ratio ≤ {C4_RATIO}",
|
| 421 |
+
bool(quiet >= C4_QUIET) and bool(ratio <= C4_RATIO)))
|
| 422 |
+
for other in chain.beats:
|
| 423 |
+
d = t.rates(k100, ro) - t.rates(k100, other)
|
| 424 |
+
p = _p(stats.wilcoxon, d)
|
| 425 |
+
out.append(Crit(f"C5 {ro} > {other}",
|
| 426 |
+
f"{r100:.2f} vs {t.rates(k100, other).mean():.2f} Hz; p = {p:.2g}",
|
| 427 |
+
f"Wilcoxon one-sided p < {P_MAX}", bool(p < P_MAX)))
|
| 428 |
+
return out
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def specificity_margin(t: Trials, stimulus: str) -> float:
|
| 432 |
+
k = stim_key(stimulus, PRIMARY_RATE)
|
| 433 |
+
return float(t.rates(k, "MDN").mean() - t.rates(k, "DNp09").mean())
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
@dataclass
|
| 437 |
+
class Attempt:
|
| 438 |
+
label: str
|
| 439 |
+
stimulus: str
|
| 440 |
+
relative: bool
|
| 441 |
+
crits: list[Crit] | None # None: not run (data missing)
|
| 442 |
+
|
| 443 |
+
@property
|
| 444 |
+
def passed(self) -> bool:
|
| 445 |
+
return self.crits is not None and all(c.passed for c in self.crits)
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def _ready(t: Trials, stimulus: str) -> bool:
|
| 449 |
+
keys = [stim_key(stimulus, r) for r in RATES]
|
| 450 |
+
keys += [control_key(SIZES[stimulus], k) for k in range(CONTROL_SETS)]
|
| 451 |
+
return all(t.has(k) for k in keys)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def _attempt(t: Trials, chain: Chain, label: str, stimulus: str, relative: bool) -> Attempt:
|
| 455 |
+
crits = judge_chain(t, chain, stimulus, relative=relative) if _ready(t, stimulus) else None
|
| 456 |
+
return Attempt(label, stimulus, relative, crits)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def judge_all(t: Trials) -> dict[str, list[Attempt]]:
|
| 460 |
+
"""Each chain's attempts in the section 4.3 order, stopping at the first pass."""
|
| 461 |
+
out: dict[str, list[Attempt]] = {}
|
| 462 |
+
for ch in CHAINS:
|
| 463 |
+
steps = [_attempt(t, ch, "primary", ch.source, False)]
|
| 464 |
+
if not steps[0].passed and ch.source == "LC9":
|
| 465 |
+
steps.append(_attempt(t, ch, "alternative: relative reading", "LC9", True))
|
| 466 |
+
if not steps[0].passed and ch.source == "LC16":
|
| 467 |
+
alt = "LC16+LPLC1+LPLC2"
|
| 468 |
+
steps.append(_attempt(t, ch, "alternative step 1: LC16 + LPLC1 + LPLC2", alt,
|
| 469 |
+
False))
|
| 470 |
+
if not steps[-1].passed and steps[-1].crits is not None:
|
| 471 |
+
worse = specificity_margin(t, alt) < specificity_margin(t, "LC16")
|
| 472 |
+
steps.append(_attempt(t, ch, "alternative step 2: relative reading",
|
| 473 |
+
"LC16" if worse else alt, True))
|
| 474 |
+
out[ch.source] = steps
|
| 475 |
+
return out
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def render(t: Trials, attempts: dict[str, list[Attempt]]) -> str:
|
| 479 |
+
lines = ["# Chain tests on MaleCNS (preregistration, section 4)", "",
|
| 480 |
+
"Judged against `records/preregistration.md` as committed before the runs. "
|
| 481 |
+
f"Matrix `connectome-v1` `{VARIANT}`, w_syn = {PARAMS.w_syn:.4f} mV "
|
| 482 |
+
"(R = 1.7505, section 3), float32. Criteria C1 to C5 and the alternatives are "
|
| 483 |
+
"defined in section 4.2 and 4.3 of the preregistration.", "",
|
| 484 |
+
"> The engine check against Brian2 **failed** under the original rule "
|
| 485 |
+
"(preregistration, section 2.3). We decided to proceed with that failure on "
|
| 486 |
+
"record. Every result below is on our engine only and carries that decision.",
|
| 487 |
+
""]
|
| 488 |
+
for ch in CHAINS:
|
| 489 |
+
steps = attempts[ch.source]
|
| 490 |
+
final = next((s for s in steps if s.passed), None)
|
| 491 |
+
verdict = (f"PASS ({final.label})" if final else
|
| 492 |
+
"NOT JUDGED: alternative not run yet" if steps[-1].crits is None else
|
| 493 |
+
"FAIL")
|
| 494 |
+
lines += [f"## {ch.source} → {ch.readout} ({ch.name}): **{verdict}**", ""]
|
| 495 |
+
for s in steps:
|
| 496 |
+
lines += [f"### {s.label}: stimulus {s.stimulus}"
|
| 497 |
+
+ (" (relative reading)" if s.relative else ""), ""]
|
| 498 |
+
if s.crits is None:
|
| 499 |
+
lines += ["Not run: `python -m flysim.validation.chains run --group lc16-alt`.",
|
| 500 |
+
""]
|
| 501 |
+
continue
|
| 502 |
+
lines += ["| Criterion | Value | Rule | Pass |", "|---|---|---|---|"]
|
| 503 |
+
lines += [f"| {c.name} | {c.value} | {c.rule} | {'✔' if c.passed else '✘'} |"
|
| 504 |
+
for c in s.crits]
|
| 505 |
+
lines += ["", _readout_table(t, s.stimulus), ""]
|
| 506 |
+
return "\n".join(lines)
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def _readout_table(t: Trials, stimulus: str) -> str:
|
| 510 |
+
rows = ["| Rate | " + " | ".join(f"{r} (Hz; L / R)" for r in READOUTS)
|
| 511 |
+
+ " | first spike, median (ms): " + " / ".join(READOUTS) + " |",
|
| 512 |
+
"|---|" + "---:|" * (len(READOUTS) + 1)]
|
| 513 |
+
for rate in RATES:
|
| 514 |
+
k = stim_key(stimulus, rate)
|
| 515 |
+
cells = []
|
| 516 |
+
for r in READOUTS:
|
| 517 |
+
cells.append(f"{t.rates(k, r).mean():.2f} ({t.rates(k, r, side='L').mean():.2f}"
|
| 518 |
+
f" / {t.rates(k, r, side='R').mean():.2f})")
|
| 519 |
+
lat = " / ".join(f"{t.latency(k, r):.1f}" for r in READOUTS)
|
| 520 |
+
rows.append(f"| {rate:g} Hz | " + " | ".join(cells) + f" | {lat} |")
|
| 521 |
+
return "\n".join(rows)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def cmd_judge(a: argparse.Namespace) -> int:
|
| 525 |
+
t = Trials(json.loads(a.trials.read_text()))
|
| 526 |
+
att = judge_all(t)
|
| 527 |
+
text = render(t, att)
|
| 528 |
+
if a.out:
|
| 529 |
+
a.out.write_text(text + "\n")
|
| 530 |
+
print(text)
|
| 531 |
+
return 0
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def cmd_draw(a: argparse.Namespace) -> int:
|
| 535 |
+
CONTROLS_JSON.write_text(json.dumps(draw_controls(Neurons.load(a.connectome))) + "\n")
|
| 536 |
+
print(f"wrote {CONTROLS_JSON}")
|
| 537 |
+
return 0
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def main(argv: list[str] | None = None) -> int:
|
| 541 |
+
p = argparse.ArgumentParser(prog="python -m flysim.validation.chains")
|
| 542 |
+
sub = p.add_subparsers(dest="cmd", required=True)
|
| 543 |
+
d = sub.add_parser("draw-controls")
|
| 544 |
+
d.add_argument("--connectome", type=Path, required=True)
|
| 545 |
+
r = sub.add_parser("run")
|
| 546 |
+
r.add_argument("--connectome", type=Path, required=True)
|
| 547 |
+
r.add_argument("--out", type=Path, required=True)
|
| 548 |
+
r.add_argument("--group", choices=sorted(GROUPS), default="primary")
|
| 549 |
+
r.add_argument("--variant", choices=artifact.VARIANTS, default=VARIANT,
|
| 550 |
+
help="matrix variant (the culling-equivalence test runs the culled ones)")
|
| 551 |
+
r.add_argument("--no-set-b", action="store_true",
|
| 552 |
+
help="leave out seed set B at 100 Hz (culling equivalence: set A only)")
|
| 553 |
+
r.add_argument("--jobs", type=int, default=mp.cpu_count())
|
| 554 |
+
r.add_argument("--only", nargs="*", help="condition keys")
|
| 555 |
+
s = sub.add_parser("summarize")
|
| 556 |
+
s.add_argument("--connectome", type=Path, required=True)
|
| 557 |
+
s.add_argument("--runs", type=Path, required=True)
|
| 558 |
+
s.add_argument("--out", type=Path, required=True)
|
| 559 |
+
j = sub.add_parser("judge")
|
| 560 |
+
j.add_argument("--trials", type=Path, required=True)
|
| 561 |
+
j.add_argument("--out", type=Path)
|
| 562 |
+
a = p.parse_args(argv)
|
| 563 |
+
return {"draw-controls": cmd_draw, "run": cmd_run, "summarize": cmd_summarize,
|
| 564 |
+
"judge": cmd_judge}[a.cmd](a)
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
if __name__ == "__main__":
|
| 568 |
+
sys.exit(main())
|
flysim/src/flysim/validation/culling.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Culling (pruning) equivalence test (records/preregistration.md, section 5).
|
| 2 |
+
|
| 3 |
+
# run every section 4 condition that was run on full, set A only, on one culled variant
|
| 4 |
+
python -m flysim.validation.culling run --connectome DIR --variant min3 --out runs/culling/min3
|
| 5 |
+
python -m flysim.validation.chains summarize --connectome DIR --runs runs/culling/min3 \
|
| 6 |
+
--out records/results/culling-min3-trials.json
|
| 7 |
+
# judge every variant against full's committed record
|
| 8 |
+
python -m flysim.validation.culling judge --full records/results/chain-tests-trials.json \
|
| 9 |
+
--variant records/results/culling-min2-trials.json ... \
|
| 10 |
+
--out records/results/culling-equivalence.md
|
| 11 |
+
|
| 12 |
+
DIR is a fetched ``connectome-v1`` holding ``matrix-<variant>.tar.zst``.
|
| 13 |
+
|
| 14 |
+
Choices section 5 leaves open are fixed here, before any variant run, and listed in
|
| 15 |
+
``records/validation-log.md`` (2026-11-05, culling-equivalence harness):
|
| 16 |
+
|
| 17 |
+
- **Conditions.** Every stimulus run on ``full`` in the chain tests (LC4, LC16, LC9
|
| 18 |
+
and LC16 + LPLC1 + LPLC2) at all five rates, set A (trials 0-29), with the same
|
| 19 |
+
keys and seeds as the chain tests. The 20 control sets of each size are run on
|
| 20 |
+
the variant too (trials 0-9), so that C2 is judged with the variant's own
|
| 21 |
+
control, as a section 4.2 judgement on that matrix needs.
|
| 22 |
+
- **Reference.** ``full``'s values are those of the committed chain-test record
|
| 23 |
+
(``records/results/chain-tests-trials.json``); ``full`` is not rerun.
|
| 24 |
+
- **Noise floors.** Per stimulus and readout, from ``full``'s 60 trials (sets A
|
| 25 |
+
and B) at 100 Hz, with :func:`flysim.validation.metrics.d95` and the section 2.3
|
| 26 |
+
splits (``default_rng(20261103)``, 1,000 permutations); one floor for every rate.
|
| 27 |
+
A split where a half has no first spike is left out of the latency floor.
|
| 28 |
+
- **Rate check.** Every readout (DNp01, MDN, DNp09), every stimulus and rate:
|
| 29 |
+
|mean set-A rate(variant) − rate(full)| ≤ max(d95, 1 Hz).
|
| 30 |
+
- **Latency check.** The section 4 latency (median first spike over the set-A
|
| 31 |
+
trials that have one). Checked where it is defined on both matrices:
|
| 32 |
+
|Δ| ≤ max(d95, 2 ms). Defined on one matrix only counts as a failure, since
|
| 33 |
+
the readout then fires on one and is silent on the other.
|
| 34 |
+
- **Same chain result.** Every attempt judged on ``full`` (primary and the section
|
| 35 |
+
4.3 steps, with the same stimulus and reading) is judged on the variant with the
|
| 36 |
+
same code, and its pass or fail must match. That also makes each chain's final
|
| 37 |
+
verdict match.
|
| 38 |
+
- A variant passes when every check passes; one failure fails it as a whole.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
from __future__ import annotations
|
| 42 |
+
|
| 43 |
+
import argparse
|
| 44 |
+
import json
|
| 45 |
+
import sys
|
| 46 |
+
from collections.abc import Callable
|
| 47 |
+
from dataclasses import dataclass
|
| 48 |
+
from pathlib import Path
|
| 49 |
+
|
| 50 |
+
import numpy as np
|
| 51 |
+
|
| 52 |
+
from flysim.validation import chains as ch
|
| 53 |
+
from flysim.validation.manifest import SET_A, SET_B
|
| 54 |
+
from flysim.validation.metrics import d95, latency_of, splits
|
| 55 |
+
|
| 56 |
+
CULLED = ("min2", "min3", "min5", "min10")
|
| 57 |
+
MIN_RATE_TOL_HZ = 1.0
|
| 58 |
+
MIN_LATENCY_TOL_MS = 2.0
|
| 59 |
+
POOL = range(SET_A.start, SET_B.stop) # trials 0-59
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def stimuli_of(full: ch.Trials) -> list[str]:
|
| 63 |
+
"""Stimuli run on full at every rate, in the section 4 order."""
|
| 64 |
+
return [s for s in ch.STIMULI if all(full.has(ch.stim_key(s, r)) for r in ch.RATES)]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def tasks(full: ch.Trials) -> list[tuple[str, int]]:
|
| 68 |
+
out: list[tuple[str, int]] = []
|
| 69 |
+
for group, members in ch.GROUPS.items():
|
| 70 |
+
if all(s in stimuli_of(full) for s in members):
|
| 71 |
+
out += ch.tasks_of(group, set_b=False)
|
| 72 |
+
return out
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# ----------------------------------------------------------------------------- floors
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@dataclass(frozen=True)
|
| 79 |
+
class Floor:
|
| 80 |
+
rate_hz: float
|
| 81 |
+
latency_ms: float # NaN if no split has a latency in both halves
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def noise_floors(full: ch.Trials, stimulus: str) -> dict[str, Floor]:
|
| 85 |
+
key = ch.stim_key(stimulus, ch.PRIMARY_RATE)
|
| 86 |
+
if sorted(full.c[key]["trials"]) != list(POOL):
|
| 87 |
+
raise ValueError(f"{key}: full needs trials 0-59 for the noise floors")
|
| 88 |
+
perms = splits(len(POOL))
|
| 89 |
+
out = {}
|
| 90 |
+
for ro in ch.READOUTS:
|
| 91 |
+
# the pool in trial order 0-59, whatever order the record stores them in
|
| 92 |
+
order = np.argsort(full.c[key]["trials"])
|
| 93 |
+
rates = full.rates(key, ro, None)[order]
|
| 94 |
+
first = np.array([np.nan if (x := full.c[key]["first_ms"][ro][i]) is None else x
|
| 95 |
+
for i in order], dtype=float)
|
| 96 |
+
out[ro] = Floor(d95(rates, np.mean, perms), d95(first, latency_of, perms))
|
| 97 |
+
return out
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# ----------------------------------------------------------------------------- judge
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclass
|
| 104 |
+
class Check:
|
| 105 |
+
stimulus: str
|
| 106 |
+
rate: float | None # None: a chain-test (section 4.2) attempt
|
| 107 |
+
what: str
|
| 108 |
+
full: str
|
| 109 |
+
variant: str
|
| 110 |
+
tol: str
|
| 111 |
+
passed: bool
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def compare(full: ch.Trials, var: ch.Trials) -> list[Check]:
|
| 115 |
+
out: list[Check] = []
|
| 116 |
+
for s in stimuli_of(full):
|
| 117 |
+
floors = noise_floors(full, s)
|
| 118 |
+
for r in ch.RATES:
|
| 119 |
+
k = ch.stim_key(s, r)
|
| 120 |
+
for ro in ch.READOUTS:
|
| 121 |
+
fl = floors[ro]
|
| 122 |
+
rf, rv = full.rates(k, ro).mean(), var.rates(k, ro).mean()
|
| 123 |
+
tol = max(fl.rate_hz, MIN_RATE_TOL_HZ)
|
| 124 |
+
out.append(Check(s, r, f"{ro} rate", f"{rf:.2f} Hz", f"{rv:.2f} Hz",
|
| 125 |
+
f"|Δ| {abs(rv - rf):.3f} ≤ {tol:.3f} Hz",
|
| 126 |
+
bool(abs(rv - rf) <= tol)))
|
| 127 |
+
lf, lv = full.latency(k, ro), var.latency(k, ro)
|
| 128 |
+
if np.isnan(lf) and np.isnan(lv):
|
| 129 |
+
continue
|
| 130 |
+
tol = max(0.0 if np.isnan(fl.latency_ms) else fl.latency_ms, MIN_LATENCY_TOL_MS)
|
| 131 |
+
if np.isnan(lf) or np.isnan(lv):
|
| 132 |
+
out.append(Check(s, r, f"{ro} latency", f"{lf:.1f} ms", f"{lv:.1f} ms",
|
| 133 |
+
"defined on one matrix only", False))
|
| 134 |
+
continue
|
| 135 |
+
out.append(Check(s, r, f"{ro} latency", f"{lf:.1f} ms", f"{lv:.1f} ms",
|
| 136 |
+
f"|Δ| {abs(lv - lf):.2f} ≤ {tol:.2f} ms",
|
| 137 |
+
bool(abs(lv - lf) <= tol)))
|
| 138 |
+
for chain in ch.CHAINS:
|
| 139 |
+
for att in ch.judge_all(full)[chain.source]:
|
| 140 |
+
if att.crits is None:
|
| 141 |
+
continue
|
| 142 |
+
v = ch._attempt(var, chain, att.label, att.stimulus, att.relative)
|
| 143 |
+
vp = "not run" if v.crits is None else ("PASS" if v.passed else "FAIL")
|
| 144 |
+
failed = [] if v.crits is None else [c.name for c in v.crits if not c.passed]
|
| 145 |
+
out.append(Check(att.stimulus, None, f"chain result {chain.source} {att.label}",
|
| 146 |
+
"PASS" if att.passed else "FAIL",
|
| 147 |
+
vp + (f" ({', '.join(failed)})" if failed else ""),
|
| 148 |
+
"same result", v.crits is not None and v.passed == att.passed))
|
| 149 |
+
return out
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _tally(cs: list[Check], pred: Callable[[Check], bool]) -> str:
|
| 153 |
+
sel = [c for c in cs if pred(c)]
|
| 154 |
+
return f"{sum(c.passed for c in sel)}/{len(sel)}"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def render(full: ch.Trials, results: dict[str, list[Check]]) -> str:
|
| 158 |
+
lines = ["# Culling equivalence (preregistration, section 5)", "",
|
| 159 |
+
"Judged against `records/preregistration.md` as committed before the runs. Each "
|
| 160 |
+
"variant runs every chain-test condition run on `full` (seed set A, trials 0-29, "
|
| 161 |
+
"same seeds) and the random-population controls of section 4.1; `full` is the "
|
| 162 |
+
"committed chain-test record. w_syn is the same for every variant (no "
|
| 163 |
+
"rescaling).", "",
|
| 164 |
+
"> The engine check against Brian2 **failed** under the original rule "
|
| 165 |
+
"(preregistration, section 2.3), and we decided to proceed with that failure on "
|
| 166 |
+
"record. These runs are on our engine only.", "",
|
| 167 |
+
"| Variant | Rate checks | Latency checks | Same chain result | Result |",
|
| 168 |
+
"|---|---|---|---|---|"]
|
| 169 |
+
for v, cs in results.items():
|
| 170 |
+
ok = all(c.passed for c in cs)
|
| 171 |
+
lines.append(f"| {v} | {_tally(cs, lambda c: c.what.endswith('rate'))} | "
|
| 172 |
+
f"{_tally(cs, lambda c: c.what.endswith('latency'))} | "
|
| 173 |
+
f"{_tally(cs, lambda c: c.rate is None)} | "
|
| 174 |
+
f"{'**PASS**' if ok else '**FAIL**'} |")
|
| 175 |
+
lines += ["", "## Noise floors (from `full`, sets A + B at 100 Hz)", "",
|
| 176 |
+
"| Stimulus | " + " | ".join(f"{r} rate / latency" for r in ch.READOUTS) + " |",
|
| 177 |
+
"|---|" + "---|" * len(ch.READOUTS)]
|
| 178 |
+
for s in stimuli_of(full):
|
| 179 |
+
f = noise_floors(full, s)
|
| 180 |
+
lines.append(f"| {s} | " + " | ".join(f"{f[r].rate_hz:.2f} Hz / {f[r].latency_ms:.1f} ms"
|
| 181 |
+
for r in ch.READOUTS) + " |")
|
| 182 |
+
for v, cs in results.items():
|
| 183 |
+
bad = [c for c in cs if not c.passed]
|
| 184 |
+
lines += ["", f"## {v}: {'PASS' if not bad else f'FAIL ({len(bad)} of {len(cs)} checks)'}",
|
| 185 |
+
"", "| Stimulus | Rate | Check | full | variant | Rule | Pass |",
|
| 186 |
+
"|---|---|---|---|---|---|---|"]
|
| 187 |
+
for c in cs:
|
| 188 |
+
if c.passed and c.rate is not None and c.rate != ch.PRIMARY_RATE:
|
| 189 |
+
continue # passing checks at other rates: counted above, not listed
|
| 190 |
+
rate = "—" if c.rate is None else f"{c.rate:g} Hz"
|
| 191 |
+
lines.append(f"| {c.stimulus} | {rate} | {c.what} | {c.full} | {c.variant} | "
|
| 192 |
+
f"{c.tol} | {'✔' if c.passed else '✘'} |")
|
| 193 |
+
lines += ["", "Passing checks at rates other than 100 Hz are counted in the summary "
|
| 194 |
+
"but not listed; every failure is listed."]
|
| 195 |
+
return "\n".join(lines)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
# ----------------------------------------------------------------------------- cli
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def cmd_run(a: argparse.Namespace) -> int:
|
| 202 |
+
full = ch.Trials(json.loads(a.full.read_text()))
|
| 203 |
+
groups = [g for g, m in ch.GROUPS.items() if all(s in stimuli_of(full) for s in m)]
|
| 204 |
+
rc = 0
|
| 205 |
+
for g in groups:
|
| 206 |
+
ns = argparse.Namespace(connectome=a.connectome, out=a.out, group=g, variant=a.variant,
|
| 207 |
+
no_set_b=True, jobs=a.jobs, only=None)
|
| 208 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 209 |
+
rc |= ch.cmd_run(ns)
|
| 210 |
+
return rc
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def cmd_judge(a: argparse.Namespace) -> int:
|
| 214 |
+
full = ch.Trials(json.loads(a.full.read_text()))
|
| 215 |
+
results = {}
|
| 216 |
+
for p in a.variant:
|
| 217 |
+
d = json.loads(p.read_text())
|
| 218 |
+
v = d.get("variant")
|
| 219 |
+
if v not in CULLED:
|
| 220 |
+
raise ValueError(f"{p}: not a culled variant's record ({v!r})")
|
| 221 |
+
results[v] = compare(full, ch.Trials(d))
|
| 222 |
+
results = {v: results[v] for v in CULLED if v in results}
|
| 223 |
+
text = render(full, results)
|
| 224 |
+
if a.out:
|
| 225 |
+
a.out.write_text(text + "\n")
|
| 226 |
+
print(text)
|
| 227 |
+
return 0
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def main(argv: list[str] | None = None) -> int:
|
| 231 |
+
p = argparse.ArgumentParser(prog="python -m flysim.validation.culling")
|
| 232 |
+
sub = p.add_subparsers(dest="cmd", required=True)
|
| 233 |
+
r = sub.add_parser("run")
|
| 234 |
+
r.add_argument("--connectome", type=Path, required=True)
|
| 235 |
+
r.add_argument("--variant", choices=CULLED, required=True)
|
| 236 |
+
r.add_argument("--out", type=Path, required=True)
|
| 237 |
+
r.add_argument("--full", type=Path,
|
| 238 |
+
default=Path("records/results/chain-tests-trials.json"))
|
| 239 |
+
r.add_argument("--jobs", type=int, default=4)
|
| 240 |
+
j = sub.add_parser("judge")
|
| 241 |
+
j.add_argument("--full", type=Path, required=True)
|
| 242 |
+
j.add_argument("--variant", type=Path, nargs="+", required=True)
|
| 243 |
+
j.add_argument("--out", type=Path)
|
| 244 |
+
a = p.parse_args(argv)
|
| 245 |
+
return {"run": cmd_run, "judge": cmd_judge}[a.cmd](a)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
if __name__ == "__main__":
|
| 249 |
+
sys.exit(main())
|
| 250 |
+
|
flysim/src/flysim/validation/engine_check.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Engine check: run our engine on Shiu et al.'s cases and judge it against Brian2
|
| 2 |
+
(records/preregistration.md, section 2).
|
| 3 |
+
|
| 4 |
+
# our engine, seed set A (trials 0-29), all E1-E4 conditions
|
| 5 |
+
python -m flysim.validation.engine_check run --fafb DIR --out runs/ours [--jobs 4]
|
| 6 |
+
# ... or the fresh set F of the recalibrated rule (trials 1000-1029; exploratory)
|
| 7 |
+
python -m flysim.validation.engine_check run --fafb DIR --out runs/ours --seed-set fresh
|
| 8 |
+
|
| 9 |
+
# Brian2 reference: scripts/brian_reference.py writes runs/brian/<stem>.parquet
|
| 10 |
+
|
| 11 |
+
# report (markdown); --crosscheck compares Shiu's shipped sugarR.parquet
|
| 12 |
+
# with our Brian2 reruns of E1 at 200 Hz (decides) and 150 Hz (section 2.1)
|
| 13 |
+
python -m flysim.validation.engine_check compare --fafb DIR --ours runs/ours \
|
| 14 |
+
--brian runs/brian [--crosscheck sugarR.parquet] [--out report.md]
|
| 15 |
+
|
| 16 |
+
# exploratory report under the recalibrated rule (never a verdict; section 9)
|
| 17 |
+
python -m flysim.validation.engine_check compare ... --rule recalibrated --seed-set fresh
|
| 18 |
+
|
| 19 |
+
DIR holds Shiu et al.'s v630 completeness CSV and connectivity parquet.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import multiprocessing as mp
|
| 26 |
+
import platform
|
| 27 |
+
import sys
|
| 28 |
+
import time
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
from flysim.engine import CpuEngine, ModelParams, poisson_schedule, trial_rng
|
| 34 |
+
from flysim.engine.inputs import merge
|
| 35 |
+
from flysim.validation import fafb as fafb_mod
|
| 36 |
+
from flysim.validation import metrics, recalibrated
|
| 37 |
+
from flysim.validation.manifest import (
|
| 38 |
+
DURATION_MS,
|
| 39 |
+
SEED_SETS,
|
| 40 |
+
SET_A,
|
| 41 |
+
Condition,
|
| 42 |
+
conditions,
|
| 43 |
+
load_cases,
|
| 44 |
+
seed_set,
|
| 45 |
+
)
|
| 46 |
+
from flysim.validation.runs import RunSet
|
| 47 |
+
|
| 48 |
+
PARAMS = ModelParams() # FAFB: w_syn = 0.275 mV
|
| 49 |
+
N_STEPS = int(round(DURATION_MS / PARAMS.dt))
|
| 50 |
+
|
| 51 |
+
_worker: dict = {}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _init_worker(fafb_dir: str) -> None:
|
| 55 |
+
f = fafb_mod.load(Path(fafb_dir))
|
| 56 |
+
eng = CpuEngine(np.float32, skip_rest=False) # the reference kernel the check ran on
|
| 57 |
+
eng.load(f.matrix, PARAMS)
|
| 58 |
+
_worker.update(fafb=f, engine=eng, cases=load_cases())
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def stimulus(cond: Condition, trial: int, fafb: fafb_mod.Fafb, cases: dict):
|
| 62 |
+
"""Input schedule of one trial. Groups draw in manifest order from one generator."""
|
| 63 |
+
rng = trial_rng(cond.case, cond.key, trial)
|
| 64 |
+
sched = None
|
| 65 |
+
for group, rate in cond.groups:
|
| 66 |
+
targets = fafb.index_of(cases["groups"][group])
|
| 67 |
+
s = poisson_schedule(rng, targets, rate, 0, N_STEPS, PARAMS.dt)
|
| 68 |
+
sched = s if sched is None else merge(sched, s)
|
| 69 |
+
assert sched is not None
|
| 70 |
+
return sched
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def run_trial(cond: Condition, trial: int, fafb: fafb_mod.Fafb, engine: CpuEngine,
|
| 74 |
+
cases: dict) -> tuple[np.ndarray, np.ndarray]:
|
| 75 |
+
engine.reset()
|
| 76 |
+
engine.schedule_inputs(stimulus(cond, trial, fafb, cases))
|
| 77 |
+
engine.advance_to(N_STEPS)
|
| 78 |
+
return engine.spikes_since(0)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _task(args: tuple[str, int]) -> tuple[str, int, np.ndarray, np.ndarray, float]:
|
| 82 |
+
key, trial = args
|
| 83 |
+
cond = next(c for c in conditions() if c.key == key)
|
| 84 |
+
t0 = time.perf_counter()
|
| 85 |
+
steps, neurons = run_trial(cond, trial, _worker["fafb"], _worker["engine"], _worker["cases"])
|
| 86 |
+
return key, trial, steps, neurons, time.perf_counter() - t0
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _select(only: list[str] | None) -> list[Condition]:
|
| 90 |
+
return [c for c in conditions() if not only or c.key in only or c.case in only]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def cmd_run(a: argparse.Namespace) -> int:
|
| 94 |
+
conds = _select(a.only)
|
| 95 |
+
if a.seed_set is not None:
|
| 96 |
+
trials = list(seed_set(a.seed_set))
|
| 97 |
+
else:
|
| 98 |
+
trials = list(range(a.first_trial, a.first_trial + a.trials))
|
| 99 |
+
tasks = [(c.key, t) for c in conds for t in trials]
|
| 100 |
+
done: dict[str, list] = {c.key: [] for c in conds}
|
| 101 |
+
wall: list[float] = []
|
| 102 |
+
print(f"{len(tasks)} trials ({len(conds)} conditions x {len(trials)}), {a.jobs} workers",
|
| 103 |
+
flush=True)
|
| 104 |
+
ctx = mp.get_context("fork")
|
| 105 |
+
with ctx.Pool(a.jobs, initializer=_init_worker, initargs=(str(a.fafb),)) as pool:
|
| 106 |
+
for key, trial, steps, neurons, secs in pool.imap_unordered(_task, tasks):
|
| 107 |
+
done[key].append((trial, steps, neurons))
|
| 108 |
+
wall.append(secs)
|
| 109 |
+
if len(done[key]) == len(trials):
|
| 110 |
+
rs = RunSet.from_trials(
|
| 111 |
+
done[key], n_neurons=_n_neurons(a.fafb), n_steps=N_STEPS, dt_ms=PARAMS.dt,
|
| 112 |
+
meta={"engine": "flysim-cpu", "numerics": "float32", "key": key,
|
| 113 |
+
"params": PARAMS.to_dict()})
|
| 114 |
+
cond = next(c for c in conds if c.key == key)
|
| 115 |
+
rs.save(a.out / f"{cond.file_stem}.npz")
|
| 116 |
+
print(f" {key}: {len(rs.neurons)} spikes, median "
|
| 117 |
+
f"{np.median(wall):.2f} s/trial", flush=True)
|
| 118 |
+
return 0
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _n_neurons(fafb_dir: Path) -> int:
|
| 122 |
+
return len(fafb_mod.read_root_ids(fafb_dir))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def cmd_compare(a: argparse.Namespace) -> int:
|
| 126 |
+
root_ids = fafb_mod.read_root_ids(a.fafb)
|
| 127 |
+
cases = load_cases()
|
| 128 |
+
readout_idx = {name: int(np.flatnonzero(root_ids == rid)[0])
|
| 129 |
+
for name, rid in cases["readouts"].items()}
|
| 130 |
+
exploratory = a.rule == "recalibrated"
|
| 131 |
+
ours_trials = seed_set(a.seed_set)
|
| 132 |
+
if exploratory:
|
| 133 |
+
lines = ["# Engine check against Brian2: EXPLORATORY, recalibrated rule", "",
|
| 134 |
+
"> Exploratory only (preregistration, section 9). This rule was written after "
|
| 135 |
+
"the engine check failed under the original rule (section 2.3); its outcome "
|
| 136 |
+
"cannot change that verdict, which stays **FAIL**.", "",
|
| 137 |
+
f"Rule: half-split quantiles at α = {recalibrated.ALPHA:.3e} "
|
| 138 |
+
f"(0.05 / {recalibrated.N_CHECKS}), {recalibrated.N_SPLITS:,} splits, "
|
| 139 |
+
f"permutation seed {recalibrated.PERMUTATION_SEED}. Our engine: seed set "
|
| 140 |
+
f"`{a.seed_set}` "
|
| 141 |
+
f"(trials {ours_trials.start}-{ours_trials.stop - 1}).", ""]
|
| 142 |
+
else:
|
| 143 |
+
lines = ["# Engine check against Brian2", ""]
|
| 144 |
+
lines += ["Judged against `records/preregistration.md`.",
|
| 145 |
+
f"Host: {platform.platform()}, Python {platform.python_version()}.", ""]
|
| 146 |
+
|
| 147 |
+
def brian(stem: str) -> RunSet:
|
| 148 |
+
return RunSet.from_brian_parquet(a.brian / f"{stem}.parquet", root_ids, 60,
|
| 149 |
+
N_STEPS, PARAMS.dt)
|
| 150 |
+
|
| 151 |
+
overall = True
|
| 152 |
+
if a.crosscheck:
|
| 153 |
+
# Section 2.1 as amended before any Brian2 run: 200 Hz decides, 150 Hz is reported.
|
| 154 |
+
shipped = RunSet.from_brian_parquet(a.crosscheck, root_ids, 30, N_STEPS, PARAMS.dt)
|
| 155 |
+
for stem, key, decides in (("E1__sugarR__200Hz", "E1/sugarR/200Hz", True),
|
| 156 |
+
("E1__sugarR__150Hz", "E1/sugarR/150Hz", False)):
|
| 157 |
+
role = "decides" if decides else "reported only (original rule)"
|
| 158 |
+
lines += [f"## Cross-check: shipped `sugarR.parquet` vs our Brian2 rerun of {key}"
|
| 159 |
+
f" ({role})", ""]
|
| 160 |
+
res = metrics.compare_condition(key, shipped, brian(stem), readout_idx["MN9"])
|
| 161 |
+
lines += _table([res])
|
| 162 |
+
if decides:
|
| 163 |
+
overall &= res.passed
|
| 164 |
+
lines += [f"Cross-check ({role}): **{'pass' if res.passed else 'FAIL'}**", ""]
|
| 165 |
+
|
| 166 |
+
selected = _select(a.only)
|
| 167 |
+
results: dict[str, metrics.ConditionResult] = {}
|
| 168 |
+
judge = recalibrated.compare_condition if exploratory else metrics.compare_condition
|
| 169 |
+
for c in selected:
|
| 170 |
+
ours = RunSet.load(a.ours / f"{c.file_stem}.npz").subset(ours_trials)
|
| 171 |
+
results[c.key] = judge(c.key, ours, brian(c.file_stem), readout_idx[c.readout])
|
| 172 |
+
lines += ["## Engine vs Brian2 set A", ""] + _table(list(results.values()))
|
| 173 |
+
dirs = []
|
| 174 |
+
for case in ("E1", "E3"):
|
| 175 |
+
ladder = sorted((c for c in conditions() if c.case == case), key=lambda c: c.ladder)
|
| 176 |
+
if all(c.key in results for c in ladder): # partial runs skip the case
|
| 177 |
+
dirs += metrics.direction_checks([results[c.key] for c in ladder])
|
| 178 |
+
lines += ["## Direction checks", "", "| Step | Our Δ (Hz) | d95 | Pass | Note |",
|
| 179 |
+
"|---|---:|---:|---|---|"]
|
| 180 |
+
lines += [f"| {d.name} | {d.value:+.2f} | {d.threshold:.2f} | {_pf(d.passed)} | {d.note} |"
|
| 181 |
+
for d in dirs]
|
| 182 |
+
gate = all(r.passed for r in results.values()) and all(d.passed for d in dirs)
|
| 183 |
+
overall &= gate
|
| 184 |
+
complete = len(selected) == len(conditions())
|
| 185 |
+
verdict = ("PASS" if gate else "FAIL") if complete else (
|
| 186 |
+
f"partial run ({len(selected)} of {len(conditions())} conditions): "
|
| 187 |
+
f"{'all checks pass' if gate else 'FAIL'}; not a verdict")
|
| 188 |
+
if exploratory:
|
| 189 |
+
lines += ["", f"**Exploratory result under the recalibrated rule: {verdict}** "
|
| 190 |
+
"(exploratory; the engine-check verdict stays FAIL)", ""]
|
| 191 |
+
elif a.seed_set != "A":
|
| 192 |
+
lines += ["", f"**Original rule on seed set `{a.seed_set}`: {verdict}** "
|
| 193 |
+
"(not a verdict: the original rule judges seed set A)", ""]
|
| 194 |
+
else:
|
| 195 |
+
lines += ["", f"**Engine check: {verdict}**", ""]
|
| 196 |
+
text = "\n".join(lines)
|
| 197 |
+
if a.out:
|
| 198 |
+
a.out.write_text(text)
|
| 199 |
+
print(text)
|
| 200 |
+
return 0 if overall else 1
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _pf(ok: bool) -> str:
|
| 204 |
+
return "✔" if ok else "✘"
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _table(rows: list[metrics.ConditionResult]) -> list[str]:
|
| 208 |
+
out = ["| Condition | Check | Value | Threshold | Pass | Note |",
|
| 209 |
+
"|---|---|---:|---:|---|---|"]
|
| 210 |
+
for r in rows:
|
| 211 |
+
for c in r.checks:
|
| 212 |
+
out.append(f"| {r.key} | {c.name} | {c.value:.3f} | {c.threshold:.3f} | "
|
| 213 |
+
f"{_pf(c.passed)} | {c.note} |")
|
| 214 |
+
return out + [""]
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def main(argv: list[str] | None = None) -> int:
|
| 218 |
+
p = argparse.ArgumentParser(prog="python -m flysim.validation.engine_check")
|
| 219 |
+
sub = p.add_subparsers(dest="cmd", required=True)
|
| 220 |
+
r = sub.add_parser("run", help="run our engine")
|
| 221 |
+
r.add_argument("--fafb", type=Path, required=True)
|
| 222 |
+
r.add_argument("--out", type=Path, required=True)
|
| 223 |
+
r.add_argument("--jobs", type=int, default=mp.cpu_count())
|
| 224 |
+
r.add_argument("--trials", type=int, default=len(SET_A))
|
| 225 |
+
r.add_argument("--first-trial", type=int, default=SET_A.start)
|
| 226 |
+
r.add_argument("--seed-set", choices=sorted(SEED_SETS),
|
| 227 |
+
help="named seed set; overrides --trials and --first-trial")
|
| 228 |
+
r.add_argument("--only", nargs="*", help="case ids (E1) or condition keys")
|
| 229 |
+
c = sub.add_parser("compare", help="judge against Brian2")
|
| 230 |
+
c.add_argument("--fafb", type=Path, required=True)
|
| 231 |
+
c.add_argument("--ours", type=Path, required=True)
|
| 232 |
+
c.add_argument("--brian", type=Path, required=True)
|
| 233 |
+
c.add_argument("--crosscheck", type=Path)
|
| 234 |
+
c.add_argument("--rule", choices=["original", "recalibrated"], default="original",
|
| 235 |
+
help="original: section 2.3, decides the check (default); "
|
| 236 |
+
"recalibrated: exploratory")
|
| 237 |
+
c.add_argument("--seed-set", choices=sorted(SEED_SETS), default="A",
|
| 238 |
+
help="our engine's trials to compare (default A, as section 2.3 requires)")
|
| 239 |
+
c.add_argument("--only", nargs="*", help="case ids (E1) or condition keys")
|
| 240 |
+
c.add_argument("--out", type=Path)
|
| 241 |
+
a = p.parse_args(argv)
|
| 242 |
+
return cmd_run(a) if a.cmd == "run" else cmd_compare(a)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
sys.exit(main())
|
flysim/src/flysim/validation/fafb.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shiu et al.'s FlyWire v630 tables as an engine matrix.
|
| 2 |
+
|
| 3 |
+
Neuron indices follow the row order of the completeness CSV, as ``model.py``
|
| 4 |
+
does (``flyid2i = {j: i for i, j in enumerate(df_comp.index)}``). The weight of
|
| 5 |
+
an edge is ``Excitatory x Connectivity``; Brian2 makes one synapse per table
|
| 6 |
+
row, so duplicate (pre, post) rows, if any, add up the same way here.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pyarrow.csv as pacsv
|
| 16 |
+
import pyarrow.parquet as pq
|
| 17 |
+
|
| 18 |
+
from flysim.engine import SynapseMatrix
|
| 19 |
+
from flysim.validation.manifest import FAFB_COMPLETENESS, FAFB_CONNECTIVITY
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass(frozen=True)
|
| 23 |
+
class Fafb:
|
| 24 |
+
matrix: SynapseMatrix
|
| 25 |
+
root_ids: np.ndarray # int64, index -> FlyWire v630 root ID
|
| 26 |
+
|
| 27 |
+
def index_of(self, ids: list[int] | np.ndarray) -> np.ndarray:
|
| 28 |
+
ids = np.asarray(ids, dtype=np.int64)
|
| 29 |
+
order = np.argsort(self.root_ids)
|
| 30 |
+
pos = np.searchsorted(self.root_ids, ids, sorter=order)
|
| 31 |
+
pos = np.minimum(pos, len(order) - 1)
|
| 32 |
+
idx = order[pos]
|
| 33 |
+
missing = ids[self.root_ids[idx] != ids]
|
| 34 |
+
if len(missing):
|
| 35 |
+
raise KeyError(f"root IDs not in the v630 table: {missing[:5].tolist()}")
|
| 36 |
+
return idx.astype(np.int32)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def read_root_ids(directory: Path) -> np.ndarray:
|
| 40 |
+
table = pacsv.read_csv(directory / FAFB_COMPLETENESS)
|
| 41 |
+
return table.column(0).to_numpy().astype(np.int64)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def load(directory: Path) -> Fafb:
|
| 45 |
+
root_ids = read_root_ids(directory)
|
| 46 |
+
t = pq.read_table(
|
| 47 |
+
directory / FAFB_CONNECTIVITY,
|
| 48 |
+
columns=["Presynaptic_ID", "Postsynaptic_ID", "Presynaptic_Index",
|
| 49 |
+
"Postsynaptic_Index", "Excitatory x Connectivity"],
|
| 50 |
+
)
|
| 51 |
+
pre = t.column("Presynaptic_Index").to_numpy()
|
| 52 |
+
post = t.column("Postsynaptic_Index").to_numpy()
|
| 53 |
+
# model.py maps IDs through the CSV but takes edge indices from the parquet;
|
| 54 |
+
# check the two agree so our indexing is the same as Brian2's.
|
| 55 |
+
if not (np.array_equal(root_ids[pre], t.column("Presynaptic_ID").to_numpy())
|
| 56 |
+
and np.array_equal(root_ids[post], t.column("Postsynaptic_ID").to_numpy())):
|
| 57 |
+
raise ValueError("connectivity indices disagree with the completeness CSV order")
|
| 58 |
+
w = t.column("Excitatory x Connectivity").to_numpy()
|
| 59 |
+
return Fafb(SynapseMatrix.from_edges(pre, post, w, len(root_ids)), root_ids)
|