"""Tests on synthetic event graphs with planted cascades. No domain data, no domain ground truth. Run: python3 test_cascade_core.py """ import collections, random, sys sys.path.insert(0, ".") from cascade_core import (Config, CycleError, Event, Graph, Link, null_diagnostics, run_hash, suggest_scale, tail_p, window_sweep) CFG = Config(windows={"A": (0.0, 10.0), "B": (0.0, 50.0)}) def plant(rng, n_cascades=40, noise_events=200, horizon=5000.0, shapes=("relay", "broadcast", "branching"), in_window_noise=0, entity_mode="station"): """Plant cascades far apart in time, add isolated noise events and out-of-window noise links.""" events, links, planted = [], [], [] eid = 0 for c in range(n_cascades): shape = shapes[c % len(shapes)] size = rng.randint(3, 9) t0 = 100.0 * c + rng.uniform(0, 5) ids = [] for _ in range(size): ids.append(f"e{eid}") eid += 1 times = {ids[0]: t0} lt = "A" if c % 2 == 0 else "B" w = 10.0 if lt == "A" else 50.0 for i in range(1, size): parent = ids[i - 1] if shape == "relay" else (ids[0] if shape == "broadcast" else ids[rng.randrange(0, i)]) times[ids[i]] = times[parent] + rng.uniform(0.5, w * 0.9) * (0.2 if shape == "relay" else 1.0) links.append(Link(parent, ids[i], lt, direction_basis="time")) for i in ids: ent = f"station{c % 7}" if entity_mode == "station" else f"ent{rng.randrange(30)}" events.append(Event(i, times[i], entities=((ent, "at"),))) planted.append((ids[0], set(ids), shape)) for _ in range(noise_events): events.append(Event(f"n{eid}", rng.uniform(0, horizon), entities=((f"ent{rng.randrange(30)}" if entity_mode != "station" else "noise", "at"),))) eid += 1 noise = [e for e in events if e.id.startswith("n")] for _ in range(in_window_noise): a, b = rng.sample(noise, 2) events_t = abs(a.time - b.time) if events_t <= 10: links.append(Link(a.id, b.id, "A")) for _ in range(300): # out-of-window noise links among noise events (must be dropped) a, b = rng.sample(noise, 2) links.append(Link(a.id, b.id, "A")) return events, links, planted def test_invariants(): rng = random.Random(1) events, links, _ = plant(rng, in_window_noise=2000) g = Graph(events, links, CFG) # raises if not a DAG flat = [e for ep in g.episodes for e in ep] assert len(flat) == len(set(flat)) == len(events), "episodes must partition the events" for root, members in g.cascades(): assert g.indeg[root] == 0, "root has an incoming link" eps = {g.episode_of[m] for m in members} assert len(eps) == 1, "cascade must lie inside one episode" for k in g.kept: assert g.events[k["src"]].time <= g.events[k["dst"]].time return "invariants hold (DAG, partition, cascade inside one episode, roots, time order)" def test_recovery_exact(): rng = random.Random(2) events, links, planted = plant(rng, in_window_noise=0) g = Graph(events, links, CFG) found = {r: set(m) for r, m in g.cascades(min_size=2)} hit = sum(1 for root, mem, _ in planted if found.get(root) == mem) assert hit == len(planted), f"recovered {hit} of {len(planted)}" shapes_ok = 0 for root, mem, shape in planted: d = g.descriptors(sorted(mem), root) expected = {"relay": "Relay", "broadcast": "Broadcast", "branching": None}[shape] if expected is None or d["shape"] == expected: shapes_ok += 1 assert shapes_ok == len(planted) return f"all {len(planted)} planted cascades recovered exactly; strict shape labels agree for relay and broadcast" def test_recovery_with_noise(): rng = random.Random(3) events, links, planted = plant(rng, in_window_noise=3000) g = Graph(events, links, CFG) found = {r: set(m) for r, m in g.cascades(min_size=2)} hit = sum(1 for root, mem, _ in planted if found.get(root) == mem) noise_cascades = [m for r, m in g.cascades(min_size=2) if r.startswith("n")] assert hit == len(planted) return f"planted cascades unaffected by in-window noise ({hit}/{len(planted)}); {len(noise_cascades)} noise candidates appear, median size {sorted(len(m) for m in noise_cascades)[len(noise_cascades)//2] if noise_cascades else 0}" def test_window_per_type(): ev = [Event("a", 0), Event("b", 20), Event("c", 0), Event("d", 20)] ln = [Link("a", "b", "A"), Link("c", "d", "B")] g = Graph(ev, ln, CFG) kept = {(k["src"], k["dst"]) for k in g.kept} assert kept == {("c", "d")}, kept assert g.dropped["outside_window"] == 1 return "gap 20 is dropped for type A (window 10) and kept for type B (window 50)" def test_ties(): ev = [Event("a", 5), Event("b", 5)] g1 = Graph(ev, [Link("a", "b", "A")], Config(windows={"A": (0, 10)}, tie_rule="drop")) assert not g1.kept and g1.dropped["tie_dropped"] == 1 g2 = Graph(ev, [Link("a", "b", "A", direction_basis="evidence")], Config(windows={"A": (0, 10)})) assert len(g2.kept) == 1 and g2.kept[0]["src"] == "a" g3 = Graph([Event("a", 5), Event("b", 1)], [Link("a", "b", "A", direction_basis="evidence")], CFG) assert not g3.kept and g3.dropped["evidence_contradicts_time"] == 1 return "same-time link: dropped under 'drop', kept when the evidence gives the direction, contradiction reported" def test_cycle_detection(): ev = [Event("a", 1), Event("b", 1), Event("c", 1)] ln = [Link(x, y, "A", direction_basis="evidence") for x, y in [("a", "b"), ("b", "c"), ("c", "a")]] try: Graph(ev, ln, Config(windows={"A": (0, 10)})) except CycleError: return "evidence-directed cycle at equal times raises CycleError" raise AssertionError("cycle not detected") def test_descriptors(): def build(edges, times): ev = [Event(i, t) for i, t in times.items()] return Graph(ev, [Link(a, b, "A") for a, b in edges], Config(windows={"A": (0, 100)})) path = build([("a", "b"), ("b", "c"), ("c", "d")], dict(a=0, b=1, c=2, d=3)) d = path.descriptors(["a", "b", "c", "d"], "a") assert d["shape"] == "Relay" and d["depth_ratio"] == 1.0 and not d["joined"] and abs(d["path_length_ratio"] - 1.0) < 1e-9 star = build([("a", "b"), ("a", "c"), ("a", "d")], dict(a=0, b=1, c=2, d=3)) d = star.descriptors(["a", "b", "c", "d"], "a") assert d["shape"] == "Broadcast" and d["fan_ratio"] == 1.0 and d["path_length_ratio"] < 1.0 ff = build([("a", "b"), ("a", "c"), ("b", "c")], dict(a=0, b=1, c=2)) d = ff.descriptors(["a", "b", "c"], "a") assert d["shape"] == "Broadcast" and d["joined"] and d["extra_edges"] == 1 tree = build([("a", "b"), ("a", "c"), ("b", "d"), ("c", "e")], dict(a=0, b=1, c=2, d=3, e=4)) d = tree.descriptors(["a", "b", "c", "d", "e"], "a") assert d["shape"] == "Branching" return "chain, star and feed-forward triangle (the three 3-event motifs) and a tree get the expected shape, joins and ratios" def test_min_size_is_display_only(): rng = random.Random(4) events, links, _ = plant(rng, in_window_noise=0) g = Graph(events, links, CFG) sizes_all = [len(m) for _, m in g.cascades()] assert 1 in sizes_all and len(sizes_all) > len([1 for s in sizes_all if s >= 3]) assert sum(len(ep) for ep in g.episodes) == len(events) return f"{sum(1 for s in sizes_all if s == 1)} single-event cascades are kept in the output; size filtering is left to the caller" def test_giant_warning_and_sweep(): rng = random.Random(5) events = [Event(f"x{i}", rng.uniform(0, 1000)) for i in range(400)] links = [Link(f"x{rng.randrange(400)}", f"x{rng.randrange(400)}", "A") for _ in range(1200)] links = [l for l in links if l.src != l.dst] cfg = Config(windows={"A": (0, 5)}, giant_fraction=0.2) sweep = window_sweep(events, links, cfg, scales=(0.25, 0.5, 1, 2, 4, 8, 16, 32, 64)) frac = [round(s["largest_fraction"], 2) for s in sweep] assert frac[-1] > frac[0] and sweep[-1]["giant_warning"] and not sweep[0]["giant_warning"] s = suggest_scale(sweep) assert s is not None return f"largest-episode fraction grows {frac} over the window scales; giant warning off at scale 0.25 and on at 64; suggested scale {s}" def test_null_models(): rng = random.Random(6) events, links, planted = plant(rng, n_cascades=40, noise_events=400, in_window_noise=0, entity_mode="mixed") cfg = CFG obs = Graph(events, links, cfg).diagnostics() rows = [] for scheme, kw in [("global", {}), ("block", dict(block=500.0)), ("entity_shift", {})]: nd = null_diagnostics(events, links, cfg, scheme=scheme, reps=100, seed=1, **kw) p = tail_p(nd["episodes_ge3"], obs["episodes_ge3"]) rows.append((scheme, round(sum(nd["episodes_ge3"]) / len(nd["episodes_ge3"]), 1), round(p, 3))) assert nd["reps"] > 0 # pure noise: same pipeline on events with no planted structure must not look surprising noise_ev = [Event(f"z{i}", rng.uniform(0, 5000), entities=((f"ent{rng.randrange(30)}", "at"),)) for i in range(400)] noise_ln = [Link(f"z{rng.randrange(400)}", f"z{rng.randrange(400)}", "A") for _ in range(400)] noise_ln = [l for l in noise_ln if l.src != l.dst] o2 = Graph(noise_ev, noise_ln, cfg).diagnostics() nd2 = null_diagnostics(noise_ev, noise_ln, cfg, scheme="global", reps=100, seed=2) p2 = tail_p(nd2["episodes_ge3"], o2["episodes_ge3"]) assert all(p <= 0.05 for _, _, p in rows), rows assert p2 > 0.05, p2 return f"cross-entity planted data (observed episodes of 3+: {obs['episodes_ge3']}); null mean and tail p {rows}; pure noise tail p {p2:.2f}. p is bounded below by 1/(R+1)" def test_entity_shift_semantics(): """Per-entity circular shift keeps each entity's own timeline. It rejects only cross-entity alignment.""" rng = random.Random(8) ev_in, ln_in, _ = plant(rng, n_cascades=40, noise_events=400, entity_mode="station") # cascades inside one entity obs_in = Graph(ev_in, ln_in, CFG).diagnostics() nd_in = null_diagnostics(ev_in, ln_in, CFG, scheme="entity_shift", reps=100, seed=3) p_in = tail_p(nd_in["episodes_ge3"], obs_in["episodes_ge3"]) assert p_in > 0.05, p_in return f"cascades that live inside one entity's rhythm are not rejected by the entity-shift null (tail p {p_in:.2f}): the strict null measures cross-entity alignment only" def test_reproducibility(): rng = random.Random(7) events, links, _ = plant(rng) h1, h2 = run_hash(events, links, CFG), run_hash(events, links, CFG) g1, g2 = Graph(events, links, CFG), Graph(events, links, CFG) assert h1 == h2 and [k["src"] for k in g1.kept] == [k["src"] for k in g2.kept] root, members = next(iter(g1.cascades(min_size=3))) rec = g1.candidate_record(root, members) assert rec["parameters"]["windows"]["A"] == [0.0, 10.0] and rec["links"] and "gap" in rec["links"][0] return f"run hash {h1}; candidate record carries members, typed links with gaps and the parameters used" def test_provenance_filter(): ev = [Event("a", 0), Event("b", 1), Event("c", 2)] ln = [Link("a", "b", "A", provenance="given"), Link("b", "c", "A", provenance="inferred")] full = Graph(ev, ln, CFG) given = Graph(ev, ln, Config(windows=CFG.windows, allowed_provenance=("given",))) assert len(full.episodes[0]) == 3 and len(given.episodes[0]) == 2 return "cascades can be recomputed from data-given links only (3 events with all links, 2 with given links)" if __name__ == "__main__": tests = [test_invariants, test_recovery_exact, test_recovery_with_noise, test_window_per_type, test_ties, test_cycle_detection, test_descriptors, test_min_size_is_display_only, test_giant_warning_and_sweep, test_null_models, test_entity_shift_semantics, test_reproducibility, test_provenance_filter] failed = 0 for t in tests: try: msg = t() print(f"PASS {t.__name__}: {msg}") except Exception as e: failed += 1 print(f"FAIL {t.__name__}: {type(e).__name__}: {e}") print(f"{len(tests) - failed} of {len(tests)} tests passed") sys.exit(1 if failed else 0)