HarriziSaad commited on
Commit
d1bf756
·
verified ·
1 Parent(s): 8b239ea

Delete src/analysis/wow_pack.py

Browse files
Files changed (1) hide show
  1. src/analysis/wow_pack.py +0 -605
src/analysis/wow_pack.py DELETED
@@ -1,605 +0,0 @@
1
- # Wow Pack — Sections 3–5 (CT-map, SIMS, Discovery Frontier, Uplifts)
2
-
3
- # %%
4
- import json, os, re, math, warnings, pathlib as p
5
- from collections import defaultdict
6
-
7
- import numpy as np
8
- import pandas as pd
9
- import matplotlib.pyplot as plt
10
- import seaborn as sns
11
-
12
- RES = p.Path("results"); RES.mkdir(exist_ok=True, parents=True)
13
-
14
- def _read_json(path):
15
- path = p.Path(path)
16
- if not path.exists():
17
- warnings.warn(f"Missing file: {path}")
18
- return {}
19
- with open(path, "r") as f:
20
- return json.load(f)
21
-
22
- def _to_df_like(obj):
23
- """Try to coerce nested dicts into a tidy DataFrame [transporter, stress, value]."""
24
- if not obj:
25
- return pd.DataFrame(columns=["transporter","stress","value"])
26
- # case A: {stress: {transporter: val}}
27
- if isinstance(obj, dict):
28
- # detect orientation by peeking at first value
29
- first_key = next(iter(obj))
30
- first_val = obj[first_key]
31
- if isinstance(first_val, dict): # nested dict
32
- # decide which level is stress vs transporter by heuristic
33
- k_outer = str(first_key).lower()
34
- if any(s in k_outer for s in ["ethanol","oxid","osmotic","nacl","h2o2","stress"]):
35
- rows=[]
36
- for stress, inner in obj.items():
37
- for tr,val in inner.items():
38
- rows.append((str(tr), str(stress), float(val)))
39
- return pd.DataFrame(rows, columns=["transporter","stress","value"])
40
- else: # likely transporter->stress
41
- rows=[]
42
- for tr, inner in obj.items():
43
- for stress,val in inner.items():
44
- rows.append((str(tr), str(stress), float(val)))
45
- return pd.DataFrame(rows, columns=["transporter","stress","value"])
46
- # case B: flat dict of {transporter: val}
47
- else:
48
- rows=[(str(k), "pooled", float(v)) for k,v in obj.items()]
49
- return pd.DataFrame(rows, columns=["transporter","stress","value"])
50
- # fallback
51
- return pd.DataFrame(obj)
52
-
53
- def _errbar(ax, x0, x1, y, color="k", lw=1):
54
- ax.plot([x0,x1],[y,y], color=color, lw=lw)
55
-
56
- def _save(fig, path, dpi=300, tight=True):
57
- path = RES / path
58
- if tight: plt.tight_layout()
59
- fig.savefig(path, dpi=dpi)
60
- print("✅ saved:", path)
61
-
62
- # Load artifacts (be flexible with names)
63
- snap3 = _read_json(RES/"causal_section3_snapshot.json")
64
- rob3 = _read_json(RES/"causal_section3_robustness.json")
65
- al4 = _read_json(RES/"al_section4_snapshot.json")
66
- al4b = _read_json(RES/"al_section4_snapshot (1).json") # optional new run name
67
- transfer= _read_json(RES/"section5_transfer_snapshot.json")
68
-
69
- # Try multiple handles for AL snapshot
70
- if not al4 and al4b: al4 = al4b
71
-
72
- # Peek what we have
73
- for name, obj in dict(s3=snap3, rob=rob3, al=al4, trans=transfer).items():
74
- print(name, "keys:", ([] if not obj else list(obj.keys()))[:8])
75
-
76
- # --- Patch the leaf parser to accept list/tuple/dict leaves ---
77
- import math, numpy as np, pandas as pd
78
-
79
- def _leaf_to_float(v):
80
- """Extract a numeric point estimate from various leaf formats."""
81
- # direct number
82
- if isinstance(v, (int, float, np.integer, np.floating)):
83
- return float(v)
84
-
85
- # list/tuple: try first numeric entry (e.g., [ATE, lo, hi])
86
- if isinstance(v, (list, tuple)):
87
- for x in v:
88
- if isinstance(x, (int, float, np.integer, np.floating)):
89
- return float(x)
90
- return np.nan
91
-
92
- # dict: look for common keys, else first numeric value
93
- if isinstance(v, dict):
94
- for k in ["ATE", "ate", "value", "mean", "point", "point_est", "point_estimate"]:
95
- if k in v and isinstance(v[k], (int, float, np.integer, np.floating)):
96
- return float(v[k])
97
- for x in v.values():
98
- if isinstance(x, (int, float, np.integer, np.floating)):
99
- return float(x)
100
- if isinstance(x, (list, tuple)) and len(x) > 0 and isinstance(x[0], (int, float, np.integer, np.floating)):
101
- return float(x[0])
102
- return np.nan
103
-
104
- # anything else
105
- return np.nan
106
-
107
- def _to_df_like(obj):
108
- """Coerce nested dicts into tidy DF [transporter, stress, value] using _leaf_to_float."""
109
- if not obj:
110
- return pd.DataFrame(columns=["transporter","stress","value"])
111
-
112
- # nested dictionaries
113
- if isinstance(obj, dict):
114
- first_key = next(iter(obj))
115
- first_val = obj[first_key]
116
-
117
- # case: {outer: {inner: leaf}}
118
- if isinstance(first_val, dict):
119
- # guess orientation by outer key name
120
- k_outer = str(first_key).lower()
121
- rows=[]
122
- if any(s in k_outer for s in ["ethanol","oxid","osmotic","nacl","kcl","stress","h2o2"]):
123
- # outer = stress
124
- for stress, inner in obj.items():
125
- for tr, leaf in inner.items():
126
- val = _leaf_to_float(leaf)
127
- if not (val is None or math.isnan(val)):
128
- rows.append((str(tr), str(stress), float(val)))
129
- else:
130
- # outer = transporter
131
- for tr, inner in obj.items():
132
- for stress, leaf in inner.items():
133
- val = _leaf_to_float(leaf)
134
- if not (val is None or math.isnan(val)):
135
- rows.append((str(tr), str(stress), float(val)))
136
- return pd.DataFrame(rows, columns=["transporter","stress","value"])
137
-
138
- # case: flat {transporter: leaf}
139
- else:
140
- rows=[]
141
- for tr, leaf in obj.items():
142
- val = _leaf_to_float(leaf)
143
- if not (val is None or math.isnan(val)):
144
- rows.append((str(tr), "pooled", float(val)))
145
- return pd.DataFrame(rows, columns=["transporter","stress","value"])
146
-
147
- # fallback
148
- return pd.DataFrame(obj)
149
-
150
- print("✅ Robust parser installed. Re-run the CT-map/SIMS cells.")
151
-
152
- # %%
153
- # Try common locations for stress-specific ATEs in Section 3 snapshot
154
- # Heuristics to find a nested dict of [stress][transporter] -> effect OR [transporter][stress]
155
- candidates = []
156
- for k,v in (snap3 or {}).items():
157
- if isinstance(v, dict):
158
- # look for 2-level dict with numeric leaves
159
- try:
160
- inner = next(iter(v.values()))
161
- if isinstance(inner, dict):
162
- numeric_leaf = next(iter(inner.values()))
163
- float(numeric_leaf)
164
- candidates.append((k, v))
165
- except Exception:
166
- pass
167
-
168
- if not candidates:
169
- warnings.warn("Could not auto-locate stress-wise effects in Section 3 snapshot.")
170
- stress_df = pd.DataFrame(columns=["transporter","stress","value"])
171
- else:
172
- key, nested = candidates[0]
173
- print(f"Using stress-effect block: '{key}'")
174
- stress_df = _to_df_like(nested)
175
-
176
- # Normalize stress names a bit
177
- def _norm_s(s):
178
- s=str(s).lower()
179
- if "eth" in s: return "ethanol"
180
- if "h2o2" in s or "oxi" in s: return "oxidative"
181
- if "osm" in s or "nacl" in s or "kcl" in s or "salt" in s: return "osmotic"
182
- return s
183
- stress_df["stress"] = stress_df["stress"].map(_norm_s)
184
- stress_df = stress_df[~stress_df["stress"].isin(["pooled",""])]
185
-
186
- # Pivot to matrix (transporters × stresses)
187
- ct_mat = stress_df.pivot_table(index="transporter", columns="stress", values="value", aggfunc="mean").fillna(0.0)
188
- ct_mat = ct_mat.reindex(sorted(ct_mat.index), axis=0)
189
- ct_mat = ct_mat.reindex(sorted(ct_mat.columns), axis=1)
190
-
191
- # ---- CT-Map Heatmap ----
192
- plt.figure(figsize=(max(6,0.16*ct_mat.shape[0]), 2.4))
193
- sns.heatmap(ct_mat.T, cmap="coolwarm", center=0, cbar_kws={"label":"ATE (high→low expr)"}, linewidths=0.2, linecolor="w")
194
- plt.title("CT-Map — Causal transportability across stresses")
195
- plt.xlabel("Transporter"); plt.ylabel("Stress")
196
- _save(plt.gcf(), "fig_ct_map.png")
197
-
198
- # ---- Top drivers (mean absolute effect across stresses) ----
199
- top = ct_mat.abs().mean(axis=1).sort_values(ascending=False).rename("mean_abs_ATE")
200
- top_tbl = top.reset_index().rename(columns={"index":"transporter"})
201
- top_tbl.to_csv(RES/"ct_map_top_drivers.csv", index=False)
202
- print(top_tbl.head(10))
203
-
204
- # %%
205
- # SIMS = |mean CATE across stresses| / (SD across stresses + eps)
206
- eps = 1e-8
207
- mu = ct_mat.mean(axis=1)
208
- sd = ct_mat.std(axis=1)
209
- sims = (mu.abs() / (sd + eps)).rename("SIMS")
210
-
211
- sims_tbl = (
212
- pd.DataFrame(dict(transporter=sims.index, SIMS=sims.values, mean_effect=mu.values, sd=sd.values))
213
- .sort_values("SIMS", ascending=False)
214
- )
215
- sims_tbl.to_csv(RES/"table_SIMS.csv", index=False)
216
-
217
- fig, ax = plt.subplots(figsize=(6, max(3.5, 0.35*len(sims_tbl))))
218
- sns.barplot(data=sims_tbl, y="transporter", x="SIMS", color="steelblue", ax=ax, orient="h")
219
- ax.set_title("SIMS — stress-invariant mechanism score")
220
- ax.set_xlabel("|mean CATE| / SD across stresses")
221
- _save(fig, "fig_SIMS_waterfall.png")
222
- sims_tbl.head(10)
223
-
224
- # %%
225
- def _extract_al_curves(blob):
226
- """
227
- Expect something like:
228
- {"strategy": {"frac": [...], "auprc": [...]}, ...}
229
- or a list of dicts with keys 'strategy','frac','auprc'
230
- """
231
- if not blob: return {}
232
- out = {}
233
- # form 1: dict of strategies
234
- for k,v in blob.items():
235
- if isinstance(v, dict) and {"frac","auprc"} <= set(v.keys()):
236
- out[k] = pd.DataFrame(dict(frac=v["frac"], auprc=v["auprc"]))
237
- # form 2: list of records
238
- if not out and isinstance(blob, list):
239
- for rec in blob:
240
- if isinstance(rec, dict) and {"strategy","frac","auprc"} <= set(rec.keys()):
241
- out.setdefault(rec["strategy"], pd.DataFrame(columns=["frac","auprc"]))
242
- out[rec["strategy"]] = pd.DataFrame(dict(frac=rec["frac"], auprc=rec["auprc"]))
243
- return out
244
-
245
- al_curves = _extract_al_curves(al4)
246
-
247
- if not al_curves:
248
- warnings.warn("Could not parse AL curves from Section 4 snapshot.")
249
- else:
250
- # plot frontier
251
- fig, ax = plt.subplots(figsize=(8,5))
252
- palette = dict(random="#8c8c8c")
253
- for k,df in al_curves.items():
254
- df = df.sort_values("frac")
255
- ax.plot(df["frac"], df["auprc"], label=k)
256
- ax.set_title("Interventional Discovery Frontier (AUPRC vs label fraction)")
257
- ax.set_xlabel("Labeled fraction of pool"); ax.set_ylabel("AUPRC (held-out)")
258
- ax.legend()
259
- _save(fig, "fig_discovery_frontier.png")
260
-
261
- # compute integrated gain vs random
262
- def _auc(df):
263
- df=df.sort_values("frac")
264
- return np.trapz(df["auprc"].to_numpy(), df["frac"].to_numpy())
265
- if "random" not in al_curves:
266
- warnings.warn("No 'random' baseline present; gains will be relative to min curve.")
267
- base_key = sorted(al_curves.keys())[0]
268
- else:
269
- base_key = "random"
270
- base_auc = _auc(al_curves[base_key])
271
-
272
- gains=[]
273
- for k,df in al_curves.items():
274
- g = _auc(df)/max(base_auc,1e-12)
275
- gains.append((k,g))
276
- gains_tbl = pd.DataFrame(gains, columns=["strategy","gain_vs_random"]).sort_values("gain_vs_random", ascending=False)
277
- gains_tbl.to_csv(RES/"table_discovery_gains.csv", index=False)
278
-
279
- fig, ax = plt.subplots(figsize=(6,3.2))
280
- sns.barplot(data=gains_tbl[gains_tbl["strategy"]!=base_key], x="strategy", y="gain_vs_random", ax=ax)
281
- ax.axhline(1.0, color="k", ls="--", lw=1)
282
- ax.set_ylabel("Efficiency gain vs random (AUC ratio)")
283
- ax.set_title("Label-efficiency gains")
284
- _save(fig, "fig_discovery_gain_bars.png")
285
-
286
- display(gains_tbl)
287
-
288
-
289
- # %%
290
- # Choose top K stable (high SIMS) transporters
291
- K = min(5, max(1, len(sims_tbl)))
292
- top_sims = sims_tbl.head(K)["transporter"].tolist()
293
-
294
- for tr in top_sims:
295
- ser = ct_mat.loc[tr].dropna()
296
- fig, ax = plt.subplots(figsize=(4.5,3.2))
297
- sns.barplot(x=ser.index, y=ser.values, ax=ax, color="steelblue")
298
- ax.axhline(0, color="k", lw=1)
299
- ax.set_title(f"Counterfactual uplift — {tr}\n(high vs low expression by stress)")
300
- ax.set_ylabel("ATE"); ax.set_xlabel("")
301
- _save(fig, f"fig_uplift_{re.sub(r'[^A-Za-z0-9]+','_',tr)}.png")
302
-
303
-
304
- # %%
305
- manifest = {
306
- "ct_map": {
307
- "figure": str(RES/"fig_ct_map.png"),
308
- "top_drivers_csv": str(RES/"ct_map_top_drivers.csv"),
309
- },
310
- "SIMS": {
311
- "waterfall": str(RES/"fig_SIMS_waterfall.png"),
312
- "table": str(RES/"table_SIMS.csv"),
313
- "definition": "|mean CATE across stresses| / (SD across stresses + 1e-8)"
314
- },
315
- "discovery_frontier": {
316
- "frontier_fig": str(RES/"fig_discovery_frontier.png"),
317
- "gain_bars_fig": str(RES/"fig_discovery_gain_bars.png"),
318
- "gains_table": str(RES/"table_discovery_gains.csv")
319
- },
320
- "uplifts": sorted([str(x) for x in RES.glob("fig_uplift_*.png")]),
321
- "notes": "Figures computed from Section 3 stress-specific ATEs and Section 4 AL curves; transfer analysis not required here."
322
- }
323
- with open(RES/"wow_pack_manifest.json","w") as f:
324
- json.dump(manifest, f, indent=2)
325
- print("✅ wrote:", RES/"wow_pack_manifest.json")
326
- for k,v in manifest.items():
327
- print(k, "→", (list(v)[:3] if isinstance(v, dict) else f"{len(v)} files"))
328
-
329
-
330
- # %% Patch: robust AL curves parser + gain stats + zip refresh
331
- import json, numpy as np, pandas as pd, pathlib as p, zipfile
332
-
333
- RES = p.Path("results"); RES.mkdir(parents=True, exist_ok=True)
334
- ALP = RES/"al_section4_snapshot.json"
335
-
336
- def _safe_json(path):
337
- try: return json.load(open(path))
338
- except Exception: return {}
339
-
340
- AL = _safe_json(ALP)
341
-
342
- def normalize_curves(AL):
343
- """
344
- Returns dict: {strategy: {"fracs":[...], "auprc":[...]}}
345
- Accepts shapes like:
346
- - {"curves":{"uncertainty":{"fracs":[...],"auprc":[...]}, ...}}
347
- - {"curves":[{"strategy":"uncertainty","fracs":[...],"auprc":[...]}, ...]}
348
- - {"curves":{"uncertainty":[{"frac":0.2,"auprc":...}, ...]}, ...}
349
- - {"curves":[{"strategy":"uncertainty","frac":0.2,"auprc":...}, ...]} (point-wise list)
350
- """
351
- curves = AL.get("curves", {})
352
- out = {}
353
-
354
- # Case A: dict of strategies
355
- if isinstance(curves, dict):
356
- for strat, obj in curves.items():
357
- # A1: direct arrays
358
- if isinstance(obj, dict) and ("fracs" in obj) and ("auprc" in obj):
359
- out[strat] = {"fracs": list(map(float, obj["fracs"])),
360
- "auprc": list(map(float, obj["auprc"]))}
361
- # A2: list of points
362
- elif isinstance(obj, list):
363
- fr, au = [], []
364
- for pt in obj:
365
- if isinstance(pt, dict):
366
- f = pt.get("frac", pt.get("fracs"))
367
- a = pt.get("auprc", pt.get("AUPRC", pt.get("aupr")))
368
- if f is not None and a is not None:
369
- fr.append(float(f)); au.append(float(a))
370
- if fr and au: out[strat] = {"fracs": fr, "auprc": au}
371
-
372
- # Case B: list at top level
373
- if not out and isinstance(curves, list):
374
- # B1: series-per-item
375
- tmp = {}
376
- for item in curves:
377
- if isinstance(item, dict) and ("strategy" in item):
378
- if "fracs" in item and "auprc" in item:
379
- tmp[item["strategy"]] = {"fracs": list(map(float, item["fracs"])),
380
- "auprc": list(map(float, item["auprc"]))}
381
- if tmp: out = tmp
382
- else:
383
- # B2: point-wise items
384
- from collections import defaultdict
385
- acc = defaultdict(lambda: {"fracs": [], "auprc": []})
386
- for pt in curves:
387
- if isinstance(pt, dict) and ("strategy" in pt):
388
- f = pt.get("frac", pt.get("fracs")); a = pt.get("auprc", pt.get("AUPRC"))
389
- if f is not None and a is not None:
390
- acc[pt["strategy"]]["fracs"].append(float(f))
391
- acc[pt["strategy"]]["auprc"].append(float(a))
392
- out = dict(acc)
393
-
394
- return out
395
-
396
- curves = normalize_curves(AL)
397
- if not curves:
398
- raise SystemExit("Could not parse AL curves; inspect results/al_section4_snapshot.json")
399
-
400
- if "random" not in curves:
401
- # Fall back: pick the first strategy as baseline (shouldn't happen in our runs)
402
- base_name = next(iter(curves))
403
- else:
404
- base_name = "random"
405
-
406
- FR = np.array(curves[base_name]["fracs"], float)
407
- base = np.array(curves[base_name]["auprc"], float)
408
-
409
- def series(name):
410
- fr = np.array(curves[name]["fracs"], float)
411
- au = np.array(curves[name]["auprc"], float)
412
- # align by truncation to the shared prefix length
413
- n = min(len(FR), len(fr), len(base))
414
- return au[:n], base[:n]
415
-
416
- def gain_ratio(name):
417
- au, b = series(name)
418
- return au / (b + 1e-12)
419
-
420
- # Bootstrap mean gain vs baseline across checkpoints
421
- B = 2000
422
- rng = np.random.default_rng(7)
423
- records = []
424
- for strat in [s for s in curves.keys() if s != base_name]:
425
- G = gain_ratio(strat)
426
- n = len(G)
427
- boots = [G[rng.integers(0, n, n)].mean() for _ in range(B)]
428
- boots = np.array(boots, float)
429
- mean = float(G.mean())
430
- lo, hi = np.percentile(boots, [2.5, 97.5])
431
- records.append({"strategy": strat, "mean_gain": mean, "ci_low": float(lo), "ci_high": float(hi)})
432
-
433
- gains_df = pd.DataFrame(records).sort_values("mean_gain", ascending=False)
434
- out_csv = RES/"gains_table.csv"
435
- gains_df.to_csv(out_csv, index=False)
436
-
437
- # Refresh the ZIP if it exists
438
- zip_path = RES/"wow_camera_ready.zip"
439
- if zip_path.exists():
440
- with zipfile.ZipFile(zip_path, "a", compression=zipfile.ZIP_DEFLATED) as z:
441
- z.write(out_csv, arcname="tables/gains_table.csv")
442
-
443
- print("✅ Rebuilt gains with bootstrap CIs.")
444
- print(gains_df)
445
- print("Saved:", out_csv, "| ZIP updated:", zip_path.exists())
446
-
447
- import json, os, zipfile, re
448
- import numpy as np, pandas as pd, matplotlib.pyplot as plt, seaborn as sns
449
- from pathlib import Path
450
-
451
- RES = Path("results"); RES.mkdir(exist_ok=True, parents=True)
452
- cand = sorted(RES.glob("al_section4_snapshot*.json"), key=os.path.getmtime)
453
- if not cand: raise FileNotFoundError("No results/al_section4_snapshot*.json found.")
454
- AL_PATH = cand[-1]
455
- al = json.load(open(AL_PATH))
456
- raw_curves = al.get("curves")
457
- if raw_curves is None: raise ValueError("al['curves'] missing.")
458
-
459
- # ---------- helpers ----------
460
- def _find_key(d, want):
461
- """find a key in dict d that matches 'frac' or 'auprc' loosely (case-insensitive substr)."""
462
- want = want.lower()
463
- for k in d.keys():
464
- lk = k.lower()
465
- if want == "frac":
466
- if ("frac" in lk) or ("label" in lk) or (lk in {"f","x"}):
467
- return k
468
- if want == "auprc":
469
- if ("auprc" in lk) or ("pr" in lk) or ("average_precision" in lk) or (lk in {"ap","y"}):
470
- return k
471
- return None
472
-
473
- def _to_pairs(obj):
474
- """Return Nx2 array of [frac, auprc] from many formats."""
475
- # list/tuple?
476
- if isinstance(obj, (list, tuple)) and len(obj)>0:
477
- # list of pairs
478
- if isinstance(obj[0], (list, tuple)) and len(obj[0])==2:
479
- return np.asarray(obj, dtype=float)
480
- # list of dict points (keys may vary)
481
- if isinstance(obj[0], dict):
482
- fr, ap = [], []
483
- for d in obj:
484
- if not isinstance(d, dict): raise TypeError("Mixed list; expected dict points.")
485
- kf = _find_key(d, "frac"); ka = _find_key(d, "auprc")
486
- if kf is None or ka is None:
487
- # if the dict has only two numeric values, take them in sorted key order
488
- nums = [v for v in d.values() if np.isscalar(v) or (isinstance(v,(list,tuple)) and len(v)==1)]
489
- if len(nums)>=2:
490
- fr.append(float(np.asarray(list(d.values())[0]).squeeze()))
491
- ap.append(float(np.asarray(list(d.values())[1]).squeeze()))
492
- continue
493
- raise ValueError("Point dict missing frac/auprc-like keys.")
494
- fr.append(float(np.asarray(d[kf]).squeeze()))
495
- ap.append(float(np.asarray(d[ka]).squeeze()))
496
- return np.column_stack([fr, ap])
497
- # dict-of-lists columns?
498
- if isinstance(obj, dict):
499
- kf = _find_key(obj, "frac"); ka = _find_key(obj, "auprc")
500
- if kf and ka and isinstance(obj[kf], (list, tuple)) and isinstance(obj[ka], (list, tuple)):
501
- fr = np.asarray(obj[kf], dtype=float).ravel()
502
- ap = np.asarray(obj[ka], dtype=float).ravel()
503
- return np.column_stack([fr, ap])
504
- # dict with nested 'points'
505
- if "points" in obj:
506
- return _to_pairs(obj["points"])
507
- raise TypeError("Unrecognized curve format.")
508
-
509
- def _normalize_one(v):
510
- """Return {'fracs':..., 'auprc':...} sorted by fracs."""
511
- # direct dict with fracs/auprc keys (any naming)
512
- if isinstance(v, dict):
513
- try:
514
- arr = _to_pairs(v)
515
- except Exception:
516
- # maybe explicit arrays under fracs/auprc aliases
517
- kf = _find_key(v, "frac"); ka = _find_key(v, "auprc")
518
- if kf and ka:
519
- arr = np.column_stack([np.asarray(v[kf], float).ravel(),
520
- np.asarray(v[ka], float).ravel()])
521
- else:
522
- raise
523
- else:
524
- arr = _to_pairs(v)
525
- arr = arr[np.argsort(arr[:,0])]
526
- return {"fracs": arr[:,0], "auprc": arr[:,1]}
527
-
528
- def normalize_curves(curves_raw):
529
- out = {}
530
- if isinstance(curves_raw, dict):
531
- for k,v in curves_raw.items():
532
- out[str(k)] = _normalize_one(v)
533
- return out
534
- if isinstance(curves_raw, list):
535
- for item in curves_raw:
536
- if isinstance(item, dict):
537
- name = item.get("strategy") or item.get("name") or item.get("label") or f"strategy_{len(out)}"
538
- payload = {kk: vv for kk,vv in item.items() if kk not in {"strategy","name","label"}}
539
- out[str(name)] = _normalize_one(payload if payload else item)
540
- if out: return out
541
- raise ValueError("Unrecognized al['curves'] structure.")
542
-
543
- # ---------- normalize & union grid ----------
544
- curves = normalize_curves(raw_curves)
545
- grid = sorted({float(x) for v in curves.values() for x in np.asarray(v["fracs"], float)})
546
- FR = np.asarray(grid, float)
547
-
548
- tidy = []
549
- for strat, v in curves.items():
550
- f = np.asarray(v["fracs"], float); a = np.asarray(v["auprc"], float)
551
- # dedup on f
552
- u, idx = np.unique(np.round(f,8), return_index=True)
553
- f2 = f[np.sort(idx)]; a2 = a[np.sort(idx)]
554
- a_interp = np.interp(FR, f2, a2)
555
- for fr, ap in zip(FR, a_interp):
556
- tidy.append({"strategy": strat, "frac_labeled": float(fr), "auprc": float(ap)})
557
- curves_df = pd.DataFrame(tidy)
558
- curves_df.to_csv(RES/"al_curves_merged.csv", index=False)
559
-
560
- # ---------- gains vs random (bootstrap CI) ----------
561
- if "random" not in curves_df["strategy"].unique():
562
- raise ValueError("Random baseline missing.")
563
-
564
- base = curves_df[curves_df.strategy=="random"].set_index("frac_labeled")["auprc"]
565
- def boot_ci(v, B=5000, seed=123):
566
- rng = np.random.default_rng(seed); v=np.asarray(v,float)
567
- boots = rng.choice(v, size=(B,len(v)), replace=True).mean(1)
568
- lo,hi = np.percentile(boots,[2.5,97.5]); return float(v.mean()), float(lo), float(hi)
569
-
570
- rows=[]
571
- for strat in sorted(set(curves_df.strategy)-{"random"}):
572
- a = curves_df[curves_df.strategy==strat].set_index("frac_labeled")["auprc"].reindex(base.index)
573
- mask = base>0
574
- gains = (a[mask]/base[mask]).dropna().values
575
- if gains.size==0: continue
576
- mean,lo,hi = boot_ci(gains)
577
- rows.append({"strategy":strat,"mean_gain":mean,"ci_low":lo,"ci_high":hi})
578
- gains_df = pd.DataFrame(rows).sort_values("mean_gain", ascending=False)
579
- gains_df.to_csv(RES/"gains_table.csv", index=False)
580
- print("✅ Parsed and merged curves. Gains:")
581
- print(gains_df)
582
-
583
- # ---------- figures ----------
584
- plt.figure(figsize=(7.4,4.8))
585
- sns.lineplot(data=curves_df, x="frac_labeled", y="auprc", hue="strategy", marker="o")
586
- plt.xlabel("Labeled fraction"); plt.ylabel("Validation AUPRC")
587
- plt.title("Active Learning Efficiency Frontier"); plt.grid(alpha=0.3); plt.tight_layout()
588
- frontier_png = RES/"fig_AL_frontier.png"; plt.savefig(frontier_png, dpi=300); plt.show()
589
-
590
- plt.figure(figsize=(6.8,4.6))
591
- order = gains_df["strategy"].tolist()
592
- ax = sns.barplot(data=gains_df, x="strategy", y="mean_gain", order=order)
593
- for i,r in enumerate(gains_df.itertuples(index=False)):
594
- ax.plot([i,i],[r.ci_low,r.ci_high], color="k", lw=1.2)
595
- plt.axhline(1.0, color="k", ls="--", lw=1, alpha=0.6)
596
- plt.ylabel("Gain vs. random (AUPRC ratio)")
597
- plt.title("Active Learning Gain (mean ± 95% CI)"); plt.tight_layout()
598
- gains_png = RES/"fig_AL_gains.png"; plt.savefig(gains_png, dpi=300); plt.show()
599
-
600
- # ---------- zip ----------
601
- zip_path = RES/"wow_camera_ready.zip"
602
- with zipfile.ZipFile(zip_path, "a" if zip_path.exists() else "w", zipfile.ZIP_DEFLATED) as zf:
603
- for f in [frontier_png, gains_png, RES/"al_curves_merged.csv", RES/"gains_table.csv", AL_PATH]:
604
- zf.write(f, arcname=f.name)
605
- print("📦 Updated:", zip_path.name)