Download flysim/tests/test_live.py from nynefold/flysim-malecns: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/datasets/nynefold/flysim-malecns/resolve/main/flysim/tests/test_live.py
- Command line
-
hf download hf://datasets/nynefold/flysim-malecns/flysim/tests/test_live.py
-
curl -L -o test_live.py https://huggingface.co/datasets/nynefold/flysim-malecns/resolve/main/flysim/tests/test_live.py
18 kB
| """Live simulation worker on a tiny synthetic network; one check on the real | |
| connectome when it is fetched.""" | |
| import asyncio | |
| import json | |
| import math | |
| import os | |
| import threading | |
| from pathlib import Path | |
| import numpy as np | |
| import pytest | |
| from flysim.engine import CpuEngine, SynapseMatrix, poisson_schedule, trial_rng | |
| from flysim.live import ( | |
| N_CHUNKS, | |
| STIMULI, | |
| BlockRequest, | |
| BlockSpec, | |
| ConnectomeSource, | |
| InMemorySource, | |
| InvalidRequest, | |
| LiveConfig, | |
| LiveModel, | |
| LiveService, | |
| Recording, | |
| ReplayCache, | |
| WorkerPool, | |
| expected_wait, | |
| make_engine, | |
| model_fingerprint, | |
| round_rate, | |
| run_block, | |
| ) | |
| from flysim.live import model as lm | |
| from flysim.validation import chains | |
| CONNECTOME = Path(os.environ.get( | |
| "FLYSIM_CONNECTOME", Path(__file__).parents[2] / "data" / "connectome-v1")) | |
| TRIALS_JSON = Path(__file__).parents[2] / "records" / "results" / "chain-tests-trials.json" | |
| def synthetic() -> InMemorySource: | |
| """40 neurons: five right-side neurons per stimulus type, one left LC9 (never | |
| stimulated), the 8 readout bodies, and 16 others with random recurrent edges.""" | |
| types = (["LC4"] * 5 + ["LC16"] * 5 + ["LC9"] * 6 + ["DNp01"] * 2 + ["MDN"] * 4 | |
| + ["DNp09"] * 2 + ["other"] * 16) | |
| sides = (["R"] * 15 + ["L"] + ["L", "R"] + ["L", "R", "L", "R"] + ["L", "R"] | |
| + [None] * 16) | |
| n = len(types) | |
| edges = [] | |
| for src, dst in (((0, 5), 17), ((5, 10), 19), ((5, 10), 21), ((10, 15), 23)): | |
| edges += [(i, dst, 120) for i in range(*src)] | |
| rng = np.random.default_rng(1) | |
| for i in range(16, n): | |
| for j in rng.choice(np.arange(16, n), 4, replace=False): | |
| edges.append((i, int(j), int(rng.integers(-60, 90)))) | |
| edges += [(23, k, 80) for k in range(24, 28)] + [(17, k, 80) for k in range(28, 32)] | |
| pre, post, w = (np.array(x) for x in zip(*edges, strict=True)) | |
| neurons = chains.Neurons( | |
| body=np.arange(1000, 1000 + n, dtype=np.int64), | |
| type=np.array(types, dtype=object), side=np.array(sides, dtype=object), | |
| superclass=np.array(["x"] * n, dtype=object), sign=np.ones(n, dtype=np.int8)) | |
| return InMemorySource(SynapseMatrix.from_edges(pre, post, w, n), neurons) | |
| def src() -> InMemorySource: | |
| return synthetic() | |
| def model(src: InMemorySource) -> LiveModel: | |
| return LiveModel.build(src.neurons, check_sizes=False) | |
| def test_stimuli_and_statuses_follow_the_chain_tests(): | |
| assert {s: STIMULI[s].status for s in STIMULI} == { | |
| "LC4": "not_validated", "LC16": "not_validated", "LC9": "validated"} | |
| assert (STIMULI["LC9"].chain, STIMULI["LC9"].readout) == ("approach", "DNp09") | |
| assert STIMULI["LC4"].readout == "DNp01" and STIMULI["LC16"].readout == "MDN" | |
| assert lm.PARAMS.w_syn == pytest.approx(0.1571, abs=1e-4) | |
| assert (lm.BLOCK_STEPS, lm.STIM_STEPS, lm.CHUNK_STEPS, N_CHUNKS) == (6000, 3000, 100, 60) | |
| def test_model_slots_and_targets(model: LiveModel): | |
| assert model.slots == (("DNp01", "L"), ("DNp01", "R"), ("MDN", "L"), ("MDN", "R"), | |
| ("DNp09", "L"), ("DNp09", "R")) | |
| assert model.targets["LC9"].tolist() == [10, 11, 12, 13, 14] # right side only | |
| assert model.slot_of[23] == 5 and model.slot_of[30] == -1 | |
| with pytest.raises(ValueError, match="the preregistration says"): | |
| LiveModel.build(synthetic().neurons, check_sizes=True) | |
| def test_validation_and_rounding(): | |
| BlockSpec("LC9", 0.0, 0).validate() | |
| BlockSpec("LC9", 200.0, 2**31 - 1).validate() | |
| for bad in (BlockSpec("LC10", 50, 0), BlockSpec("LC9", -1, 0), BlockSpec("LC9", 201, 0), | |
| BlockSpec("LC9", math.nan, 0), BlockSpec("LC9", 50, -1), | |
| BlockSpec("LC9", 50, 2**31)): | |
| with pytest.raises(InvalidRequest): | |
| bad.validate() | |
| assert round_rate(97.6, 5) == 100.0 and round_rate(2.4, 5) == 0.0 | |
| assert round_rate(199.0, 5) == 200.0 and round_rate(12.34, 0) == 12.34 | |
| assert BlockSpec("LC9", 100.0, 3).condition() == chains.stim_key("LC9", 100.0) | |
| def _reference(src: InMemorySource, model: LiveModel, spec: BlockSpec, experiment: str): | |
| """The chain-test way: one reset, one schedule, one advance over the whole trial.""" | |
| eng = CpuEngine(np.float32, skip_rest=False) | |
| eng.load(src.matrix, lm.PARAMS) | |
| rng = trial_rng(experiment, spec.condition(), spec.seed) | |
| eng.schedule_inputs(poisson_schedule(rng, model.targets[spec.stimulus], spec.rate_hz, 0, | |
| lm.STIM_STEPS, lm.PARAMS.dt)) | |
| eng.advance_to(lm.BLOCK_STEPS) | |
| return eng.spikes_since(0) | |
| def test_chunks_equal_one_whole_trial(src: InMemorySource, model: LiveModel): | |
| eng = make_engine(src.matrix) | |
| spec = BlockSpec("LC9", 100.0, 7) | |
| chunks = list(run_block(eng, model, spec, "chain-tests")) | |
| assert [c.index for c in chunks] == list(range(N_CHUNKS)) | |
| for c in chunks: | |
| assert c.step1 - c.step0 == 100 | |
| assert np.all((c.steps >= c.step0) & (c.steps < c.step1)) | |
| slot = model.slot_of[c.neurons] | |
| assert c.counts.tolist() == np.bincount(slot[slot >= 0], minlength=6).tolist() | |
| steps = np.concatenate([c.steps for c in chunks]) | |
| neurons = np.concatenate([c.neurons for c in chunks]) | |
| ref_s, ref_n = _reference(src, model, spec, "chain-tests") | |
| assert len(ref_s) > 100 | |
| assert np.array_equal(steps, ref_s) and np.array_equal(neurons, ref_n) | |
| # the stimulated chain drives its readout: DNp09 right, not left | |
| total = np.sum([c.counts for c in chunks], axis=0) | |
| assert total[5] > 0 and total[4] == 0 | |
| # no input after 300 ms | |
| assert not np.any(np.isin(neurons[steps >= lm.STIM_STEPS], model.targets["LC9"])) | |
| def test_every_block_starts_from_rest(src: InMemorySource, model: LiveModel): | |
| eng = make_engine(src.matrix) | |
| a = [c.neurons.tolist() for c in run_block(eng, model, BlockSpec("LC4", 150.0, 1))] | |
| list(run_block(eng, model, BlockSpec("LC16", 200.0, 2))) | |
| b = [c.neurons.tolist() for c in run_block(eng, model, BlockSpec("LC4", 150.0, 1))] | |
| assert a == b | |
| c = [c.neurons.tolist() for c in run_block(eng, model, BlockSpec("LC4", 150.0, 2))] | |
| assert a != c # another seed, other input trains | |
| def _recording(src, model, spec, experiment="live") -> Recording: | |
| eng = make_engine(src.matrix) | |
| return Recording.from_chunks(spec, experiment, model.n, model.slots, | |
| run_block(eng, model, spec, experiment), 1.5) | |
| def test_recording_roundtrip_and_cache(tmp_path: Path, src, model): | |
| spec = BlockSpec("LC9", 100.0, 3) | |
| rec = _recording(src, model, spec) | |
| fp = model_fingerprint(src, "live") | |
| cache = ReplayCache(tmp_path, fp) | |
| assert cache.get(spec) is None and cache.find(spec) is None | |
| path = cache.put(rec) | |
| assert path.parent.name == fp[:16] and path.name == "LC9_100Hz_s3.npz" | |
| back = cache.get(spec) | |
| assert back is not None and back.spec == spec and back.slots == model.slots | |
| for x, y in zip(rec.chunks(), back.chunks(), strict=True): | |
| assert np.array_equal(x.steps, y.steps) and np.array_equal(x.neurons, y.neurons) | |
| assert np.array_equal(x.counts, y.counts) | |
| s = back.summary() | |
| assert s["readouts_block"]["DNp09"]["R"] == int(rec.chunk_counts[:, 5].sum()) | |
| assert s["readouts_stimulus"]["DNp09"]["R"] == int(rec.chunk_counts[:30, 5].sum()) | |
| # the busy fallback takes another seed of the same stimulus and rate | |
| other = cache.find(BlockSpec("LC9", 100.0, 99)) | |
| assert other is not None and other.spec.seed == 3 | |
| assert cache.find(BlockSpec("LC9", 50.0, 3)) is None | |
| assert cache.seeds("LC9", 100.0) == [3] | |
| # another model (or experiment) never sees these recordings | |
| assert ReplayCache(tmp_path, model_fingerprint(src, "chain-tests")).find(spec) is None | |
| # a damaged file is a miss | |
| path.write_bytes(b"not an npz") | |
| assert cache.get(spec) is None | |
| def test_cache_evicts_stale_fingerprints_then_least_recently_used(tmp_path: Path, src, model): | |
| import os | |
| recs = [_recording(src, model, BlockSpec("LC9", 100.0, s)) for s in range(3)] | |
| stale = ReplayCache(tmp_path, model_fingerprint(src, "chain-tests")) | |
| old = stale.put(recs[0]) | |
| cache = ReplayCache(tmp_path, model_fingerprint(src, "live")) | |
| paths = [cache.put(r) for r in recs] | |
| size = paths[0].stat().st_size | |
| for k, p in enumerate(paths): # put order = age, seed 0 oldest | |
| os.utime(p, (1000 + k, 1000 + k)) | |
| assert cache.get(BlockSpec("LC9", 100.0, 0)) is not None # a replay is a use | |
| cache.max_bytes = int(2.5 * size) | |
| assert cache.evict() == 2 # the stale recording, then seed 1 (least recently used) | |
| assert not old.exists() | |
| assert cache.seeds("LC9", 100.0) == [0, 2] | |
| cache.max_bytes = None | |
| assert cache.evict() == 0 | |
| def test_fingerprints(tmp_path: Path, src): | |
| assert model_fingerprint(src, "live") == model_fingerprint(synthetic(), "live") | |
| other = synthetic() | |
| w = other.matrix.weights.copy() | |
| w[0] += 1 | |
| changed = InMemorySource(SynapseMatrix(other.matrix.indptr, other.matrix.indices, w), | |
| other.neurons) | |
| assert model_fingerprint(changed, "live") != model_fingerprint(src, "live") | |
| d = tmp_path / "c" | |
| d.mkdir() | |
| (d / "SHA256SUMS").write_text("aa matrix-full.tar.zst\nbb neurons.parquet\ncc x\n") | |
| fp1 = ConnectomeSource(d).fingerprint() | |
| (d / "SHA256SUMS").write_text("aa matrix-full.tar.zst\nbb neurons.parquet\ndd x\n") | |
| assert ConnectomeSource(d).fingerprint() == fp1 # other files do not matter | |
| (d / "SHA256SUMS").write_text("ab matrix-full.tar.zst\nbb neurons.parquet\n") | |
| assert ConnectomeSource(d).fingerprint() != fp1 | |
| def test_expected_wait(): | |
| assert expected_wait(10.0, 0, [], 0, 3.0) == math.inf | |
| assert expected_wait(10.0, 2, [], 0, 3.0) == 0.0 | |
| assert expected_wait(10.0, 1, [9.0], 0, 3.0) == pytest.approx(2.0) | |
| assert expected_wait(10.0, 1, [9.0], 2, 3.0) == pytest.approx(8.0) | |
| assert expected_wait(10.0, 2, [9.0], 1, 3.0) == pytest.approx(2.0) | |
| assert expected_wait(10.0, 2, [9.0, 10.0], 2, 3.0) == pytest.approx(5.0) | |
| assert expected_wait(10.0, 1, [1.0], 0, 3.0) == 0.0 # overdue counts as free now | |
| # ----------------------------------------------------------------------------- pool | |
| def _collect(pool: WorkerPool, spec: BlockSpec, timeout: float = 120.0): | |
| done = threading.Event() | |
| events: list = [] | |
| def cb(kind, payload): | |
| events.append((kind, payload)) | |
| if kind in ("done", "failed"): | |
| done.set() | |
| pool.submit(spec, cb) | |
| assert done.wait(timeout), events | |
| return events | |
| def pool(tmp_path_factory, src): | |
| p = WorkerPool(src, 1, cache_root=tmp_path_factory.mktemp("cache"), compute_ratio_prior=5.0) | |
| p.start() | |
| yield p | |
| p.close() | |
| def test_pool_runs_blocks_in_a_worker_process(pool: WorkerPool, src, model): | |
| spec = BlockSpec("LC9", 100.0, 5) | |
| events = _collect(pool, spec) | |
| kinds = [k for k, _ in events] | |
| assert kinds == ["started"] + ["chunk"] * N_CHUNKS + ["done"] | |
| assert events[0][1] == (model.n, model.slots) | |
| ref = list(run_block(make_engine(src.matrix), model, spec)) | |
| for (_, got), want in zip(events[1:-1], ref, strict=True): | |
| assert np.array_equal(got.neurons, want.neurons) | |
| assert np.array_equal(got.counts, want.counts) | |
| compute_s, summary = events[-1][1] | |
| assert compute_s > 0 and summary["spikes"] == sum(len(c.neurons) for c in ref) | |
| assert pool.block_s < 5.0 * lm.BLOCK_S # the estimate moved toward the measurement | |
| assert pool.ready == 1 and pool.queued == 0 | |
| assert ReplayCache(pool._cfg.cache_root, pool.fingerprint).get(spec) is not None | |
| assert pool.expected_wait() == 0.0 | |
| def test_pool_reports_a_worker_that_cannot_load(tmp_path: Path): | |
| p = WorkerPool(ConnectomeSource(tmp_path / "missing"), 1) | |
| p.start() | |
| try: | |
| events = _collect(p, BlockSpec("LC9", 100.0, 0)) | |
| assert events[-1][0] == "failed" and "load" in events[-1][1] | |
| assert p.error is not None and p.expected_wait() == math.inf | |
| finally: | |
| p.close() | |
| # ----------------------------------------------------------------------------- service | |
| def _drain(service: LiveService, req: BlockRequest) -> list[dict]: | |
| async def go(): | |
| return [m async for m in service.stream(req)] | |
| return asyncio.run(go()) | |
| def test_service_live_then_repeat_replays_the_same_block(tmp_path: Path, src, model): | |
| svc = LiveService(src, LiveConfig(workers=1, cache_dir=tmp_path, rate_step_hz=5.0)) | |
| svc.start() | |
| try: | |
| live = _drain(svc, BlockRequest("LC9", 98.0, 4)) | |
| again = _drain(svc, BlockRequest("LC9", 101.0, 4)) | |
| finally: | |
| svc.close() | |
| assert [m["type"] for m in live] == ["queued", "start"] + ["chunk"] * N_CHUNKS + ["end"] | |
| assert [m["type"] for m in again] == ["start"] + ["chunk"] * N_CHUNKS + ["end"] | |
| for m in live + again: # every message discloses the chain status and the source | |
| assert m["chain_status"] == "validated" and m["chain"] == "approach" | |
| assert {m["source"] for m in live} == {"live"} and {m["source"] for m in again} == {"replay"} | |
| start = live[1] | |
| assert start["rate_hz"] == 100.0 and start["rate_hz_requested"] == 98.0 | |
| assert start["block"]["starts_from_rest"] and start["block"]["chunks"] == 60 | |
| assert start["readouts"] == {"DNp01": ["L", "R"], "MDN": ["L", "R"], "DNp09": ["L", "R"]} | |
| p = start["pacing"] | |
| min_stretch = LiveConfig().min_stretch | |
| assert p["stretch"] == pytest.approx(max(min_stretch, p["compute_ratio"] * 1.2), abs=1e-3) | |
| assert again[0]["replay_reason"] == "repeat" | |
| assert again[0]["pacing"]["stretch"] == min_stretch | |
| strip = lambda ms: [{k: v for k, v in m.items() if k not in ("run", "source")} # noqa: E731 | |
| for m in ms if m["type"] == "chunk"] | |
| assert strip(live) == strip(again) | |
| ref = list(run_block(make_engine(src.matrix), model, BlockSpec("LC9", 100.0, 4))) | |
| assert [m["neurons"] for m in live[2:-1]] == [c.neurons.tolist() for c in ref] | |
| assert live[5]["t0_ms"] == 30.0 and live[5]["t1_ms"] == 40.0 | |
| assert all(0 <= s < 100 for m in live[2:-1] for s in m["steps"]) | |
| json.dumps(live) # JSON-ready | |
| class BusyPool: | |
| """Stands in for a saturated pool.""" | |
| error = None | |
| queued = 0 | |
| compute_ratio = 6.0 | |
| def __init__(self, wait: float) -> None: | |
| self.wait = wait | |
| self.submitted: list = [] | |
| def expected_wait(self) -> float: | |
| return self.wait | |
| def submit(self, spec, cb): | |
| self.submitted.append(spec) | |
| cb("failed", "stub") | |
| def test_service_busy_falls_back_to_a_replay(tmp_path: Path, src, model): | |
| cfg = LiveConfig(workers=0, cache_dir=tmp_path, serve_repeats=False, max_wait_s=2.0) | |
| busy = BusyPool(5.0) | |
| svc = LiveService(src, cfg, pool=busy) # type: ignore[arg-type] | |
| svc.cache.put(_recording(src, model, BlockSpec("LC4", 50.0, 2))) # type: ignore[union-attr] | |
| out = _drain(svc, BlockRequest("LC4", 50.0, 11)) | |
| assert out[0]["type"] == "start" and out[0]["source"] == "replay" | |
| assert out[0]["replay_reason"] == "busy" and out[0]["seed"] == 2 | |
| assert out[0]["seed_requested"] == 11 and out[0]["chain_status"] == "not_validated" | |
| assert busy.submitted == [] | |
| # no recording for this rate: queued live anyway | |
| out = _drain(svc, BlockRequest("LC4", 100.0, 11)) | |
| assert [m["type"] for m in out] == ["queued", "error"] and busy.submitted | |
| # with a short wait, live even though a recording of another seed exists | |
| busy.wait = 0.5 | |
| out = _drain(svc, BlockRequest("LC4", 50.0, 11)) | |
| assert out[0]["type"] == "queued" | |
| # serve_repeats off: an exact recording is not replayed while workers are free | |
| out = _drain(svc, BlockRequest("LC4", 50.0, 2)) | |
| assert out[0]["type"] == "queued" | |
| def test_service_refuses_bad_requests_and_no_workers(tmp_path: Path, src): | |
| svc = LiveService(src, LiveConfig(workers=0, cache_dir=tmp_path)) | |
| for req in (BlockRequest("LC10", 50, 0), BlockRequest("LC9", 250, 0), | |
| BlockRequest("LC9", 50, -3), BlockRequest("LC9", 50, 0, min_stretch=0.5)): | |
| (m,) = _drain(svc, req) | |
| assert m["type"] == "error" | |
| (m,) = _drain(svc, BlockRequest("LC9", 50, 0)) | |
| assert m["type"] == "error" and "no recording" in m["detail"] | |
| assert m["chain_status"] == "validated" | |
| info = svc.info() | |
| assert info["live"] is False | |
| assert [s["chain_status"] for s in info["stimuli"]] == [ | |
| "not_validated", "not_validated", "validated"] | |
| # ----------------------------------------------------------------------------- real data | |
| def test_real_connectome_block_is_the_recorded_chain_test_trial(tmp_path: Path): | |
| """LC9 at 100 Hz, trial 0, under the chain-test seed key: the same readout counts as | |
| the committed chain-test record (live default kernel, chunked stepping, mapped | |
| matrix).""" | |
| src = ConnectomeSource(CONNECTOME, unpack_dir=tmp_path) | |
| matrix, neurons = src.load() | |
| model = LiveModel.build(neurons) | |
| chunks = list(run_block(make_engine(matrix), model, BlockSpec("LC9", 100.0, 0), "chain-tests")) | |
| rec = json.loads(TRIALS_JSON.read_text())["conditions"]["LC9/100Hz"] | |
| k = rec["trials"].index(0) | |
| steps = np.concatenate([c.steps for c in chunks]) | |
| neurons_ = np.concatenate([c.neurons for c in chunks]) | |
| assert int(np.sum(steps < lm.STIM_STEPS)) == rec["net_stim"][k] | |
| assert int(np.sum((steps >= 4000) & (steps < 6000))) == rec["net_late"][k] | |
| for r, bodies in rec["bodies"].items(): | |
| idx = neurons.index_of(bodies) | |
| order = np.argsort(neurons.body[idx]) | |
| want = dict(zip(bodies, rec["counts"][r][k], strict=True)) | |
| got = {int(neurons.body[i]): int(np.sum((neurons_ == i) & (steps < lm.STIM_STEPS))) | |
| for i in idx[order]} | |
| assert got == want, r | |