flycns 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. flycns-0.6.0/LICENSE +21 -0
  2. flycns-0.6.0/PKG-INFO +128 -0
  3. flycns-0.6.0/README.md +91 -0
  4. flycns-0.6.0/pyproject.toml +64 -0
  5. flycns-0.6.0/setup.cfg +4 -0
  6. flycns-0.6.0/src/flycns/__init__.py +7 -0
  7. flycns-0.6.0/src/flycns/compiled.py +150 -0
  8. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/LICENSE-flyvis.txt +9 -0
  9. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/bias.bin +0 -0
  10. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/group_du.bin +0 -0
  11. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/group_dv.bin +0 -0
  12. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/group_n_syn.bin +0 -0
  13. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/group_pair.bin +0 -0
  14. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/manifest.json +248 -0
  15. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/pair_sign.bin +1 -0
  16. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/pair_source.bin +0 -0
  17. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/pair_target.bin +0 -0
  18. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/strength.bin +0 -0
  19. flycns-0.6.0/src/flycns/data/flyvis-1.2.0-ensemble/time_const_s.bin +0 -0
  20. flycns-0.6.0/src/flycns/dynamics/__init__.py +18 -0
  21. flycns-0.6.0/src/flycns/dynamics/graded.py +184 -0
  22. flycns-0.6.0/src/flycns/dynamics/hybrid.py +330 -0
  23. flycns-0.6.0/src/flycns/dynamics/lif.py +391 -0
  24. flycns-0.6.0/src/flycns/eyes.py +360 -0
  25. flycns-0.6.0/src/flycns/flyvis.py +101 -0
  26. flycns-0.6.0/src/flycns/mapped.py +103 -0
  27. flycns-0.6.0/src/flycns/motion.py +250 -0
  28. flycns-0.6.0/src/flycns/nulls.py +144 -0
  29. flycns-0.6.0/src/flycns/optic_lobe.py +412 -0
  30. flycns-0.6.0/src/flycns/py.typed +0 -0
  31. flycns-0.6.0/src/flycns/record.py +32 -0
  32. flycns-0.6.0/src/flycns/release/__init__.py +6 -0
  33. flycns-0.6.0/src/flycns/release/base.py +67 -0
  34. flycns-0.6.0/src/flycns/release/malecns_v1.py +412 -0
  35. flycns-0.6.0/src/flycns/rng.py +65 -0
  36. flycns-0.6.0/src/flycns.egg-info/PKG-INFO +128 -0
  37. flycns-0.6.0/src/flycns.egg-info/SOURCES.txt +59 -0
  38. flycns-0.6.0/src/flycns.egg-info/dependency_links.txt +1 -0
  39. flycns-0.6.0/src/flycns.egg-info/requires.txt +16 -0
  40. flycns-0.6.0/src/flycns.egg-info/top_level.txt +1 -0
  41. flycns-0.6.0/tests/test_compiled.py +38 -0
  42. flycns-0.6.0/tests/test_eyes.py +141 -0
  43. flycns-0.6.0/tests/test_eyes_data.py +46 -0
  44. flycns-0.6.0/tests/test_flyvis_ensemble.py +55 -0
  45. flycns-0.6.0/tests/test_graded.py +76 -0
  46. flycns-0.6.0/tests/test_graded_parity.py +64 -0
  47. flycns-0.6.0/tests/test_hybrid.py +107 -0
  48. flycns-0.6.0/tests/test_lif.py +175 -0
  49. flycns-0.6.0/tests/test_lif_parity.py +109 -0
  50. flycns-0.6.0/tests/test_malecns_data.py +44 -0
  51. flycns-0.6.0/tests/test_mapped.py +58 -0
  52. flycns-0.6.0/tests/test_motion.py +69 -0
  53. flycns-0.6.0/tests/test_motion_parity.py +51 -0
  54. flycns-0.6.0/tests/test_nulls.py +118 -0
  55. flycns-0.6.0/tests/test_optic_lobe.py +142 -0
  56. flycns-0.6.0/tests/test_optic_lobe_data.py +75 -0
  57. flycns-0.6.0/tests/test_record.py +38 -0
  58. flycns-0.6.0/tests/test_release.py +128 -0
  59. flycns-0.6.0/tests/test_stabilisers.py +71 -0
  60. flycns-0.6.0/tests/test_version.py +23 -0
  61. flycns-0.6.0/tests/test_whole_cns_data.py +128 -0
flycns-0.6.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Felipe Santibanez-Leal
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.
flycns-0.6.0/PKG-INFO ADDED
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: flycns
3
+ Version: 0.6.0
4
+ Summary: Compile fly connectome releases (MaleCNS v1.0) into simulation-ready graphs with two-eye column maps, and simulate the whole central nervous system (graded optic lobe plus spiking LIF) with parity between Python and the browser.
5
+ Author-email: Felipe Santibanez-Leal <fsantibanez@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/fsantibanezleal/CAOS_FlyCNS
8
+ Project-URL: Source, https://github.com/fsantibanezleal/CAOS_FlyCNS
9
+ Project-URL: Issues, https://github.com/fsantibanezleal/CAOS_FlyCNS/issues
10
+ Project-URL: Changelog, https://github.com/fsantibanezleal/CAOS_FlyCNS/blob/main/CHANGELOG.md
11
+ Keywords: connectome,drosophila,malecns,neuroscience,simulation,spiking,leaky-integrate-and-fire,compound-eye
12
+ Classifier: Development Status :: 2 - Pre-Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy>=1.26
25
+ Provides-Extra: release
26
+ Requires-Dist: pyarrow>=15; extra == "release"
27
+ Requires-Dist: pandas>=2.1; extra == "release"
28
+ Provides-Extra: gpu
29
+ Requires-Dist: torch>=2.3; extra == "gpu"
30
+ Provides-Extra: parity
31
+ Requires-Dist: brian2>=2.7; extra == "parity"
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=8.0; extra == "dev"
34
+ Requires-Dist: ruff>=0.6; extra == "dev"
35
+ Requires-Dist: mmh3>=4.0; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # flycns
39
+
40
+ [![ci](https://github.com/fsantibanezleal/CAOS_FlyCNS/actions/workflows/ci.yaml/badge.svg?branch=main)](https://github.com/fsantibanezleal/CAOS_FlyCNS/actions/workflows/ci.yaml)
41
+ [![license: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
42
+
43
+ Compile a fly connectome release into a graph a simulator can run, model the two compound eyes over the release's
44
+ own optic-lobe columns, and simulate the whole central nervous system with the published neuron models, in Python
45
+ and in the browser, with the two implementations held to each other by parity tests.
46
+
47
+ - **Release:** MaleCNS v1.0, the complete male *Drosophila* CNS (166,700 neurons, brain and ventral nerve cord;
48
+ Berg et al., *Cell* 189:5504-5526, 2026, doi:10.1016/j.cell.2026.08.015; data CC BY 4.0). Both optic lobes are
49
+ mapped column by column in the release (879 columns left, 892 right), which is what lets two eyes feed it.
50
+ - **Neuron models:** the published leaky integrate-and-fire model of the fly brain (Shiu et al., *Nature*
51
+ 634:210-219, 2024, doi:10.1038/s41586-024-07763-9), and a graded optic lobe in the form of the connectome-constrained
52
+ visual model (Lappalainen et al., *Nature* 2024, doi:10.1038/s41586-024-07939-3).
53
+ - **Two implementations, one set of equations:** a Python reference (NumPy, and PyTorch on a GPU) and a browser
54
+ engine (`@fasl-work/flycns`, WebGPU with a worker fallback).
55
+
56
+ ## What it is not
57
+
58
+ A general neural simulator, a learned model of the fly, or a claim about behaviour. Synapse counts and signs are
59
+ data and never change; the package integrates published equations over them and says where those equations are
60
+ known to fall short.
61
+
62
+ ## Status
63
+
64
+ Version 0.06.000: the MaleCNS v1.0 compiler and compiled format; the two compound eyes over the release's own
65
+ columns, their vertical set by the dorsal rim; the published spiking model, identical to a literal Brian2
66
+ transcription, on a NumPy reference and a GPU engine; the graded visual neurons as flyvis computes them, held to
67
+ flyvis itself, with its 50 trained networks shipped as data; and flyvis's numbers transferred onto the neuron-level
68
+ wiring of both MaleCNS optic lobes, where T4 cells, measured through the modelled eyes, prefer their known
69
+ directions; and the whole CNS coupled, in four engines (the published model everywhere, which does not see; the
70
+ graded optic lobes with the spiking CNS, which carries a flash to the motor neurons; flyvis's own networks mapped
71
+ onto MaleCNS; and the stabilised version, which leaves the published model one state). Next: the browser engine.
72
+ This README lists capabilities only as they land.
73
+
74
+ ## Compile MaleCNS v1.0
75
+
76
+ Download the four tables listed in [`docs/releases/01_malecns-v1.md`](docs/releases/01_malecns-v1.md) into one
77
+ folder, then:
78
+
79
+ ```python
80
+ from pathlib import Path
81
+ from flycns.release import compile_malecns_v1
82
+ from flycns.compiled import read_compiled
83
+
84
+ compile_malecns_v1(Path("malecns-tables"), Path("compiled/malecns-v1.0"), progress=print)
85
+ graph = read_compiled(Path("compiled/malecns-v1.0")) # every array verified against its SHA-256
86
+ print(graph.n_neurons, graph.n_edges, graph.counts["columns"])
87
+ ```
88
+
89
+ A table whose SHA-256 differs from the locked value is refused. Compilation streams the 13 GB synapse table in record
90
+ batches and takes a few minutes on a desktop.
91
+
92
+ ## Simulate
93
+
94
+ ```python
95
+ from pathlib import Path
96
+
97
+ from flycns.compiled import read_compiled
98
+ from flycns.dynamics import Drive, LIFReference, synaptic_weights
99
+
100
+ graph = read_compiled(Path("compiled/malecns-v1.0"))
101
+ weights = synaptic_weights(graph["csr_indptr"], graph["csr_indices"], graph["csr_count"], graph["neuron_sign"], 0.275)
102
+ engine = LIFReference(graph["csr_indptr"], graph["csr_indices"], weights) # or LIFTorch on a GPU
103
+ run = engine.run(10_000, Drive(activate={1234: 150.0}), seed=0) # one second of model time
104
+ print(run.spike_counts().sum(), "spikes")
105
+ ```
106
+
107
+ The graded visual neurons run through `flycns.dynamics.GradedReference` (or `GradedTorch`), with the trained flyvis
108
+ parameters from `flycns.flyvis.load_ensemble()`; see [`docs/models/03_graded.md`](docs/models/03_graded.md).
109
+
110
+ ## Install (development)
111
+
112
+ ```bash
113
+ python -m venv .venv
114
+ .venv/Scripts/python -m pip install -e ".[dev,release,parity]" # add ,gpu for PyTorch; .venv/bin/python elsewhere
115
+ .venv/Scripts/python -m pytest -rs
116
+ npm ci && npm test
117
+ ```
118
+
119
+ ## Documentation
120
+
121
+ The wiki starts at [`docs/README.md`](docs/README.md).
122
+
123
+ ## License
124
+
125
+ Code: MIT. Connectome data are not redistributed here; they are fetched from the release with their hashes checked,
126
+ and remain under their own licence (MaleCNS: CC BY 4.0). The trained parameters of flyvis's pretrained networks
127
+ ship inside the package under flyvis's MIT licence, whose notice travels with them
128
+ (`src/flycns/data/flyvis-1.2.0-ensemble/LICENSE-flyvis.txt`).
flycns-0.6.0/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # flycns
2
+
3
+ [![ci](https://github.com/fsantibanezleal/CAOS_FlyCNS/actions/workflows/ci.yaml/badge.svg?branch=main)](https://github.com/fsantibanezleal/CAOS_FlyCNS/actions/workflows/ci.yaml)
4
+ [![license: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
5
+
6
+ Compile a fly connectome release into a graph a simulator can run, model the two compound eyes over the release's
7
+ own optic-lobe columns, and simulate the whole central nervous system with the published neuron models, in Python
8
+ and in the browser, with the two implementations held to each other by parity tests.
9
+
10
+ - **Release:** MaleCNS v1.0, the complete male *Drosophila* CNS (166,700 neurons, brain and ventral nerve cord;
11
+ Berg et al., *Cell* 189:5504-5526, 2026, doi:10.1016/j.cell.2026.08.015; data CC BY 4.0). Both optic lobes are
12
+ mapped column by column in the release (879 columns left, 892 right), which is what lets two eyes feed it.
13
+ - **Neuron models:** the published leaky integrate-and-fire model of the fly brain (Shiu et al., *Nature*
14
+ 634:210-219, 2024, doi:10.1038/s41586-024-07763-9), and a graded optic lobe in the form of the connectome-constrained
15
+ visual model (Lappalainen et al., *Nature* 2024, doi:10.1038/s41586-024-07939-3).
16
+ - **Two implementations, one set of equations:** a Python reference (NumPy, and PyTorch on a GPU) and a browser
17
+ engine (`@fasl-work/flycns`, WebGPU with a worker fallback).
18
+
19
+ ## What it is not
20
+
21
+ A general neural simulator, a learned model of the fly, or a claim about behaviour. Synapse counts and signs are
22
+ data and never change; the package integrates published equations over them and says where those equations are
23
+ known to fall short.
24
+
25
+ ## Status
26
+
27
+ Version 0.06.000: the MaleCNS v1.0 compiler and compiled format; the two compound eyes over the release's own
28
+ columns, their vertical set by the dorsal rim; the published spiking model, identical to a literal Brian2
29
+ transcription, on a NumPy reference and a GPU engine; the graded visual neurons as flyvis computes them, held to
30
+ flyvis itself, with its 50 trained networks shipped as data; and flyvis's numbers transferred onto the neuron-level
31
+ wiring of both MaleCNS optic lobes, where T4 cells, measured through the modelled eyes, prefer their known
32
+ directions; and the whole CNS coupled, in four engines (the published model everywhere, which does not see; the
33
+ graded optic lobes with the spiking CNS, which carries a flash to the motor neurons; flyvis's own networks mapped
34
+ onto MaleCNS; and the stabilised version, which leaves the published model one state). Next: the browser engine.
35
+ This README lists capabilities only as they land.
36
+
37
+ ## Compile MaleCNS v1.0
38
+
39
+ Download the four tables listed in [`docs/releases/01_malecns-v1.md`](docs/releases/01_malecns-v1.md) into one
40
+ folder, then:
41
+
42
+ ```python
43
+ from pathlib import Path
44
+ from flycns.release import compile_malecns_v1
45
+ from flycns.compiled import read_compiled
46
+
47
+ compile_malecns_v1(Path("malecns-tables"), Path("compiled/malecns-v1.0"), progress=print)
48
+ graph = read_compiled(Path("compiled/malecns-v1.0")) # every array verified against its SHA-256
49
+ print(graph.n_neurons, graph.n_edges, graph.counts["columns"])
50
+ ```
51
+
52
+ A table whose SHA-256 differs from the locked value is refused. Compilation streams the 13 GB synapse table in record
53
+ batches and takes a few minutes on a desktop.
54
+
55
+ ## Simulate
56
+
57
+ ```python
58
+ from pathlib import Path
59
+
60
+ from flycns.compiled import read_compiled
61
+ from flycns.dynamics import Drive, LIFReference, synaptic_weights
62
+
63
+ graph = read_compiled(Path("compiled/malecns-v1.0"))
64
+ weights = synaptic_weights(graph["csr_indptr"], graph["csr_indices"], graph["csr_count"], graph["neuron_sign"], 0.275)
65
+ engine = LIFReference(graph["csr_indptr"], graph["csr_indices"], weights) # or LIFTorch on a GPU
66
+ run = engine.run(10_000, Drive(activate={1234: 150.0}), seed=0) # one second of model time
67
+ print(run.spike_counts().sum(), "spikes")
68
+ ```
69
+
70
+ The graded visual neurons run through `flycns.dynamics.GradedReference` (or `GradedTorch`), with the trained flyvis
71
+ parameters from `flycns.flyvis.load_ensemble()`; see [`docs/models/03_graded.md`](docs/models/03_graded.md).
72
+
73
+ ## Install (development)
74
+
75
+ ```bash
76
+ python -m venv .venv
77
+ .venv/Scripts/python -m pip install -e ".[dev,release,parity]" # add ,gpu for PyTorch; .venv/bin/python elsewhere
78
+ .venv/Scripts/python -m pytest -rs
79
+ npm ci && npm test
80
+ ```
81
+
82
+ ## Documentation
83
+
84
+ The wiki starts at [`docs/README.md`](docs/README.md).
85
+
86
+ ## License
87
+
88
+ Code: MIT. Connectome data are not redistributed here; they are fetched from the release with their hashes checked,
89
+ and remain under their own licence (MaleCNS: CC BY 4.0). The trained parameters of flyvis's pretrained networks
90
+ ship inside the package under flyvis's MIT licence, whose notice travels with them
91
+ (`src/flycns/data/flyvis-1.2.0-ensemble/LICENSE-flyvis.txt`).
@@ -0,0 +1,64 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "flycns"
7
+ version = "0.6.0"
8
+ description = "Compile fly connectome releases (MaleCNS v1.0) into simulation-ready graphs with two-eye column maps, and simulate the whole central nervous system (graded optic lobe plus spiking LIF) with parity between Python and the browser."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Felipe Santibanez-Leal", email = "fsantibanez@gmail.com" }]
13
+ keywords = ["connectome", "drosophila", "malecns", "neuroscience", "simulation", "spiking", "leaky-integrate-and-fire", "compound-eye"]
14
+ classifiers = [
15
+ "Development Status :: 2 - Pre-Alpha",
16
+ "Intended Audience :: Science/Research",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
23
+ "Typing :: Typed",
24
+ ]
25
+ dependencies = ["numpy>=1.26"]
26
+
27
+ [project.optional-dependencies]
28
+ # reading release files (feather tables)
29
+ release = ["pyarrow>=15", "pandas>=2.1"]
30
+ # the GPU path of the dynamics
31
+ gpu = ["torch>=2.3"]
32
+ # the literal Brian2 transcription used by the parity tests
33
+ parity = ["brian2>=2.7"]
34
+ # mmh3 is the independent MurmurHash3 oracle for the counter-based generator
35
+ dev = ["pytest>=8.0", "ruff>=0.6", "mmh3>=4.0"]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/fsantibanezleal/CAOS_FlyCNS"
39
+ Source = "https://github.com/fsantibanezleal/CAOS_FlyCNS"
40
+ Issues = "https://github.com/fsantibanezleal/CAOS_FlyCNS/issues"
41
+ Changelog = "https://github.com/fsantibanezleal/CAOS_FlyCNS/blob/main/CHANGELOG.md"
42
+
43
+ [tool.setuptools.packages.find]
44
+ where = ["src"]
45
+
46
+ [tool.setuptools.package-data]
47
+ flycns = ["py.typed", "data/**/*"]
48
+
49
+ [tool.pytest.ini_options]
50
+ testpaths = ["tests"]
51
+ addopts = "-q"
52
+ markers = [
53
+ "data: needs the release files on disk (skipped when absent, and reported with -rs)",
54
+ "gpu: needs a CUDA device",
55
+ "parity: needs brian2",
56
+ ]
57
+
58
+ [tool.ruff]
59
+ line-length = 110
60
+ target-version = "py311"
61
+
62
+ [tool.ruff.lint]
63
+ select = ["E", "F", "I", "UP", "B"]
64
+ ignore = ["E501"]
flycns-0.6.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,7 @@
1
+ """flycns: fly connectome releases compiled for simulation, two compound eyes, and the whole CNS in motion.
2
+
3
+ The display version (``X.XX.XXX``) lives in the ``VERSION`` file at the repository root; ``__version__`` is its
4
+ semantic form, the one the package index and ``pyproject.toml`` carry.
5
+ """
6
+
7
+ __version__ = "0.6.0"
@@ -0,0 +1,150 @@
1
+ """The compiled directory: the one thing both simulators read.
2
+
3
+ A compiled connectome is a directory holding ``manifest.json`` and one little-endian binary file per array. The
4
+ manifest lists every array with its dtype, shape and SHA-256, plus the release it came from, the hashes of the source
5
+ tables, the string tables the index arrays point into, and the counts the compiler measured. The reader refuses a
6
+ directory whose arrays do not match their recorded hashes: a simulation must never run on a graph that is not the one
7
+ that was compiled.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import numpy as np
19
+
20
+ SCHEMA = "flycns.compiled/1"
21
+
22
+ #: dtypes the format allows, by name; each is written little-endian.
23
+ DTYPES = {
24
+ "int8": np.int8,
25
+ "uint8": np.uint8,
26
+ "int16": np.int16,
27
+ "uint16": np.uint16,
28
+ "int32": np.int32,
29
+ "uint32": np.uint32,
30
+ "int64": np.int64,
31
+ "float32": np.float32,
32
+ }
33
+
34
+
35
+ class CompiledError(ValueError):
36
+ """A compiled directory that cannot be trusted: a missing file, a wrong shape, or a hash that differs."""
37
+
38
+
39
+ def sha256_bytes(data: bytes) -> str:
40
+ return hashlib.sha256(data).hexdigest()
41
+
42
+
43
+ def sha256_file(path: Path, chunk: int = 1 << 24) -> str:
44
+ digest = hashlib.sha256()
45
+ with open(path, "rb") as handle:
46
+ while block := handle.read(chunk):
47
+ digest.update(block)
48
+ return digest.hexdigest()
49
+
50
+
51
+ def _dtype_name(array: np.ndarray) -> str:
52
+ for name, dtype in DTYPES.items():
53
+ if array.dtype == np.dtype(dtype):
54
+ return name
55
+ raise CompiledError(f"dtype {array.dtype} is not allowed in a compiled directory")
56
+
57
+
58
+ def write_compiled(directory: Path, arrays: dict[str, np.ndarray], meta: dict[str, Any],
59
+ schema: str = SCHEMA) -> dict[str, Any]:
60
+ """Write ``arrays`` and a manifest into ``directory``; return the manifest.
61
+
62
+ ``meta`` carries the release, sources, counts and string tables; it is stored as given under the manifest's
63
+ ``release``, ``sources``, ``counts`` and ``strings`` keys. Array files are written in name order so two
64
+ compilations of the same inputs produce the same bytes.
65
+ """
66
+ directory = Path(directory)
67
+ directory.mkdir(parents=True, exist_ok=True)
68
+ entries = []
69
+ for name in sorted(arrays):
70
+ array = np.ascontiguousarray(arrays[name])
71
+ dtype = _dtype_name(array)
72
+ data = array.astype(array.dtype.newbyteorder("<"), copy=False).tobytes(order="C")
73
+ file_name = f"{name}.bin"
74
+ (directory / file_name).write_bytes(data)
75
+ entries.append(
76
+ {"name": name, "dtype": dtype, "shape": list(array.shape), "file": file_name, "bytes": len(data),
77
+ "sha256": sha256_bytes(data)}
78
+ )
79
+ manifest = {
80
+ "schema": schema,
81
+ "release": meta.get("release", {}),
82
+ "sources": meta.get("sources", []),
83
+ "counts": meta.get("counts", {}),
84
+ "strings": meta.get("strings", {}),
85
+ "arrays": entries,
86
+ }
87
+ # LF on every system, so the same inputs give the same bytes on Windows and Linux
88
+ (directory / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8",
89
+ newline="\n")
90
+ return manifest
91
+
92
+
93
+ @dataclass
94
+ class Compiled:
95
+ """A verified compiled connectome: its manifest, arrays and string tables."""
96
+
97
+ directory: Path
98
+ manifest: dict[str, Any]
99
+ arrays: dict[str, np.ndarray] = field(repr=False)
100
+
101
+ @property
102
+ def strings(self) -> dict[str, list[str]]:
103
+ return self.manifest["strings"]
104
+
105
+ @property
106
+ def counts(self) -> dict[str, Any]:
107
+ return self.manifest["counts"]
108
+
109
+ @property
110
+ def n_neurons(self) -> int:
111
+ return int(self.arrays["neuron_body_id"].shape[0])
112
+
113
+ @property
114
+ def n_edges(self) -> int:
115
+ return int(self.arrays["csr_indices"].shape[0])
116
+
117
+ def __getitem__(self, name: str) -> np.ndarray:
118
+ return self.arrays[name]
119
+
120
+
121
+ def read_compiled(directory: Path, verify: bool = True, schema: str = SCHEMA) -> Compiled:
122
+ """Read a compiled directory, checking every array against the manifest.
123
+
124
+ With ``verify`` (the default) each file's SHA-256 is recomputed; any difference, a missing file or a size that
125
+ does not match the declared shape raises :class:`CompiledError`.
126
+ """
127
+ directory = Path(directory)
128
+ manifest_path = directory / "manifest.json"
129
+ if not manifest_path.is_file():
130
+ raise CompiledError(f"{directory} holds no manifest.json")
131
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
132
+ if manifest.get("schema") != schema:
133
+ raise CompiledError(f"schema {manifest.get('schema')!r} is not {schema!r}")
134
+ arrays: dict[str, np.ndarray] = {}
135
+ for entry in manifest["arrays"]:
136
+ path = directory / entry["file"]
137
+ if not path.is_file():
138
+ raise CompiledError(f"array {entry['name']} is missing its file {entry['file']}")
139
+ data = path.read_bytes()
140
+ if verify and sha256_bytes(data) != entry["sha256"]:
141
+ raise CompiledError(
142
+ f"array {entry['name']}: SHA-256 {sha256_bytes(data)} differs from the manifest's {entry['sha256']}"
143
+ )
144
+ dtype = np.dtype(DTYPES[entry["dtype"]]).newbyteorder("<")
145
+ shape = tuple(entry["shape"])
146
+ expected = int(np.prod(shape, dtype=np.int64)) * dtype.itemsize
147
+ if len(data) != expected:
148
+ raise CompiledError(f"array {entry['name']}: {len(data)} bytes where shape {shape} needs {expected}")
149
+ arrays[entry["name"]] = np.frombuffer(data, dtype=dtype).reshape(shape).astype(dtype.newbyteorder("="))
150
+ return Compiled(directory=directory, manifest=manifest, arrays=arrays)
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Janne K. Lappalainen, Fabian D. Tschopp, Mason McGill, Jakob H. Macke, Srinivas C. Turaga
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.