"""Chain-test harness (preregistration, section 4) on synthetic data (no download).""" import json import os from pathlib import Path import numpy as np import pytest from flysim.validation import chains as ch from flysim.validation.manifest import SET_A, SET_B CONNECTOME = Path(os.environ.get( "FLYSIM_CONNECTOME", Path(__file__).parents[2] / "data" / "connectome-v1")) BODIES = {"DNp01": [1, 2], "MDN": [3, 4, 5, 6], "DNp09": [7, 8]} SIDES = {"DNp01": ["L", "R"], "MDN": ["L", "R", "L", "R"], "DNp09": ["L", "R"]} def test_keys_and_task_counts(): assert ch.stim_key("LC16+LPLC1+LPLC2", 100.0) == "LC16+LPLC1+LPLC2/100Hz" assert ch.control_key(55, 3) == "control-55/03" assert ch.file_stem("LC16+LPLC1+LPLC2/25Hz") == "LC16_LPLC1_LPLC2__25Hz" t = ch.tasks_of("primary") # 3 chains x (5 rates x 30 + 30 set B at 100 Hz) + 3 sizes x 20 sets x 10 trials assert len(t) == 3 * (5 * 30 + 30) + 3 * 20 * 10 assert len(set(t)) == len(t) assert ("LC4/100Hz", 59) in t and ("LC4/25Hz", 30) not in t assert ("control-115/19", 9) in t and ("control-115/19", 10) not in t assert len(ch.tasks_of("lc16-alt")) == 5 * 30 + 30 + 20 * 10 assert ch.rate_of_key("control-94/00") == 100.0 assert ch.rate_of_key("LC9/25Hz") == 25.0 def _cond(key, rates_hz, *, trials=SET_A, late=0.0, net=(1000, 2), seed=0): """Synthetic summary: Poisson counts per body at the given mean rate per readout.""" rng = np.random.default_rng(seed) tr = list(trials) counts = {r: rng.poisson(rates_hz.get(r, 0.0) * ch.STIM_S, (len(tr), len(b))).tolist() for r, b in BODIES.items()} return {"key": key, "trials": tr, "bodies": BODIES, "sides": SIDES, "counts": counts, "first_ms": {r: [10.0 if any(c) else None for c in counts[r]] for r in BODIES}, "late_readout": [i < late * len(tr) for i in range(len(tr))], "net_stim": [net[0]] * len(tr), "net_late": [net[1]] * len(tr), "net_stim_nonstim": [net[0] // 2] * len(tr), "net_late_nonstim": [net[1]] * len(tr)} def _data(stimuli, gain, control_hz=0.5, **kw): """gain: stimulus -> readout -> rate at 100 Hz (scaled linearly with input rate).""" conds = {} for s in stimuli: for i, r in enumerate(ch.RATES): key = ch.stim_key(s, r) trials = [*SET_A, *SET_B] if r == ch.PRIMARY_RATE else SET_A conds[key] = _cond(key, {ro: g * r / 100 for ro, g in gain[s].items()}, trials=trials, seed=i, **kw) for k in range(ch.CONTROL_SETS): key = ch.control_key(ch.SIZES[s], k) conds[key] = _cond(key, dict.fromkeys(BODIES, control_hz), trials=ch.CONTROL_TRIALS, seed=100 + k) return ch.Trials({"conditions": conds}) GOOD = {"LC4": {"DNp01": 40}, "LC16": {"MDN": 30, "DNp09": 2}, "LC9": {"DNp09": 25, "DNp01": 1, "MDN": 1}} def test_all_primary_chains_pass(): t = _data(["LC4", "LC16", "LC9"], GOOD) att = ch.judge_all(t) for s in ("LC4", "LC16", "LC9"): assert len(att[s]) == 1 and att[s][0].passed, att[s][0].crits assert [c.name for c in att["LC9"][0].crits] == [ "C1 activation", "C2 beats control", "C3 dose response", "C4 stability", "C5 DNp09 > DNp01", "C5 DNp09 > MDN"] assert [c.name for c in att["LC4"][0].crits][-1] == "C4 stability" # no C5 for LC4 md = ch.render(t, att) assert "LC4 → DNp01 (escape): **PASS (primary)**" in md def test_c1_fails_and_lc9_relative_reading_passes(): gain = {**GOOD, "LC9": {"DNp09": 1.5, "DNp01": 0.0, "MDN": 0.0}} att = ch.judge_all(_data(["LC4", "LC16", "LC9"], gain, control_hz=0.0)) lc9 = att["LC9"] assert [a.label for a in lc9] == ["primary", "alternative: relative reading"] assert not lc9[0].passed and lc9[0].crits[0].name == "C1 activation" assert not lc9[0].crits[0].passed assert lc9[1].passed and lc9[1].crits[0].name == "C2 beats control" def test_lc4_has_no_alternative(): gain = {**GOOD, "LC4": {"DNp01": 0.5}} att = ch.judge_all(_data(["LC4", "LC16", "LC9"], gain)) assert len(att["LC4"]) == 1 and not att["LC4"][0].passed def test_lc16_alternatives_in_order(): bad = {**GOOD, "LC16": {"MDN": 1.0, "DNp09": 3.0}} t = _data(["LC4", "LC16", "LC9"], bad) att = ch.judge_all(t) assert [a.label for a in att["LC16"]] == ["primary", "alternative step 1: LC16 + LPLC1 + LPLC2"] assert att["LC16"][1].crits is None # not run yet assert "NOT JUDGED" in ch.render(t, att) # step 1 run, fails on specificity; it makes specificity worse than LC16 alone, # so step 2 uses LC16 alone (and still fails C5 there) t2 = _data(["LC4", "LC16", "LC9", "LC16+LPLC1+LPLC2"], {**bad, "LC16+LPLC1+LPLC2": {"MDN": 5.0, "DNp09": 9.0}}) a2 = ch.judge_all(t2)["LC16"] assert [a.label for a in a2][1:] == ["alternative step 1: LC16 + LPLC1 + LPLC2", "alternative step 2: relative reading"] assert a2[2].stimulus == "LC16" and a2[2].relative and not a2[2].passed # step 1 passes: no step 2 t3 = _data(["LC4", "LC16", "LC9", "LC16+LPLC1+LPLC2"], {**bad, "LC16+LPLC1+LPLC2": {"MDN": 30.0, "DNp09": 2.0}}) a3 = ch.judge_all(t3)["LC16"] assert len(a3) == 2 and a3[1].passed def test_stability_criterion(): t = _data(["LC4"], GOOD, late=0.1) # 10% of trials with late readout spikes crit = {c.name: c for c in ch.judge_chain(t, ch.CHAINS[0], "LC4")} assert not crit["C4 stability"].passed t = _data(["LC4"], GOOD, net=(1000, 10)) # ratio (10/0.2)/(1000/0.3) = 0.015 crit = {c.name: c for c in ch.judge_chain(t, ch.CHAINS[0], "LC4")} assert not crit["C4 stability"].passed assert ch.Trials.stability(t, ch.stim_key("LC4", 100.0))[1] == pytest.approx(0.015) def test_rates_per_side_and_set(): t = _data(["LC4"], GOOD) k = ch.stim_key("LC4", 100.0) assert len(t.rates(k, "MDN")) == 30 and len(t.rates(k, "MDN", None)) == 60 both = t.rates(k, "MDN") left, right = t.rates(k, "MDN", side="L"), t.rates(k, "MDN", side="R") assert np.allclose(both, (left + right) / 2) def _neurons(): types = ["VP"] * 40 + ["LC4"] * 3 + ["VP"] * 5 side = ["R"] * 30 + ["L"] * 10 + ["R"] * 3 + ["R"] * 5 sc = ["visual_projection"] * 43 + ["ol_intrinsic"] * 5 sign = [1] * 25 + [-1] * 5 + [1] * 18 return ch.Neurons(np.arange(100, 148, dtype=np.int64), np.asarray(types, object), np.asarray(side, object), np.asarray(sc, object), np.asarray(sign, np.int8)) def test_control_pool_rule_and_draw(monkeypatch): n = _neurons() pool = n.control_pool() # right side, sign +1, visual_projection, not LC4: bodies 100..124 assert pool.tolist() == list(range(100, 125)) monkeypatch.setattr(ch, "SIZES", {"LC4": 3, "X": 5}) d1, d2 = ch.draw_controls(n), ch.draw_controls(n) assert d1 == d2 and d1["pool_size"] == 25 assert all(len(s) == 3 and len(set(s)) == 3 and set(s) <= set(pool.tolist()) for s in d1["sets"]["3"]) assert len(d1["sets"]["5"]) == ch.CONTROL_SETS def test_committed_controls_shape(): d = ch.load_controls() assert d["seed"] == 20261103 and d["pool_size"] == 3533 assert {k: (len(v), {len(s) for s in v}) for k, v in d["sets"].items()} == { "55": (20, {55}), "94": (20, {94}), "115": (20, {115}), "251": (20, {251})} @pytest.mark.skipif(not CONNECTOME.exists(), reason="connectome-v1 not fetched") def test_committed_controls_match_the_draw_rule(): n = ch.Neurons.load(CONNECTOME) assert ch.draw_controls(n) == json.loads(ch.CONTROLS_JSON.read_text()) for s, size in ch.SIZES.items(): assert len(ch.targets_of(ch.stim_key(s, 100.0), n, ch.load_controls())) == size