Download flysim/scripts/brian_reference.py from nynefold/flysim-malecns: direct link, hf CLI and curl.
- Browser
- Download file 7.15 kB
-
https://huggingface.co/datasets/nynefold/flysim-malecns/resolve/main/flysim/scripts/brian_reference.py
- Command line
-
hf download hf://datasets/nynefold/flysim-malecns/flysim/scripts/brian_reference.py
-
curl -L -o brian_reference.py https://huggingface.co/datasets/nynefold/flysim-malecns/resolve/main/flysim/scripts/brian_reference.py
7.15 kB
| # /// script | |
| # requires-python = "==3.10.*" | |
| # dependencies = [ | |
| # "brian2==2.5.1", | |
| # "numpy==1.22.3", | |
| # "pandas==1.4.3", | |
| # "pyarrow==11.0.0", | |
| # "joblib==1.2.0", | |
| # "cython==0.29.33", | |
| # "setuptools==67.8.0", | |
| # "sympy==1.12", | |
| # "jinja2==2.11.3", | |
| # "markupsafe==2.0.1", | |
| # "pyparsing==3.0.9", | |
| # ] | |
| # /// | |
| """Brian2 reference runs for the engine check (records/preregistration.md, section 2.1). | |
| Runs Shiu et al.'s ``model.py`` at commit 91bdd1e **unmodified**, from a checkout of | |
| their repository, with the versions of their ``environment_full.yml``. The only | |
| change is ``n_run = 60`` (seed sets A and B), passed in the params dict. Output is | |
| ``<out>/<condition stem>.parquet`` in Shiu's own format. | |
| Each condition runs in a child process, and its save is guarded. Twice the job | |
| segfaulted (exit 139) right after the simulation, while ``run_exp`` built and wrote the | |
| brotli parquet (see the validation log, 2026-11-04), losing 12-25 min of work. The child | |
| therefore pickles the spike table before the parquet write, and writes the parquet | |
| to a temporary name that is renamed only when complete. If the child dies anyway, | |
| this process converts the pickle to an uncompressed parquet (same columns and rows; | |
| only the codec differs) and lists the condition under ``saved_by_fallback`` in | |
| ``brian_env.json``. A crash after a complete parquet keeps the parquet. model.py | |
| itself stays unmodified; only pandas' writer is wrapped. | |
| git clone https://github.com/philshiu/Drosophila_brain_model shiu | |
| git -C shiu checkout 91bdd1e7dcf193f3e7ca5a8933497fcef63b7960 | |
| uv run scripts/brian_reference.py --shiu shiu --out runs/brian [--only E1] [--n-proc 4] | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import importlib.util | |
| import json | |
| import os | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| HERE = Path(__file__).resolve().parent | |
| MANIFEST = HERE.parent / "src" / "flysim" / "validation" / "manifest.py" | |
| def _load_manifest(): | |
| # The manifest is stdlib-only; load it by path so this env needs no flysim. | |
| spec = importlib.util.spec_from_file_location("engine_check_manifest", MANIFEST) | |
| mod = importlib.util.module_from_spec(spec) | |
| sys.modules["engine_check_manifest"] = mod # dataclasses look the module up by name | |
| spec.loader.exec_module(mod) | |
| return mod | |
| def _part(path: Path) -> Path: | |
| return path.with_name(path.name + ".part") | |
| def _safety(path: Path) -> Path: | |
| return path.with_name(path.name.removesuffix(".parquet") + ".spikes.pkl") | |
| def _guard_parquet_writes() -> None: | |
| """In the child: pickle each spike table first, then write the parquet atomically.""" | |
| import pandas as pd # noqa: PLC0415 | |
| original = pd.DataFrame.to_parquet | |
| def to_parquet(self, path, *args, **kwargs): | |
| path = Path(path) | |
| safety = _safety(path) | |
| self.to_pickle(safety) | |
| with open(safety, "rb") as f: | |
| os.fsync(f.fileno()) | |
| original(self, _part(path), *args, **kwargs) | |
| os.replace(_part(path), path) | |
| safety.unlink() | |
| pd.DataFrame.to_parquet = to_parquet | |
| def _settle(path: Path) -> str: | |
| """In the parent, after the child: 'ok', 'fallback' or 'missing'.""" | |
| import pandas as pd # noqa: PLC0415 | |
| if path.is_file(): | |
| pd.read_parquet(path, columns=["t", "trial", "flywire_id"]) # raises if unreadable | |
| _safety(path).unlink(missing_ok=True) | |
| return "ok" | |
| if _safety(path).is_file(): | |
| df = pd.read_pickle(_safety(path)) | |
| df.to_parquet(_part(path), compression=None) | |
| os.replace(_part(path), path) | |
| _safety(path).unlink() | |
| return "fallback" | |
| return "missing" | |
| def main() -> int: | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--shiu", type=Path, required=True, help="checkout of Shiu et al.'s repo") | |
| p.add_argument("--out", type=Path, required=True) | |
| p.add_argument("--only", nargs="*", help="case ids (E1) or condition keys") | |
| p.add_argument("--n-run", type=int, default=60, | |
| help="60, as preregistered; less only to smoke-test") | |
| p.add_argument("--n-proc", type=int, default=-1) | |
| p.add_argument("--child", action="store_true", help=argparse.SUPPRESS) | |
| a = p.parse_args() | |
| if a.child: | |
| return _child(a) | |
| m = _load_manifest() | |
| head = subprocess.run(["git", "-C", str(a.shiu), "rev-parse", "HEAD"], capture_output=True, | |
| text=True, check=True).stdout.strip() | |
| if head != m.SHIU_COMMIT: | |
| raise SystemExit(f"Shiu checkout is at {head}, expected {m.SHIU_COMMIT}") | |
| if subprocess.run(["git", "-C", str(a.shiu), "diff", "--quiet", "HEAD", "--", "model.py"] | |
| ).returncode != 0: | |
| raise SystemExit("model.py is modified; the reference must run it unmodified") | |
| a.out.mkdir(parents=True, exist_ok=True) | |
| conds = [c for c in m.conditions() if not a.only or c.key in a.only or c.case in a.only] | |
| fallback, missing = [], [] | |
| for c in conds: | |
| path = a.out / f"{c.file_stem}.parquet" | |
| if not path.is_file() and not _safety(path).is_file(): | |
| rc = subprocess.run([ | |
| sys.executable, str(Path(__file__).resolve()), "--child", | |
| "--shiu", str(a.shiu), "--out", str(a.out), "--only", c.key, | |
| "--n-run", str(a.n_run), "--n-proc", str(a.n_proc), | |
| ]).returncode | |
| if rc != 0: | |
| print(f">>> {c.key}: child exited with {rc}", flush=True) | |
| state = _settle(path) | |
| print(f">>> {c.key}: {state}", flush=True) | |
| if state == "fallback": | |
| fallback.append(c.key) | |
| elif state == "missing": | |
| missing.append(c.key) | |
| import brian2 # noqa: PLC0415 | |
| (a.out / "brian_env.json").write_text(json.dumps({ | |
| "brian2": brian2.__version__, "python": sys.version, "shiu_commit": head, | |
| "codegen_target": str(brian2.prefs.codegen.target), "n_run": a.n_run, | |
| "saved_by_fallback": fallback, | |
| }, indent=1)) | |
| if missing: | |
| print(f">>> no output for: {' '.join(missing)}", file=sys.stderr) | |
| return 1 | |
| return 0 | |
| def _child(a: argparse.Namespace) -> int: | |
| """Runs the one condition named by ``--only`` through Shiu's ``run_exp``.""" | |
| m = _load_manifest() | |
| _guard_parquet_writes() | |
| sys.path.insert(0, str(a.shiu.resolve())) | |
| from brian2 import Hz # noqa: PLC0415 | |
| from model import default_params, run_exp # noqa: PLC0415 | |
| cases = json.loads((MANIFEST.parent / "cases.json").read_text()) | |
| (c,) = [c for c in m.conditions() if c.key in a.only] | |
| params = dict(default_params) | |
| params["n_run"] = a.n_run | |
| (g1, r1), *rest = c.groups | |
| params["r_poi"] = r1 * Hz | |
| exc2: list[int] = [] | |
| if rest: | |
| (g2, r2), = rest | |
| params["r_poi2"] = r2 * Hz | |
| exc2 = cases["groups"][g2] | |
| run_exp( | |
| exp_name=c.file_stem, | |
| neu_exc=cases["groups"][g1], | |
| neu_exc2=exc2, | |
| path_res=a.out, | |
| path_comp=a.shiu / m.FAFB_COMPLETENESS, | |
| path_con=a.shiu / m.FAFB_CONNECTIVITY, | |
| params=params, | |
| n_proc=a.n_proc, | |
| ) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |