|
| 1 | +import json |
| 2 | +import pickle |
| 3 | +import secrets |
| 4 | +from datetime import datetime, timezone |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +from cloudfiles import CloudFile |
| 9 | + |
| 10 | +from pychunkedgraph.graph import basetypes |
| 11 | + |
| 12 | +from .current import run_current_stitch |
| 13 | +from .proposed import run_proposed_stitch |
| 14 | +from .tables import restore_test_table, setup_env, PREFIX, EDGES_SRC, _get_instance |
| 15 | +from .utils import _compare_components, _compare_cross_edges, _convert_for_json |
| 16 | + |
| 17 | +LOGS_ROOT = Path("/home/akhilesh/opt/zetta_utils/.env/pcg/.env/stitching/runs") |
| 18 | + |
| 19 | + |
| 20 | +def generate_run_id() -> str: |
| 21 | + return secrets.token_hex(4) |
| 22 | + |
| 23 | + |
| 24 | +# ───────────────────────────────────────────────────────────────────── |
| 25 | +# Top-level API |
| 26 | +# ───────────────────────────────────────────────────────────────────── |
| 27 | + |
| 28 | + |
| 29 | +def run_current_baseline(experiment: str = "single", edge_file: str = None): |
| 30 | + """ |
| 31 | + Run the current stitch path once for an experiment type. |
| 32 | + If the table + saved results already exist, skips and prints "reusing". |
| 33 | + """ |
| 34 | + setup_env() |
| 35 | + if edge_file is None: |
| 36 | + edge_file = f"{EDGES_SRC}/task_0_0.edges" |
| 37 | + |
| 38 | + table_name = f"{PREFIX}hsmith_mec_current_{experiment}" |
| 39 | + log_dir = LOGS_ROOT / experiment / "current" |
| 40 | + log_dir.mkdir(parents=True, exist_ok=True) |
| 41 | + structure_path = log_dir / "current_structure.json" |
| 42 | + |
| 43 | + instance = _get_instance() |
| 44 | + if instance.table(table_name).exists() and structure_path.exists(): |
| 45 | + print(f"reusing {table_name}") |
| 46 | + return |
| 47 | + |
| 48 | + print(f"restoring and running current path for '{experiment}'") |
| 49 | + restore_test_table(table_name) |
| 50 | + edges = pickle.loads(CloudFile(edge_file).get()) |
| 51 | + edges = np.asarray(edges, dtype=basetypes.NODE_ID) |
| 52 | + result = run_current_stitch(table_name, edges, do_sanity_check=False) |
| 53 | + _save_run_result(log_dir, "current", result) |
| 54 | + print(f"current {experiment} done: {result['elapsed']:.1f}s") |
| 55 | + |
| 56 | + |
| 57 | +def run_proposed_and_compare(experiment: str = "single", edge_file: str = None): |
| 58 | + """ |
| 59 | + Run the proposed stitch path and compare against the current baseline. |
| 60 | + Returns (match, result_current, result_proposed). |
| 61 | + """ |
| 62 | + setup_env() |
| 63 | + if edge_file is None: |
| 64 | + edge_file = f"{EDGES_SRC}/task_0_0.edges" |
| 65 | + |
| 66 | + run_id = generate_run_id() |
| 67 | + log_dir = LOGS_ROOT / experiment / run_id |
| 68 | + log_dir.mkdir(parents=True, exist_ok=True) |
| 69 | + table_proposed = f"{PREFIX}hsmith_mec_{run_id}_proposed" |
| 70 | + |
| 71 | + print(f"run_id: {run_id}") |
| 72 | + print(f"logs: {log_dir}") |
| 73 | + |
| 74 | + current_log_dir = LOGS_ROOT / experiment / "current" |
| 75 | + result_current = _load_result(current_log_dir, "current") |
| 76 | + |
| 77 | + restore_test_table(table_proposed) |
| 78 | + edges = pickle.loads(CloudFile(edge_file).get()) |
| 79 | + edges = np.asarray(edges, dtype=basetypes.NODE_ID) |
| 80 | + result_proposed = run_proposed_stitch(table_proposed, edges) |
| 81 | + _save_run_result(log_dir, "proposed", result_proposed) |
| 82 | + |
| 83 | + print(f"\ncurrent: {result_current['elapsed']:.1f}s, proposed: {result_proposed['elapsed']:.1f}s") |
| 84 | + match = compare_stitch_results(result_current, result_proposed) |
| 85 | + |
| 86 | + summary = { |
| 87 | + "run_id": run_id, |
| 88 | + "experiment": experiment, |
| 89 | + "timestamp": datetime.now(timezone.utc).isoformat(), |
| 90 | + "edge_file": edge_file, |
| 91 | + "match": match, |
| 92 | + "time_current": result_current["elapsed"], |
| 93 | + "time_proposed": result_proposed["elapsed"], |
| 94 | + "proposed_perf": result_proposed.get("perf", {}), |
| 95 | + } |
| 96 | + with open(log_dir / "summary.json", "w") as f: |
| 97 | + json.dump(_convert_for_json(summary), f, indent=2) |
| 98 | + |
| 99 | + print(f"\n{'MATCH' if match else 'MISMATCH'}") |
| 100 | + return match, result_current, result_proposed |
| 101 | + |
| 102 | + |
| 103 | +# ───────────────────────────────────────────────────────────────────── |
| 104 | +# Comparison |
| 105 | +# ───────────────────────────────────────────────────────────────────── |
| 106 | + |
| 107 | + |
| 108 | +def compare_stitch_results(result_a: dict, result_b: dict) -> bool: |
| 109 | + ids_match = _compare_new_ids_per_layer(result_a, result_b) |
| 110 | + comp_match = _compare_components(result_a["structure"], result_b["structure"]) |
| 111 | + cx_match = _compare_cross_edges(result_a["structure"], result_b["structure"]) |
| 112 | + return ids_match and comp_match and cx_match |
| 113 | + |
| 114 | + |
| 115 | +def _compare_new_ids_per_layer(result_a, result_b): |
| 116 | + lc_a = {int(k): v for k, v in result_a.get("layer_counts", {}).items()} |
| 117 | + lc_b = {int(k): v for k, v in result_b.get("layer_counts", {}).items()} |
| 118 | + all_layers = sorted(set(lc_a.keys()) | set(lc_b.keys())) |
| 119 | + match = True |
| 120 | + for layer in all_layers: |
| 121 | + if lc_a.get(layer, 0) != lc_b.get(layer, 0): |
| 122 | + print(f" NEW IDS MISMATCH layer {layer}: {lc_a.get(layer,0)} vs {lc_b.get(layer,0)}") |
| 123 | + match = False |
| 124 | + if match: |
| 125 | + print(f" NEW IDS MATCH: {sum(lc_a.values())} across {len(all_layers)} layers") |
| 126 | + return match |
| 127 | + |
| 128 | + |
| 129 | +# ───────────────────────────────────────────────────────────────────── |
| 130 | +# Persistence helpers |
| 131 | +# ───────────────────────────────────────────────────────────────────── |
| 132 | + |
| 133 | + |
| 134 | +def _save_structure(log_dir, name, structure): |
| 135 | + serializable = {} |
| 136 | + comps = structure.get("components", {}) |
| 137 | + serializable["components"] = { |
| 138 | + str(layer): [sorted(c) for c in ccs] for layer, ccs in comps.items() |
| 139 | + } |
| 140 | + cx = structure.get("cross_edges", {}) |
| 141 | + serializable["cross_edges"] = { |
| 142 | + str(layer): [[sorted(src), sorted(dst)] for src, dst in pairs] |
| 143 | + for layer, pairs in cx.items() |
| 144 | + } |
| 145 | + with open(log_dir / f"{name}_structure.json", "w") as f: |
| 146 | + json.dump(_convert_for_json(serializable), f, indent=2) |
| 147 | + |
| 148 | + |
| 149 | +def _save_run_result(log_dir, name, result): |
| 150 | + _save_structure(log_dir, name, result["structure"]) |
| 151 | + meta = {k: v for k, v in result.items() if k != "structure"} |
| 152 | + with open(log_dir / f"{name}_meta.json", "w") as f: |
| 153 | + json.dump(_convert_for_json(meta), f, indent=2) |
| 154 | + |
| 155 | + |
| 156 | +def _load_structure(path): |
| 157 | + with open(path) as f: |
| 158 | + data = json.load(f) |
| 159 | + return { |
| 160 | + "components": { |
| 161 | + int(layer): [frozenset(c) for c in ccs] |
| 162 | + for layer, ccs in data.get("components", {}).items() |
| 163 | + }, |
| 164 | + "cross_edges": { |
| 165 | + int(layer): [(frozenset(src), frozenset(dst)) for src, dst in pairs] |
| 166 | + for layer, pairs in data.get("cross_edges", {}).items() |
| 167 | + }, |
| 168 | + } |
| 169 | + |
| 170 | + |
| 171 | +def _load_result(log_dir, name): |
| 172 | + with open(log_dir / f"{name}_meta.json") as f: |
| 173 | + result = json.load(f) |
| 174 | + result["structure"] = _load_structure(log_dir / f"{name}_structure.json") |
| 175 | + return result |
0 commit comments