junidude14 commited on
Commit
ca12448
·
verified ·
1 Parent(s): af0f5fe

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/figure5_details.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Draw all-state results and the explicitly unmatched Behcet A/B comparison."""
2
+ from pathlib import Path
3
+ import hashlib
4
+ import json
5
+ import numpy as np
6
+ import pandas as pd
7
+ import matplotlib
8
+ matplotlib.use('Agg')
9
+ import matplotlib.pyplot as plt
10
+
11
+
12
+ def sha(p):
13
+ return hashlib.file_digest(Path(p).open('rb'),'sha256').hexdigest()
14
+
15
+
16
+ def all_state_metrics(donor, summary):
17
+ records=[]
18
+ for (cohort,unit,arm,state),d in donor.groupby(['cohort','unit','arm','state'],sort=True):
19
+ if d.donor_id.duplicated().any():
20
+ raise ValueError('repeated visits must be collapsed before rare-state detection')
21
+ present=d.obs_state.gt(0); absent=d.obs_state.eq(0)
22
+ records.append({'cohort':cohort,'unit':unit,'arm':arm,'state':state,
23
+ 'missed_observed_fraction':float(d.loc[present,'gen_state'].eq(0).mean()) if present.any() else np.nan,
24
+ 'generated_in_observed_zero_fraction':float(d.loc[absent,'gen_state'].gt(0).mean()) if absent.any() else np.nan,
25
+ 'n_observed_positive_donors':int(present.sum()),'n_evaluable_donors':len(d)})
26
+ extra=pd.DataFrame(records)
27
+ keys=['cohort','unit','arm','state']
28
+ return summary.merge(extra,on=keys,validate='one_to_one')
29
+
30
+
31
+ def render_all_states(out, donor, summary, tier, arms):
32
+ data=all_state_metrics(donor,summary)
33
+ data.to_csv(out/'source_data/rare_all_states.csv',index=False)
34
+ agg=data.groupby(['cohort','state','arm'],as_index=False).agg(
35
+ abundance_error=('mae_donor_pp','mean'), abundance_error_draw_sd=('mae_donor_pp','std'),
36
+ ranking=('spearman_donor','mean'),ranking_draw_sd=('spearman_donor','std'),
37
+ missed_observed_fraction=('missed_observed_fraction','mean'),
38
+ generated_in_observed_zero_fraction=('generated_in_observed_zero_fraction','mean'))
39
+ agg.to_csv(out/'source_data/rare_all_states_aggregate.csv',index=False)
40
+ keys=list(dict.fromkeys(zip(agg.cohort,agg.state)))
41
+ fig,axes=plt.subplots(1,4,figsize=(12,max(6,len(keys)*.18)),layout='constrained')
42
+ for ax,col,label,vmax in zip(axes,['abundance_error','ranking','missed_observed_fraction','generated_in_observed_zero_fraction'],
43
+ ['Abundance error (pp)','Abundance Spearman r','Missed observed-positive donors','Generated in observed-zero donors'],[None,1,1,1]):
44
+ matrix=np.full((len(keys),len(arms)),np.nan)
45
+ for i,(cohort,state) in enumerate(keys):
46
+ for j,arm in enumerate(arms):
47
+ row=agg[(agg.cohort==cohort)&(agg.state==state)&(agg.arm==arm)]
48
+ if len(row):matrix[i,j]=row.iloc[0][col]
49
+ image=ax.imshow(np.ma.masked_invalid(matrix),aspect='auto',cmap='coolwarm' if col=='ranking' else 'viridis',
50
+ vmin=-1 if col=='ranking' else 0,vmax=vmax)
51
+ ax.set_xticks(range(len(arms)),arms,rotation=65,ha='right',fontsize=7)
52
+ ax.set_yticks(range(len(keys)),[f'{c}: {s}' for c,s in keys] if ax is axes[0] else [])
53
+ ax.tick_params(axis='y',labelsize=5.2);ax.set_title(label,fontsize=9)
54
+ fig.colorbar(image,ax=ax,shrink=.5)
55
+ fig.suptitle('All predefined states · every draw retained · '+tier)
56
+ for ext in ['pdf','svg','png']:fig.savefig(out/'figures'/f'fig5_all_states_{tier}.{ext}',dpi=220)
57
+ plt.close(fig)
58
+ return data
59
+
60
+
61
+ def behcet_source(behcet,out):
62
+ (out/'reports').mkdir(parents=True,exist_ok=True)
63
+ source=behcet/'out/rules_groups/per_sample_group_metrics.csv'
64
+ pairs=behcet.parent/'behcet_pair_recovery_20261004/out/pairs_recovered.csv'
65
+ group=behcet/'out/group_table.csv'
66
+ train=set(pd.read_csv(pairs).bulk_sample.astype(str))
67
+ if len(train)!=3:raise ValueError('Behcet candidate training set changed')
68
+ data=pd.read_csv(source)
69
+ names=['obs','obs_thin_lora3','zs_raw_s13','zs_cal_s13','lora3_raw_s13','lora3_raw_s04']
70
+ data=data[data.arm.isin(names)&(data.arm.str.startswith('obs')|~data.sample_id.isin(train))].copy()
71
+ reference=pd.read_csv(group)
72
+ for arm,sub in data.groupby('arm'):
73
+ expected=reference[(reference.arm==arm)&reference.rows.isin(['test','observed'])&(reference.metric=='c1q_high_rule_A')].iloc[0]
74
+ if (int(sub.group.eq('BD').sum()),int(sub.group.eq('HC').sum()))!=(int(expected.n_bd),int(expected.n_hc)):
75
+ raise ValueError('Behcet individual data do not reproduce frozen held-out groups')
76
+ data['evidence_tier']='descriptive_unmatched'
77
+ data['real_reference_includes_training_donors']=True
78
+ data.to_csv(out/'source_data/rare_behcet_per_sample.csv',index=False)
79
+ (out/'reports/rare_behcet_provenance.json').write_text(json.dumps({
80
+ 'schema':'pbisc.fig5.behcet-descriptive.v1','sources':{str(p):sha(p) for p in [source,pairs,group]},
81
+ 'training_bulk_samples':sorted(train),'pair_identity':'2 primary passes; 1 uncertain',
82
+ 'calibration':'zs_cal is gene-wise calibration fitted on the same three candidate pairs; it is not external AIFI ref-cal',
83
+ 'real_reference':'4 BD and 4 HC; includes training sc donors, mostly unmatched to held-out bulks',
84
+ 'rules':{'A':'at least one C1Q gene detected','B':'at least two C1Q genes co-detected in the same cell'},
85
+ 'independent_paired_validation':False},indent=2)+'\n')
86
+ return data,names
87
+
88
+
89
+ def render_behcet(behcet,out,tier):
90
+ data,names=behcet_source(behcet,out)
91
+ labels=['Observed native','Observed thinned to LoRA','Raw','Same-3-pair calibration','LoRA-3 seed 1','LoRA-3 seed 2']
92
+ fig,axes=plt.subplots(1,2,figsize=(10,4.5),layout='constrained')
93
+ for ax,rule,title in zip(axes,['A','B'],['A Any C1Q gene','B At least two C1Q genes in one cell']):
94
+ for j,arm in enumerate(names):
95
+ for k,group in enumerate(['HC','BD']):
96
+ values=100*data[(data.arm==arm)&(data.group==group)][f'c1q_high_fraction_{rule}'].to_numpy()
97
+ y=np.full(len(values),j+(k-.5)*.22)+np.linspace(-.05,.05,len(values))
98
+ ax.scatter(values,y,s=13,c='#c15f46' if group=='BD' else '#437c96',alpha=.65,label=group if j==0 else None)
99
+ ax.plot(np.mean(values),j+(k-.5)*.22,'|',color='black',markersize=10)
100
+ ax.set_yticks(range(len(names)),labels);ax.invert_yaxis();ax.set_xlabel('Monocytes satisfying rule (%)')
101
+ ax.set_title(title,fontsize=10);ax.legend(frameon=False,fontsize=8);ax.grid(axis='x',alpha=.15)
102
+ fig.suptitle('Behcet · descriptive unmatched reference; observed set includes training donors',fontsize=10)
103
+ for ext in ['pdf','svg','png']:fig.savefig(out/'figures'/f'fig5_behcet_rules_{tier}.{ext}',dpi=220)
104
+ plt.close(fig)
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/figure5_panels.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Render Figure 5 from the corrected rare-state tables; preserve diagnostic labels."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import matplotlib
10
+ matplotlib.use("Agg")
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+ HERE = Path(__file__).resolve().parents[1]
16
+ M8 = HERE.parents[1]
17
+ BEHCET = M8 / "plans/behcet_c1q_lora3_20261004"
18
+ COLORS = {"lora5": "#006c80", "scsemi5": "#b76938", "zs_raw": "#7d7d88", "zs_cal": "#b38b2d",
19
+ "lora": "#006c80", "pairedcal": "#b38b2d", "scsemi": "#b76938",
20
+ "raw": "#7d7d88", "refcal": "#70569a"}
21
+ ARM_ORDER = {"diagnostic": ("zs_raw", "zs_cal", "scsemi5", "lora5"),
22
+ "strict": ("raw", "refcal", "pairedcal", "scsemi", "lora")}
23
+ REFERENCE_ARM = {"diagnostic": "lora5", "strict": "lora"}
24
+
25
+
26
+ def validate_plot_data(sample: pd.DataFrame, donor: pd.DataFrame,
27
+ summary: pd.DataFrame, tier: str) -> list[str]:
28
+ if tier not in ARM_ORDER:
29
+ raise ValueError(f"unknown Figure 5 evidence tier: {tier}")
30
+ available = set(summary.arm)
31
+ if tier == "strict" and available != set(ARM_ORDER[tier]):
32
+ raise ValueError(f"strict figure arms incomplete: {sorted(available)}")
33
+ arms = [a for a in ARM_ORDER[tier] if a in available]
34
+ if not arms or not set(arms) <= set(sample.arm) or not set(arms) <= set(donor.arm):
35
+ raise ValueError("Figure 5 plotting tables lack matched arm data")
36
+ focus = "C1Q-high monocyte (reference)"
37
+ if summary[(summary.arm == REFERENCE_ARM[tier]) & (summary.state == focus)].empty:
38
+ raise ValueError("Figure 5 reference C1Q state missing")
39
+ if sample[(sample.state == focus) & (sample.arm == REFERENCE_ARM[tier])].empty or donor[
40
+ (donor.state == focus) & (donor.arm == REFERENCE_ARM[tier])].empty:
41
+ raise ValueError("Figure 5 sample/donor C1Q scatter missing")
42
+ if sample[(sample.state_kind == "markers") & (sample.arm.isin(arms))].empty:
43
+ raise ValueError("Figure 5 marker codetection data missing")
44
+ return arms
45
+
46
+
47
+ def _behcet(out: Path) -> pd.DataFrame:
48
+ source = BEHCET / "out/group_table.csv"
49
+ if not source.is_file():
50
+ raise FileNotFoundError(source)
51
+ x = pd.read_csv(source)
52
+ x = x[(x.rows == "test") & (x.metric == "c1q_high_rule_A") &
53
+ x.arm.isin(["zs_raw_s13", "zs_cal_s13", "lora3_raw_s13", "lora3_raw_s04"])]
54
+ x = x.assign(evidence_tier="descriptive_unmatched",
55
+ training="3 BD-only candidate pairs; 2 primary identity passes, 1 uncertain",
56
+ truth="4 BD and 4 HC sc donors mostly unmatched to generated-bulk donors",
57
+ rule="any C1Q gene; weak single-gene state")
58
+ x.to_csv(out / "source_data/rare_behcet_descriptive.csv", index=False)
59
+ return x
60
+
61
+
62
+ def require_visual_readiness(out: Path, tier: str) -> None:
63
+ if tier != "strict":
64
+ raise ValueError("complete visual readiness requires strict Figure 5 data")
65
+ provenance = out / "reports/rare_provenance.json"
66
+ visual = out / "reports/rare_visual_provenance.json"
67
+ if not provenance.is_file() or not visual.is_file():
68
+ raise ValueError("strict Figure 5 visual provenance is incomplete")
69
+ rare = json.loads(provenance.read_text())
70
+ vis = json.loads(visual.read_text())
71
+ if (len(rare.get("units", [])) != 20 or
72
+ {u.get("evidence_tier") for u in rare["units"]} != {"strict"} or
73
+ rare.get("visuals", {}).get("status") != "complete" or
74
+ vis.get("schema") != "pbisc.figure5.marker-visuals.v1" or
75
+ vis.get("status") != "complete" or
76
+ len(vis.get("examples", [])) != 3 or
77
+ any(e.get("status") not in {"available", "unavailable"} for e in vis["examples"])):
78
+ raise ValueError("strict Figure 5 visual readiness is incomplete")
79
+ for ext in ("pdf", "svg", "png"):
80
+ path = out / "figures" / f"fig5_rare_visuals_strict.{ext}"
81
+ if not path.is_file() or path.stat().st_size == 0:
82
+ raise ValueError(f"strict Figure 5 visual asset absent: {path}")
83
+
84
+
85
+ def render(out: Path, *, require_complete: bool = False) -> None:
86
+ src = out / "source_data"
87
+ sample = pd.read_csv(src / "rare_per_sample.csv")
88
+ donor = pd.read_csv(src / "rare_per_donor.csv")
89
+ summary = pd.read_csv(src / "rare_summary.csv")
90
+ if summary.empty:
91
+ raise ValueError("no rare-state data")
92
+ tiers = set(summary.evidence_tier)
93
+ if len(tiers) != 1:
94
+ raise ValueError("do not mix strict and diagnostic analyses in one figure")
95
+ tier = tiers.pop()
96
+ if require_complete:
97
+ require_visual_readiness(out, tier)
98
+ arms = validate_plot_data(sample, donor, summary, tier)
99
+ reference_arm = REFERENCE_ARM[tier]
100
+ behcet = _behcet(out)
101
+ plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 8, "pdf.fonttype": 42})
102
+ fig = plt.figure(figsize=(13.2, 13.5), constrained_layout=True)
103
+ gs = fig.add_gridspec(3, 2, height_ratios=[1.5, 1, 1])
104
+ axs = [fig.add_subplot(gs[i, j]) for i in range(3) for j in range(2)]
105
+ ax = axs[0]
106
+ # Actual observed fractions: median over repeated draws; every state remains visible.
107
+ obs = (summary[summary.arm == reference_arm].groupby(["state", "cohort"], as_index=False)
108
+ .obs_pct.median())
109
+ states = list(dict.fromkeys(summary.state))
110
+ cohorts = list(dict.fromkeys(summary.cohort))
111
+ for i, state in enumerate(states):
112
+ for j, cohort in enumerate(cohorts):
113
+ v = obs[(obs.state == state) & (obs.cohort == cohort)].obs_pct
114
+ if len(v):
115
+ value = float(v.iloc[0])
116
+ ax.scatter(j, i, s=24 + 120 * np.sqrt(max(value, 0) / 100),
117
+ c=[np.log10(value + .01)], cmap="viridis", vmin=-2, vmax=1.5,
118
+ edgecolors="#425260", linewidths=.3)
119
+ ax.annotate(f"{value:.1f}" if value >= .1 else f"{value:.2f}",
120
+ (j, i), xytext=(6, 0), textcoords="offset points",
121
+ va="center", fontsize=5.5, color="#344047")
122
+ ax.set_xticks(range(len(cohorts)), [s.replace("_", " ") for s in cohorts], rotation=25, ha="right")
123
+ ax.set_yticks(range(len(states)), states)
124
+ ax.invert_yaxis()
125
+ ax.set_xlim(-.5, len(cohorts)-.35)
126
+ ax.grid(alpha=.17)
127
+ ax.set_title("A Observed state share within parent (%) · all evaluable rules", loc="left", weight="bold")
128
+ ax = axs[1]
129
+ observed_donors = donor[donor.arm == reference_arm]
130
+ for i, state in enumerate(states):
131
+ for j, cohort in enumerate(cohorts):
132
+ part = observed_donors[(observed_donors.state == state) & (observed_donors.cohort == cohort)]
133
+ if part.empty:
134
+ continue
135
+ counts = part.groupby('unit').agg(present=('obs_state', lambda x: int((x > 0).sum())), total=('donor_id', 'nunique'))
136
+ ax.text(j, i, f"{counts.present.median():g}/{counts.total.median():g}", ha='center', va='center', fontsize=6)
137
+ ax.set_xticks(range(len(cohorts)), [s.replace('_', ' ') for s in cohorts], rotation=25, ha='right')
138
+ ax.set_yticks(range(len(states)), []); ax.set_ylim(len(states)-.5, -.5); ax.set_xlim(-.5,len(cohorts)-.5)
139
+ ax.set_title('Observed-positive / evaluated donors · median across draws',loc='left',fontsize=9,weight='bold')
140
+ ax = axs[2]
141
+ for i, arm in enumerate(arms):
142
+ y = summary.loc[summary.arm == arm, "mae_donor_pp"].dropna()
143
+ if len(y):
144
+ ax.boxplot([y], positions=[i], widths=.48, showfliers=False,
145
+ boxprops=dict(color=COLORS[arm]), whiskerprops=dict(color=COLORS[arm]),
146
+ capprops=dict(color=COLORS[arm]), medianprops=dict(color="#132f39"))
147
+ ax.scatter(np.full(len(y), i) + np.random.default_rng(81+i).uniform(-.2, .2, len(y)),
148
+ y, s=3, color=COLORS[arm], alpha=.2)
149
+ ax.set_xticks(range(len(arms)), arms, rotation=20)
150
+ ax.set_ylabel("Donor absolute error (percentage points)")
151
+ ax.set_title("B Abundance error", loc="left", weight="bold", pad=14)
152
+ ax = axs[3]
153
+ focus = donor[donor.state == "C1Q-high monocyte (reference)"]
154
+ sample_focus = sample[(sample.state == "C1Q-high monocyte (reference)") &
155
+ (sample.arm == reference_arm)].copy()
156
+ sx = 100 * sample_focus.obs_state / sample_focus.obs_parent.replace(0, np.nan)
157
+ sy = 100 * sample_focus.gen_state / sample_focus.gen_parent.replace(0, np.nan)
158
+ ax.scatter(sx, sy, s=5, alpha=.12, label="matched samples (LoRA)", color="#4b5960")
159
+ for arm in arms:
160
+ d = focus[focus.arm == arm]
161
+ ax.scatter(d.obs_pct, d.gen_pct, s=13, alpha=.45, label=arm, color=COLORS[arm])
162
+ lim = max(2, np.nanmax(focus[["obs_pct", "gen_pct"]].to_numpy()) * 1.05) if len(focus) else 2
163
+ ax.plot([0, lim], [0, lim], color="#72818a", linewidth=.8, linestyle="--")
164
+ ax.set(xlim=(0, lim), ylim=(0, lim), xlabel="Observed donor C1Q share (%)",
165
+ ylabel="Generated donor C1Q share (%)")
166
+ ax.legend(frameon=False, fontsize=7)
167
+ ax.set_title("C C1Q share by donor", loc="left", weight="bold", pad=14)
168
+ ax = axs[4]
169
+ marker = sample[(sample.state_kind == "markers") & (sample.arm.isin(arms))]
170
+ cod = marker.groupby("arm", as_index=False)[["obs_codetection", "gen_codetection"]].mean()
171
+ x = np.arange(len(cod))
172
+ ax.bar(x-.17, 100*cod.obs_codetection, width=.34, color="#c7d5d9", label="Observed")
173
+ ax.bar(x+.17, 100*cod.gen_codetection, width=.34,
174
+ color=[COLORS.get(a, "#777") for a in cod.arm], label="Generated")
175
+ ax.set_xticks(x, cod.arm, rotation=20)
176
+ ax.set_ylabel("Parent cells with ≥2 positive markers (%)")
177
+ ax.legend(frameon=False, fontsize=7)
178
+ ax.set_title("D Multi-marker codetection", loc="left", weight="bold", pad=14)
179
+ ax = axs[5]
180
+ names = {"zs_raw_s13": "Zero-shot", "zs_cal_s13": "Calibrated",
181
+ "lora3_raw_s13": "LoRA-3 seed 1", "lora3_raw_s04": "LoRA-3 seed 2"}
182
+ yy = np.arange(len(behcet))
183
+ ax.barh(yy, behcet.gap_pp, color=["#7d7d88", "#b38b2d", "#006c80", "#2497aa"][:len(behcet)])
184
+ ax.axvline(0, color="#3f4b4e", linewidth=.7)
185
+ ax.set_yticks(yy, [names[a] for a in behcet.arm])
186
+ ax.invert_yaxis()
187
+ ax.set_xlabel("BD − HC C1Q-positive monocyte share (pp)")
188
+ ax.set_title("E Behçet disease contrast", loc="left", weight="bold", pad=14)
189
+ ax.text(.01, -.32, "3 candidate BD training pairs (2 primary identity passes, 1 uncertain); "
190
+ "6 BD + 10 HC held-out bulks. Real sc: 4 BD + 4 HC, mostly different donors.\n"
191
+ "Rule A is any C1Q gene; multi-gene C1Q-high cells remain under-produced. "
192
+ "No independent paired-sample claim.", transform=ax.transAxes, va="top", fontsize=7)
193
+ fig.suptitle(f"Figure 5 Rare-state abundance and limits | {tier.upper()}", fontsize=16, weight="bold")
194
+ (out / "figures").mkdir(exist_ok=True)
195
+ for ext in ("pdf", "svg", "png"):
196
+ fig.savefig(out / "figures" / f"fig5_rare_states_{tier}.{ext}", dpi=220, bbox_inches="tight")
197
+ plt.close(fig)
198
+ from figure5_details import render_all_states, render_behcet
199
+ render_all_states(out, donor, summary, tier, arms)
200
+ render_behcet(BEHCET, out, tier)
201
+
202
+
203
+ if __name__ == "__main__":
204
+ ap = argparse.ArgumentParser()
205
+ ap.add_argument("--output", type=Path, default=HERE)
206
+ ap.add_argument("--require-complete", action="store_true")
207
+ args = ap.parse_args()
208
+ render(args.output, require_complete=args.require_complete)
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/finalize_campaign.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Complete source-bound CPU analyses and render Figure 1–5 after the GPU campaign."""
2
+ from __future__ import annotations
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ import time
10
+
11
+ from runtime import Runtime, atomic_json, sha256, stamp
12
+ import campaign as C
13
+
14
+ ROOT = C.ROOT
15
+ ARMS = ("lora", "pairedcal", "scsemi", "raw", "refcal")
16
+ PDF_PY = "/home/sj_server_1/miniforge3/bin/python" # verified pptx, matplotlib, pandas environment
17
+
18
+
19
+ def assert_publication_ready(figures: dict, rare: dict) -> None:
20
+ if figures.get("status") != "complete":
21
+ raise ValueError("Figure 2–4 strict evidence is incomplete")
22
+ if rare.get("design") != "strict5pair" or rare.get("units") != 20:
23
+ raise ValueError("Figure 5 requires all 20 strict units; diagnostic results are insufficient")
24
+
25
+
26
+ def generated_arms(path: Path) -> dict[str, Path]:
27
+ cohort = C.read_support(path)["cohort"]
28
+ values = {a: C.gen_dir(path) / f"{a}.npz" for a in ("lora", "pairedcal", "scsemi")}
29
+ values.update({a: ROOT / "generated/global" / cohort / f"{a}.npz" for a in ("raw", "refcal")})
30
+ return values
31
+
32
+
33
+ def wait_cuda_idle() -> None:
34
+ while True:
35
+ result = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory",
36
+ "--format=csv,noheader"], capture_output=True, text=True, check=True)
37
+ if not result.stdout.strip():
38
+ return
39
+ time.sleep(15)
40
+
41
+
42
+ def deconvolution(runtime: Runtime, units: list[Path]) -> None:
43
+ script = ROOT / "tools/deconv_strict.py"
44
+ for path in units:
45
+ support = C.read_support(path)
46
+ if support["cohort"] == "immicro":
47
+ continue
48
+ out = ROOT / "deconvolution" / C.relative(path)
49
+ for action in ("prepare", "bayesprism", "cibersortx", "score"):
50
+ wait_cuda_idle()
51
+ outputs = {"prepare": [out / "INPUTS.json"],
52
+ "bayesprism": [out / "inputs" / support["cohort"] / "fewshot0_full/bp/DONE"],
53
+ "cibersortx": [out / "cibersortx" / support["cohort"] / "fewshot0/out_fractions/DONE"],
54
+ "score": [out / "score/SUMMARY.json", out / "score/figure4_methods.csv",
55
+ out / "score/expression_signal.csv"]}[action]
56
+ runtime.execute(f"{C.name(path)}-deconv-{action}",
57
+ [C.CPU_PY, "-u", str(script), "--support-manifest", str(path),
58
+ "--action", action, "--threads", "4"], memory_gib=24,
59
+ inputs=[path, script], outputs=outputs,
60
+ previous_outputs=preserve_preview_outputs(runtime, f"{C.name(path)}-deconv-{action}", outputs)
61
+ if action == "prepare" else None)
62
+ if action == "score":
63
+ result = json.loads((out / "score/SUMMARY.json").read_text())
64
+ if result.get("status") not in ("complete", "complete_with_not_estimable"):
65
+ raise ValueError(f"deconvolution is not complete: {out}")
66
+
67
+
68
+ def rare_caches(runtime: Runtime, units: list[Path]) -> None:
69
+ script = ROOT / "tools/rare_cache_builder.py"
70
+ for path in units:
71
+ if C.read_support(path)["cohort"] == "immicro":
72
+ continue
73
+ out = ROOT / "work/rare_strict_caches" / C.relative(path)
74
+ score = ROOT / "scores" / C.relative(path) / "score"
75
+ argv = [C.CPU_PY, "-u", str(script), "--support-manifest", str(path),
76
+ "--score-dir", str(score), "--output-dir", str(out),
77
+ "--cell-budget", "1500", "--depth-target", "1000"]
78
+ for arm, source in generated_arms(path).items():
79
+ argv += ["--arm", f"{arm}={source}"]
80
+ runtime.execute(f"{C.name(path)}-rare-cache", argv, memory_gib=16,
81
+ inputs=[path, script, score / "summary.json", score.parent / "scoring_support.json"],
82
+ outputs=[out / "rare_manifest.json"])
83
+
84
+
85
+ def preserve_diagnostic() -> None:
86
+ """Keep the first diagnostic's source data when strict tables replace the live navigation files."""
87
+ dest = ROOT / "diagnostic_legacy_v1"
88
+ if dest.exists():
89
+ return
90
+ files = [*sorted((ROOT / "source_data").glob("rare_*")),
91
+ *sorted((ROOT / "reports").glob("rare_*")),
92
+ *sorted((ROOT / "figures").glob("fig5*diagnostic*"))]
93
+ records = []
94
+ for path in files:
95
+ if path.is_file():
96
+ target = dest / path.relative_to(ROOT)
97
+ target.parent.mkdir(parents=True, exist_ok=True)
98
+ shutil.copy2(path, target)
99
+ records.append({"path": str(target), "sha256": sha256(target)})
100
+ atomic_json(dest / "PRESERVED.json", {"at": stamp(), "design": "legacy_5donor_diagnostic", "files": records})
101
+
102
+
103
+ def preserve_preview_outputs(runtime: Runtime, name: str, paths: list[Path]) -> dict:
104
+ """A preview may be replaced only after preserving its exact bytes with an explicit receipt."""
105
+ if runtime.receipt_path(name).exists():
106
+ return {}
107
+ proof = {}
108
+ for path in paths:
109
+ if not path.exists():
110
+ continue
111
+ dest = ROOT / "previews/before_strict_final" / name / path.relative_to(ROOT)
112
+ dest.parent.mkdir(parents=True, exist_ok=True)
113
+ if dest.exists() and sha256(dest) != sha256(path):
114
+ raise ValueError(f"a different preview is already preserved: {dest}")
115
+ if not dest.exists():
116
+ shutil.copy2(path, dest)
117
+ proof[str(path)] = {"backup": str(dest), "sha256": sha256(path)}
118
+ if proof:
119
+ atomic_json(ROOT / "previews/before_strict_final" / f"{name}.json", {"at": stamp(), "outputs": proof})
120
+ return proof
121
+
122
+
123
+ def _run_preserving(runtime: Runtime, name: str, argv: list[str], *, memory_gib: int,
124
+ inputs: list[Path], outputs: list[Path]) -> None:
125
+ runtime.execute(name, argv, memory_gib=memory_gib, inputs=inputs, outputs=outputs,
126
+ previous_outputs=preserve_preview_outputs(runtime, name, outputs))
127
+
128
+
129
+ def cross_draw_statistics(runtime: Runtime, units: list[Path]) -> None:
130
+ script = ROOT / "tools/finalize_outputs.py"
131
+ disease = [p for p in units if C.read_support(p)["cohort"] != "immicro"]
132
+ if len(disease) != 20:
133
+ raise ValueError("cross-draw statistics require all 20 disease units")
134
+ inputs = [script, ROOT / "tools/score_strict.py", ROOT / "tools/donor_statistics.py"]
135
+ for path in disease:
136
+ base = ROOT / "scores" / C.relative(path)
137
+ inputs.extend([path, base / "scoring_support.json", base / "score/summary.json",
138
+ base / "score/per_donor.csv", base / "statistics/per_donor_long.csv",
139
+ base / "statistics/status.json"])
140
+ _run_preserving(runtime, "aggregate-five-draw-donor-ci",
141
+ [C.CPU_PY, str(script), "--action", "cross-draw", "--require-complete"],
142
+ memory_gib=8, inputs=inputs,
143
+ outputs=[ROOT / "source_data/fig4_cross_draw_donor_ci.csv",
144
+ ROOT / "source_data/fig4_cross_draw_donor_ci.json"])
145
+
146
+
147
+ def corrected_disease_signal(runtime: Runtime, units: list[Path]) -> None:
148
+ script = ROOT / "tools/disease_signal.py"
149
+ disease = [p for p in units if C.read_support(p)["cohort"] != "immicro"]
150
+ if len(disease) != 20:
151
+ raise ValueError("donor-aware disease signal requires all 20 disease units")
152
+ inputs = [script, ROOT / "tools/score_strict.py", ROOT / "tools/donor_statistics.py"]
153
+ for path in disease:
154
+ base = ROOT / "scores" / C.relative(path)
155
+ deg = base / "statistics/donor_deg"
156
+ inputs.extend([path, base / "scoring_support.json", base / "score/summary.json",
157
+ base / "statistics/status.json", deg / "genes_kept.csv",
158
+ deg / "donor_deg_summary.csv"])
159
+ inputs.extend(sorted(p for p in deg.glob("*/*/*") if p.is_file() and p.name in (
160
+ "donor_condition_pseudobulk.csv", "donor_limma_genes.csv", "limma_status.json")))
161
+ cohort = C.read_support(path)["cohort"]
162
+ inputs.extend([C.OLD / "data" / cohort / "features.npz", C.OLD / "data" / cohort / "folds.csv"])
163
+ names = ("fig4_donor_aware_signal.csv", "fig4_donor_aware_summary.csv",
164
+ "fig4_donor_aware_genes.csv", "fig4_donor_aware_cat.csv",
165
+ "fig4_donor_aware_provenance.json")
166
+ _run_preserving(runtime, "compute-donor-aware-disease-signal",
167
+ [C.CPU_PY, str(script), "--require-complete"], memory_gib=12,
168
+ inputs=inputs, outputs=[ROOT / "source_data" / name for name in names])
169
+
170
+
171
+ def _figure234_outputs() -> list[Path]:
172
+ names = ("fig2_ablation_and_support", "fig3_healthy_strict_oof", "fig3_realism_metrics",
173
+ "fig3_umap_by_celltype", "fig3_composition_fractions", "fig3_runtime_components",
174
+ "fig3_canonical_marker_dotplot", "fig4_disease_strict_draws", "fig4_disease_signal_strict",
175
+ "fig4_disease_signal_scatter", "fig4_disease_signal_heatmap", "fig4_disease_signal_cat",
176
+ "fig4_deconvolution_strict", "fig4_deconvolution_expression_strict",
177
+ "fig4_deconvolution_historical_signal", "fig4_deconvolution_covered_sensitivity",
178
+ "fig4_historical_5fold_separate")
179
+ files = [ROOT / "figures" / f"{name}.{ext}" for name in names for ext in ("pdf", "svg", "png")]
180
+ files += [ROOT / "source_data" / name for name in (
181
+ "fig2_historical_rank_full.csv", "fig2_strict_curve.csv", "fig3_per_sample.csv",
182
+ "fig3_extras.csv", "fig4_strict_per_sample.csv", "fig4_corrected_statistics.csv",
183
+ "fig4_strict_contrast.csv", "fig4_deconvolution.csv", "fig4_deconvolution_signal.csv",
184
+ "fig4_historical_5fold.csv")]
185
+ files += [ROOT / "reports/figures234_readiness.json", ROOT / "reports/figures234_readiness.md"]
186
+ return files
187
+
188
+
189
+ def final_documents(runtime: Runtime, figures: dict, rare: dict) -> None:
190
+ assert_publication_ready(figures, rare)
191
+ deck = ROOT / "tools/build_review_deck.py"
192
+ panel_outputs = [ROOT / "deck" / f"fig1_panel_{panel}.{ext}"
193
+ for panel in ("ab", "cd", "e") for ext in ("png", "svg")]
194
+ _run_preserving(runtime, "render-final-review-deck",
195
+ [PDF_PY, str(deck), "--require-complete"], memory_gib=4,
196
+ inputs=[deck, ROOT / "reports/figures234_readiness.json",
197
+ ROOT / "reports/rare_provenance.json", ROOT / "reports/rare_visual_provenance.json"],
198
+ outputs=[ROOT / "deck/paper_figures_final.pptx", ROOT / "deck/final_gate_sources.json",
199
+ ROOT / "deck/README.md", *panel_outputs])
200
+ manuscript = ROOT / "tools/assemble_manuscript.py"
201
+ stage = ROOT / "manuscript"
202
+ previous_sources = [*stage.glob("*.tex"), *stage.glob("sections/*.tex"),
203
+ stage / "main.pdf", stage / "supplementary.pdf", stage / "integration_manifest.json"]
204
+ # Assembly changes many staged TeX files; preserve the earlier review copy
205
+ # before replacing any of them, while Runtime protects its manifest output.
206
+ proof = preserve_preview_outputs(runtime, "assemble-verified-manuscript", previous_sources)
207
+ manifest = stage / "integration_manifest.json"
208
+ runtime.execute("assemble-verified-manuscript", [C.CPU_PY, str(manuscript), "--require-complete"],
209
+ memory_gib=4,
210
+ inputs=[manuscript, ROOT / "reports/figures234_readiness.json",
211
+ ROOT / "reports/rare_provenance.json",
212
+ ROOT / "source_data/fig4_cross_draw_donor_ci.csv"],
213
+ outputs=[manifest],
214
+ previous_outputs={str(manifest): proof[str(manifest)]} if str(manifest) in proof else {})
215
+ export = ROOT / "tools/finalize_outputs.py"
216
+ _run_preserving(runtime, "compile-final-manuscript-pdfs",
217
+ [PDF_PY, str(export), "--action", "manuscript-pdf", "--require-complete"],
218
+ memory_gib=8, inputs=[export, manifest, stage / "main.tex", stage / "supplementary.tex"],
219
+ outputs=[stage / "main.pdf", stage / "supplementary.pdf"])
220
+ _run_preserving(runtime, "convert-final-deck-pdf",
221
+ [PDF_PY, str(export), "--action", "deck-pdf", "--require-complete"],
222
+ memory_gib=8, inputs=[export, ROOT / "deck/paper_figures_final.pptx",
223
+ ROOT / "deck/final_gate_sources.json"],
224
+ outputs=[ROOT / "deck/paper_figures_final.pdf"])
225
+
226
+
227
+ def render(runtime: Runtime, units: list[Path]) -> None:
228
+ preserve_diagnostic()
229
+ cross_draw_statistics(runtime, units)
230
+ corrected_disease_signal(runtime, units)
231
+ visual = ROOT / "tools/export_healthy_visuals.py"
232
+ _run_preserving(runtime, "export-healthy-visuals", [C.CPU_PY, str(visual)], memory_gib=24,
233
+ inputs=[visual, *units], outputs=[ROOT / "source_data" / name for name in (
234
+ "fig3_visual_data.json", "fig3_visual_data.npz", "fig3_marker_codetection.csv",
235
+ "fig3_runtime_evidence.json", "fig3_runtime.csv", "fig3_runtime.json",
236
+ "fig3_celltype_fractions.csv", "fig3_umap_coordinates.csv")])
237
+ cache_root = ROOT / "work/rare_strict_caches"
238
+ analysis = ROOT / "tools/build_figure5.py"
239
+ _run_preserving(runtime, "analyze-strict-rare", [C.CPU_PY, str(analysis), "--manifest-dir", str(cache_root)],
240
+ memory_gib=12, inputs=[analysis, *sorted(cache_root.rglob("rare_manifest.json"))],
241
+ outputs=[ROOT / "source_data" / name for name in (
242
+ "rare_per_sample.csv", "rare_per_donor.csv", "rare_summary.csv",
243
+ "rare_ineligible_states.csv")])
244
+ export = ROOT / "tools/export_rare_visuals.py"
245
+ _run_preserving(runtime, "export-strict-rare-visuals",
246
+ [C.CPU_PY, str(export), "--manifest-dir", str(cache_root)],
247
+ memory_gib=16, inputs=[export, ROOT / "source_data/rare_summary.csv"],
248
+ outputs=[ROOT / "reports/rare_visual_provenance.json", ROOT / "reports/rare_provenance.json",
249
+ *[ROOT / "source_data" / n for n in ("rare_visual_cells.csv", "rare_visual_heatmap.csv",
250
+ "rare_visual_donor_draws.csv")],
251
+ *[ROOT / "figures" / f"fig5_rare_visuals_strict.{ext}" for ext in ("pdf", "svg", "png")]])
252
+ plot = ROOT / "tools/figure5_panels.py"
253
+ _run_preserving(runtime, "render-strict-rare", [C.CPU_PY, str(plot), "--require-complete"],
254
+ memory_gib=4, inputs=[plot, ROOT / "tools/figure5_details.py", ROOT / "reports/rare_provenance.json"],
255
+ outputs=[ROOT / "source_data" / name for name in ("rare_behcet_descriptive.csv",
256
+ "rare_behcet_per_sample.csv", "rare_all_states.csv", "rare_all_states_aggregate.csv")]
257
+ + [ROOT / "reports/rare_behcet_provenance.json"]
258
+ + [ROOT / "figures" / f"fig5_{stem}_strict.{ext}" for stem in
259
+ ("rare_states", "all_states", "behcet_rules") for ext in ("pdf", "svg", "png")])
260
+ plot = ROOT / "tools/build_results_figures.py"
261
+ _run_preserving(runtime, "render-strict-figures234", [C.CPU_PY, str(plot), "--require-complete"],
262
+ memory_gib=8, inputs=[plot, ROOT / "tools/figure2_panels.py", ROOT / "deconvolution/deconvolution_manifest.json",
263
+ ROOT / "source_data/fig4_cross_draw_donor_ci.json",
264
+ ROOT / "source_data/fig4_donor_aware_provenance.json"],
265
+ outputs=_figure234_outputs())
266
+ ready = json.loads((ROOT / "reports/figures234_readiness.json").read_text())
267
+ rare = json.loads((ROOT / "reports/rare_provenance.json").read_text())
268
+ strict = all(u.get("design") == "strict5pair" and u.get("evidence_tier") == "strict" for u in rare.get("units", []))
269
+ assert_publication_ready(ready, {"design": "strict5pair" if strict else "diagnostic", "units": len(rare.get("units", []))})
270
+ final_documents(runtime, ready, {"design": "strict5pair" if strict else "diagnostic",
271
+ "units": len(rare.get("units", []))})
272
+
273
+
274
+ def main() -> None:
275
+ p = argparse.ArgumentParser(description=__doc__)
276
+ p.add_argument("--stage", choices=("deconvolution", "rare", "render", "all"), default="all")
277
+ a = p.parse_args()
278
+ units = C.discover_units()
279
+ if len(units) != 40:
280
+ raise ValueError("all 40 strict support units are required before finalization")
281
+ runtime = Runtime(ROOT)
282
+ state = {"state": "running", "stage": a.stage, "at": stamp(), "figure6": "waiting_user_data"}
283
+ out = ROOT / "FINALIZATION_STATUS.json"
284
+ atomic_json(out, state)
285
+ try:
286
+ if a.stage in ("deconvolution", "all"):
287
+ deconvolution(runtime, units)
288
+ if a.stage in ("rare", "all"):
289
+ rare_caches(runtime, units)
290
+ if a.stage in ("render", "all"):
291
+ render(runtime, units)
292
+ if a.stage in ("render", "all"):
293
+ artifacts = [ROOT / "manuscript/main.pdf", ROOT / "manuscript/supplementary.pdf",
294
+ ROOT / "deck/paper_figures_final.pptx", ROOT / "deck/paper_figures_final.pdf",
295
+ ROOT / "source_data/fig4_cross_draw_donor_ci.csv",
296
+ ROOT / "source_data/fig4_donor_aware_signal.csv"]
297
+ if any(not p.is_file() or p.stat().st_size == 0 for p in artifacts):
298
+ raise ValueError("final PDF/deck or disease source artifact missing after render")
299
+ state.update(state="complete", artifacts={str(p): sha256(p) for p in artifacts},
300
+ canonical_integration="awaiting_review", archive_update="coordinator_task_end")
301
+ else:
302
+ state.update(state="selected_finalization_stage_complete")
303
+ state["finished_at"] = stamp()
304
+ except BaseException as exc:
305
+ state.update(state="stopped_needs_inspection", error=str(exc), stopped_at=stamp())
306
+ raise
307
+ finally:
308
+ atomic_json(out, state)
309
+
310
+
311
+ if __name__ == "__main__":
312
+ main()
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/finalize_outputs.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """CPU-only final source data and PDF exports after strict evidence gates."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import subprocess
9
+ import tempfile
10
+ from pathlib import Path
11
+
12
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
13
+
14
+ import pandas as pd # noqa: E402
15
+
16
+ from runtime import sha256 # noqa: E402
17
+ from score_strict import read_support, validate_draw_long # noqa: E402
18
+ from donor_statistics import summarize_metrics # noqa: E402
19
+
20
+ ROOT = Path(__file__).resolve().parents[1]
21
+ COHORTS = ("ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
22
+ ARMS = ("lora", "pairedcal", "scsemi", "raw", "refcal")
23
+
24
+
25
+ def cohort_draw_ci(cohort: str, *, draws=range(5)) -> tuple[pd.DataFrame, dict]:
26
+ """One donor-cluster bootstrap over all five verified draws of a cohort."""
27
+ if cohort not in COHORTS or tuple(draws) != tuple(range(5)):
28
+ raise ValueError("cross-draw CI requires exactly five canonical disease draws")
29
+ supports = []
30
+ for draw in draws:
31
+ path = ROOT / "protocol/splits" / cohort / "disease" / f"draw{draw}" / "support.json"
32
+ if not path.is_file():
33
+ raise ValueError(f"five-draw support missing: {path}")
34
+ support = read_support(path)
35
+ if (support.get("cohort") != cohort or support.get("design") != "disease_existing_draw" or
36
+ support.get("unit") != f"draw{draw}_n5" or support.get("n_pairs") != 5):
37
+ raise ValueError(f"five-draw support differs: {path}")
38
+ supports.append(support)
39
+ tables, sources = [], []
40
+ for draw, support in zip(draws, supports):
41
+ path = ROOT / "scores" / cohort / "disease" / f"draw{draw}" / "statistics/per_donor_long.csv"
42
+ status_path = path.parent / "status.json"
43
+ if not status_path.is_file():
44
+ raise ValueError(f"corrected donor DEG pending: {status_path}")
45
+ status = json.loads(status_path.read_text())
46
+ if (status.get("support_sha256") != support["sha256"] or
47
+ status.get("bootstrap_replicates") != 2000 or
48
+ status.get("disease_deg", {}).get("status") not in ("ok", "complete_with_not_estimable")):
49
+ raise ValueError(f"corrected donor DEG pending or wrong support: {status_path}")
50
+ # validate_draw_long requires another current draw; the next frozen
51
+ # support supplies that context so every one of the five is verified.
52
+ current = supports[(draw + 1) % 5]
53
+ table = validate_draw_long(path, current, ARMS)
54
+ tables.append(table)
55
+ sources.append({"unit": support["unit"], "support_sha256": support["sha256"],
56
+ "support_path": str(ROOT / "protocol/splits" / cohort / "disease" / f"draw{draw}" / "support.json"),
57
+ "long_path": str(path), "long_sha256": sha256(path),
58
+ "statistics_status_sha256": sha256(status_path),
59
+ "score_binding_sha256": sha256(path.parents[1] / "scoring_support.json"),
60
+ "score_summary_sha256": sha256(path.parents[1] / "score/summary.json")})
61
+ rows = pd.concat(tables, ignore_index=True)
62
+ if set(rows.draw.astype(str)) != {f"draw{d}_n5" for d in draws}:
63
+ raise ValueError("five verified long tables do not contain five distinct draws")
64
+ result = summarize_metrics(rows, baseline="raw", n_boot=2000, seed=20261012)
65
+ if result.empty or set(result.arm) != set(ARMS) - {"raw"}:
66
+ raise ValueError("cross-draw CI lacks the common five-arm comparison")
67
+ result.insert(0, "cohort", cohort)
68
+ result.insert(1, "design", "strict_exact5_donor_draw_cluster")
69
+ receipt = {"schema": "pbisc.paper.fig4-cross-draw-donor-ci.v1", "cohort": cohort,
70
+ "draws": [f"draw{d}_n5" for d in draws], "baseline": "raw",
71
+ "bootstrap_unit": "unique_donor_all_draws_and_visits", "n_boot": 2000, "seed": 20261012,
72
+ "sources": sources, "n_rows": len(result)}
73
+ return result, receipt
74
+
75
+
76
+ def write_cross_draw_ci() -> None:
77
+ tables, sources = [], []
78
+ for cohort in COHORTS:
79
+ table, receipt = cohort_draw_ci(cohort)
80
+ tables.append(table)
81
+ sources.append(receipt)
82
+ output = ROOT / "source_data/fig4_cross_draw_donor_ci.csv"
83
+ record = ROOT / "source_data/fig4_cross_draw_donor_ci.json"
84
+ output.parent.mkdir(parents=True, exist_ok=True)
85
+ pd.concat(tables, ignore_index=True).to_csv(output, index=False)
86
+ record.write_text(json.dumps({"schema": "pbisc.paper.fig4-cross-draw-donor-ci-collection.v1",
87
+ "cohorts": sources, "csv": str(output), "csv_sha256": sha256(output)},
88
+ indent=2) + "\n")
89
+
90
+
91
+ def _pdf(path: Path) -> None:
92
+ if not path.is_file() or path.stat().st_size < 1024:
93
+ raise ValueError(f"PDF export missing or invalid: {path}")
94
+ with path.open("rb") as stream:
95
+ if stream.read(5) != b"%PDF-":
96
+ raise ValueError(f"PDF export missing or invalid: {path}")
97
+
98
+
99
+ def _require_staged_manuscript() -> None:
100
+ import assemble_manuscript as A
101
+ manifest = ROOT / "manuscript/integration_manifest.json"
102
+ if not manifest.is_file():
103
+ raise ValueError("final staged manuscript manifest missing")
104
+ record = json.loads(manifest.read_text())
105
+ if record.get("mode") != "complete" or record.get("gaps"):
106
+ raise ValueError("staged manuscript is not a complete strict assembly")
107
+ gaps, _ = A.strict_gate()
108
+ if gaps:
109
+ raise ValueError("strict manuscript gate changed: " + "; ".join(gaps[:3]))
110
+ for rel, info in record.get("staged_changes", {}).items():
111
+ path = ROOT / "manuscript" / rel
112
+ if not path.is_file() or sha256(path) != info["sha256"]:
113
+ raise ValueError(f"staged manuscript source changed after assembly: {rel}")
114
+ for rel, old_sha in record.get("canonical_source_sha256", {}).items():
115
+ path = A.CANON / rel
116
+ if not path.is_file() or sha256(path) != old_sha:
117
+ raise ValueError(f"canonical manuscript changed after assembly: {rel}")
118
+
119
+
120
+ def compile_manuscript_pdfs() -> None:
121
+ _require_staged_manuscript()
122
+ stage = ROOT / "manuscript"
123
+ (ROOT / "work").mkdir(parents=True, exist_ok=True)
124
+ with tempfile.TemporaryDirectory(prefix="pbisc-strict-tex-", dir=ROOT / "work") as work:
125
+ temp = Path(work)
126
+ for name in ("main", "supplementary"):
127
+ subprocess.run(["/home/sj_server_1/.local/bin/tectonic", "--keep-logs", "--outdir", str(temp), f"{name}.tex"],
128
+ cwd=stage, check=True)
129
+ _pdf(temp / f"{name}.pdf")
130
+ for name in ("main", "supplementary"):
131
+ (temp / f"{name}.pdf").replace(stage / f"{name}.pdf")
132
+
133
+
134
+ def convert_deck_pdf() -> None:
135
+ import build_review_deck as D
136
+ D.final_gate(ROOT)
137
+ deck = ROOT / "deck/paper_figures_final.pptx"
138
+ if not deck.is_file() or deck.stat().st_size == 0:
139
+ raise ValueError("strict final PPTX missing")
140
+ (ROOT / "work").mkdir(parents=True, exist_ok=True)
141
+ with tempfile.TemporaryDirectory(prefix="pbisc-strict-deck-", dir=ROOT / "work") as work:
142
+ temp = Path(work)
143
+ profile = temp / "lo-profile"
144
+ subprocess.run(["/usr/bin/libreoffice", "-env:UserInstallation=" + profile.as_uri(),
145
+ "--headless", "--convert-to", "pdf", "--outdir", str(temp), str(deck)],
146
+ check=True)
147
+ pdf = temp / "paper_figures_final.pdf"
148
+ _pdf(pdf)
149
+ pdf.replace(ROOT / "deck/paper_figures_final.pdf")
150
+
151
+
152
+ def main() -> None:
153
+ p = argparse.ArgumentParser(description=__doc__)
154
+ p.add_argument("--action", required=True, choices=("cross-draw", "manuscript-pdf", "deck-pdf"))
155
+ p.add_argument("--require-complete", action="store_true")
156
+ a = p.parse_args()
157
+ if not a.require_complete:
158
+ p.error("final outputs require --require-complete")
159
+ if a.action == "cross-draw":
160
+ write_cross_draw_ci()
161
+ elif a.action == "manuscript-pdf":
162
+ compile_manuscript_pdfs()
163
+ else:
164
+ convert_deck_pdf()
165
+
166
+
167
+ if __name__ == "__main__":
168
+ main()