junidude14 commited on
Commit
45e27dc
·
verified ·
1 Parent(s): 4df3510

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261004T165054Z-rare-states-screen/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/tools/screen.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rare disease-associated PBMC states beyond C1Q-high monocytes: generated vs observed (CPU only; 2026-10-04).
3
+
4
+ Re-uses the zero-shot arms of plans/c1q_crossdisease_20261004 (final f01 6k model, each sample's own sc pseudobulk at
5
+ K = 1,000, seed 20260913, Poisson read-out seed 20260916, frozen f01common scANVI labels). No new generation.
6
+
7
+ States are defined in tools/states.json:
8
+ kind 'label' : cells whose AIFI L2 label is in `labels`, counted within `parent` (AIFI L2 or L1 names; 'ALL' = all
9
+ cells).
10
+ kind 'markers': cells of `parent` with >= k of the positive genes `genes` detected (count > 0), the rule used for
11
+ C1Q-high monocytes (k = 2 of C1QA/B/C). Optional `require_any`: list of gene groups, each needing
12
+ >= 1 detected gene; optional `exclude`: genes that must all be undetected. Marker definitions follow
13
+ the 2026-10-04 literature survey (README).
14
+ Depth: for marker states, observed parent cells are binomially thinned (seed 20261004) by one constant per dataset and
15
+ state so that their median library on the shared measured panel genes equals the generated parent median (no thinning
16
+ if the observed median is already lower), as in c1q_crossdisease compare.py. Label states use the labels as they are.
17
+ Per sample: parent cells, state cells (observed native, observed thinned, generated). Per dataset and state: pooled
18
+ "X of N" on both sides, generated / observed ratio, Spearman over samples, and the disease contrasts in CONTRASTS
19
+ (difference of per-sample means, observed vs generated).
20
+ usage: screen.py GEN_DIR (GEN_DIR holds <ds>_zs_s13_poisson.h5ad, copied back from spark-0110 and sha-checked)
21
+ outputs: out/per_sample.csv, out/summary.csv, out/contrasts.csv
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import sys
27
+ from pathlib import Path
28
+
29
+ import anndata as ad
30
+ import numpy as np
31
+ import pandas as pd
32
+ import scipy.sparse as sp
33
+ from scipy.stats import spearmanr
34
+
35
+ PLAN = Path(__file__).resolve().parents[1]
36
+ SRC = PLAN.parent / "c1q_crossdisease_20261004"
37
+ CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
38
+ "canonical_genes.tsv")
39
+ SEED = 20261004
40
+ DATASETS = ["dress", "kawasaki", "sle"]
41
+ CONTRASTS = {"kawasaki": [("KD_before", "HC"), ("KD_before", "KD_after")],
42
+ "sle": [("aSLE", "aHD"), ("cSLE", "cHD")],
43
+ "dress": [("DRESS|none", "healthy|none")]}
44
+
45
+
46
+ def parent_mask(lab: pd.DataFrame, parent: list[str]) -> np.ndarray:
47
+ if parent == ["ALL"]:
48
+ return np.ones(len(lab), bool)
49
+ return lab.aifi_l2.isin(parent).to_numpy() | lab.aifi_l1.isin(parent).to_numpy()
50
+
51
+
52
+ def state_cols(st: dict, sym2id: dict, pos: dict) -> tuple[list[str], list[int], list[list[int]], list[int]]:
53
+ """Positive genes (and their columns), require_any groups and exclude genes, restricted to the shared genes."""
54
+ col = lambda gs: [pos[sym2id[g]] for g in gs if sym2id.get(g) in pos]
55
+ genes = [g for g in st["genes"] if sym2id.get(g) in pos]
56
+ req = [col(grp) for grp in st.get("require_any", [])]
57
+ return genes, col(genes), [r for r in req if r], col(st.get("exclude", []))
58
+
59
+
60
+ def call_state(C: np.ndarray, st: dict, n_pos: int, req: list[list[int]], exc: list[int]) -> np.ndarray:
61
+ """C: counts on columns [positive genes | require groups flattened | exclude genes]."""
62
+ det = C > 0
63
+ h = det[:, :n_pos].sum(1) >= st["k"]
64
+ o = n_pos
65
+ for r in req:
66
+ h &= det[:, o:o + len(r)].any(1)
67
+ o += len(r)
68
+ if exc:
69
+ h &= ~det[:, o:o + len(exc)].any(1)
70
+ return h
71
+
72
+
73
+ def rule_text(st: dict, genes_used: list[str]) -> str:
74
+ if st["kind"] == "label":
75
+ return f"AIFI L2 in {st['labels']} / {st['parent']}"
76
+ s = f">= {st['k']} of {' '.join(genes_used)}"
77
+ s += "".join(f"; any of {' '.join(g)}" for g in st.get("require_any", []))
78
+ s += f"; none of {' '.join(st['exclude'])}" if st.get("exclude") else ""
79
+ return f"{s} / {st['parent']}"
80
+
81
+
82
+ def main() -> int:
83
+ gen_dir = Path(sys.argv[1])
84
+ states = json.loads((PLAN / "tools/states.json").read_text())
85
+ canon = pd.read_csv(CANON, sep="\t", dtype=str)
86
+ sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
87
+ rng = np.random.default_rng(SEED)
88
+ per, summ, con = [], [], []
89
+ for ds in DATASETS:
90
+ tag = f"{ds}_zs_s13"
91
+ ob = ad.read_h5ad(SRC / f"data/{ds}/observed_panel6k.h5ad")
92
+ lo = pd.read_parquet(SRC / f"work/obs_labels_{ds}/labels.parquet")
93
+ gn = ad.read_h5ad(gen_dir / f"{tag}_poisson.h5ad")
94
+ lg = pd.read_parquet(SRC / f"work/scanvi_labels_{tag}_f01common/labels.parquet")
95
+ if len(lo) != ob.n_obs or len(lg) != gn.n_obs:
96
+ raise SystemExit(f"{tag}: labels / cells differ")
97
+ groups = pd.read_csv(SRC / f"data/{ds}/samples.csv").set_index("sample_id").group
98
+ Xo, Xg = sp.csr_matrix(ob.X), sp.csr_matrix(gn.X)
99
+ vo, vg = list(ob.var_names.astype(str)), list(gn.var_names.astype(str))
100
+ meas = np.asarray((Xo.sum(0) > 0)).ravel()
101
+ vgs = set(vg)
102
+ shared = [g for g, mk in zip(vo, meas) if mk and g in vgs]
103
+ Xo = Xo[:, [vo.index(g) for g in shared]].tocsr()
104
+ Xg = Xg[:, [vg.index(g) for g in shared]].tocsr()
105
+ pos = {g: i for i, g in enumerate(shared)}
106
+ so, sg = ob.obs.sample_id.astype(str).to_numpy(), gn.obs.sample_id.astype(str).to_numpy()
107
+ libo, libg = np.asarray(Xo.sum(1)).ravel(), np.asarray(Xg.sum(1)).ravel()
108
+ for st in states:
109
+ po, pg = parent_mask(lo, st["parent"]), parent_mask(lg, st["parent"])
110
+ if st["kind"] == "label":
111
+ ho = lo.aifi_l2.isin(st["labels"]).to_numpy() & po
112
+ hg = lg.aifi_l2.isin(st["labels"]).to_numpy() & pg
113
+ ht, thin, genes_used = ho, 1.0, []
114
+ else:
115
+ genes_used, pcols, req, exc = state_cols(st, sym2id, pos)
116
+ cols = pcols + [c for r in req for c in r] + exc
117
+ thin = min(1.0, float(np.median(libg[pg])) / float(np.median(libo[po])))
118
+ co = Xo[:, cols].toarray().astype(np.int64)
119
+ ho = call_state(co, st, len(pcols), req, exc) & po
120
+ ct = rng.binomial(co, thin) if thin < 1.0 else co
121
+ ht = call_state(ct, st, len(pcols), req, exc) & po
122
+ hg = call_state(Xg[:, cols].toarray(), st, len(pcols), req, exc) & pg
123
+ rows = []
124
+ for s in pd.unique(so):
125
+ mo, mg = so == s, sg == s
126
+ rows.append({"dataset": ds, "state": st["name"], "sample_id": s, "group": groups.get(s),
127
+ "obs_parent": int((po & mo).sum()), "obs_state": int((ho & mo).sum()),
128
+ "obsthin_state": int((ht & mo).sum()),
129
+ "gen_parent": int((pg & mg).sum()), "gen_state": int((hg & mg).sum())})
130
+ t = pd.DataFrame(rows)
131
+ for p in ("obs", "obsthin", "gen"):
132
+ par = "gen_parent" if p == "gen" else "obs_parent"
133
+ t[f"{p}_pct"] = 100 * t[f"{p}_state"] / t[par].where(t[par] > 0)
134
+ per.append(t)
135
+ ok = t[["gen_pct", "obsthin_pct"]].dropna()
136
+ rho = float(spearmanr(ok.gen_pct, ok.obsthin_pct).correlation) if len(ok) > 2 else np.nan
137
+ ro = 100 * t.obsthin_state.sum() / max(t.obs_parent.sum(), 1)
138
+ rg = 100 * t.gen_state.sum() / max(t.gen_parent.sum(), 1)
139
+ summ.append({"dataset": ds, "state": st["name"], "rule": rule_text(st, genes_used), "k": st.get("k", ""),
140
+ "thin": round(thin, 3),
141
+ "gen": f"{int(t.gen_state.sum()):,} / {int(t.gen_parent.sum()):,}",
142
+ "obs_thinned": f"{int(t.obsthin_state.sum()):,} / {int(t.obs_parent.sum()):,}",
143
+ "obs_native_n": int(t.obs_state.sum()), "gen_pct": rg, "obs_pct": ro,
144
+ "gen_over_obs": rg / ro if ro else np.nan, "spearman": rho})
145
+ for a, b in CONTRASTS[ds]:
146
+ ga, gb = t[t.group == a], t[t.group == b]
147
+ con.append({"dataset": ds, "state": st["name"], "contrast": f"{a} - {b}",
148
+ "obs_a": ga.obsthin_pct.mean(), "obs_b": gb.obsthin_pct.mean(),
149
+ "gen_a": ga.gen_pct.mean(), "gen_b": gb.gen_pct.mean(),
150
+ "obs_a_counts": f"{int(ga.obsthin_state.sum())} / {int(ga.obs_parent.sum())}",
151
+ "obs_b_counts": f"{int(gb.obsthin_state.sum())} / {int(gb.obs_parent.sum())}",
152
+ "gen_a_counts": f"{int(ga.gen_state.sum())} / {int(ga.gen_parent.sum())}",
153
+ "gen_b_counts": f"{int(gb.gen_state.sum())} / {int(gb.gen_parent.sum())}"})
154
+ out = PLAN / "out"
155
+ P, S, C = pd.concat(per), pd.DataFrame(summ), pd.DataFrame(con)
156
+ C["obs_diff"], C["gen_diff"] = C.obs_a - C.obs_b, C.gen_a - C.gen_b
157
+ C["same_direction"] = np.sign(C.obs_diff) == np.sign(C.gen_diff)
158
+ P.to_csv(out / "per_sample.csv", index=False); S.to_csv(out / "summary.csv", index=False)
159
+ C.to_csv(out / "contrasts.csv", index=False)
160
+ with pd.option_context("display.width", 250, "display.max_columns", 30, "display.max_colwidth", 60):
161
+ print(S.drop(columns="rule").round(3).to_string(index=False))
162
+ print(C[["dataset", "state", "contrast", "obs_a_counts", "obs_b_counts", "gen_a_counts", "gen_b_counts",
163
+ "obs_diff", "gen_diff", "same_direction"]].round(2).to_string(index=False))
164
+ return 0
165
+
166
+
167
+ if __name__ == "__main__":
168
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261004T165054Z-rare-states-screen/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/tools/states.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {"name": "C1Q-high monocyte (reference)", "kind": "markers", "parent": ["Monocyte"], "genes": ["C1QA", "C1QB", "C1QC"], "k": 2},
3
+ {"name": "Cycling T/NK", "kind": "markers", "parent": ["T cell", "NK cell"], "genes": ["MKI67", "TOP2A", "TYMS", "CENPF", "UBE2C", "BIRC5"], "k": 2},
4
+ {"name": "Cycling activated T (CD38/HLA-DR)", "kind": "markers", "parent": ["T cell"], "genes": ["MKI67", "TOP2A", "TYMS", "CENPF", "UBE2C", "BIRC5"], "k": 1, "require_any": [["CD38", "HLA-DRA", "HLA-DRB1"]]},
5
+ {"name": "Proliferating T (label)", "kind": "label", "parent": ["T cell"], "labels": ["Proliferating T cell"]},
6
+ {"name": "Plasmablast (label)", "kind": "label", "parent": ["ALL"], "labels": ["Plasma cell"]},
7
+ {"name": "Plasmablast (markers)", "kind": "markers", "parent": ["ALL"], "genes": ["JCHAIN", "MZB1", "TNFRSF17", "TXNDC5", "PRDM1", "IRF4", "IGLL5"], "k": 3},
8
+ {"name": "MS1 monocyte (IL1R2+)", "kind": "markers", "parent": ["Monocyte"], "genes": ["RETN", "ALOX5AP", "CYP1B1", "MCEMP1", "PLAC8", "CLU", "CD163"], "k": 2, "require_any": [["IL1R2"]]},
9
+ {"name": "Cycling monocyte (Ye 2026)", "kind": "markers", "parent": ["Monocyte"], "genes": ["MKI67", "TOP2A", "TYMS", "CENPF", "UBE2C", "BIRC5"], "k": 1},
10
+ {"name": "ISG-high monocyte (positive control)", "kind": "markers", "parent": ["Monocyte"], "genes": ["ISG15", "IFI6", "IFI27", "IFI44L", "MX1", "OAS1", "IFIT1", "IFIT3", "RSAD2", "SIGLEC1"], "k": 4},
11
+ {"name": "ISG-high T", "kind": "markers", "parent": ["T cell"], "genes": ["ISG15", "IFI6", "IFI27", "IFI44L", "MX1", "OAS1", "IFIT1", "IFIT3", "RSAD2", "SIGLEC1"], "k": 4},
12
+ {"name": "DN2 / ABC B", "kind": "markers", "parent": ["B cell"], "genes": ["ITGAX", "TBX21", "FCRL5", "FGR", "TFEC", "SOX5", "ZEB2"], "k": 2, "require_any": [["ITGAX", "TBX21"]], "exclude": ["CR2"]},
13
+ {"name": "HSPC", "kind": "markers", "parent": ["ALL"], "genes": ["CD34", "PRSS57", "SPINK2", "SMIM24"], "k": 2},
14
+ {"name": "Cytotoxic CD4 T", "kind": "markers", "parent": ["Naive CD4 T cell", "Memory CD4 T cell", "Treg"], "genes": ["GZMH", "GZMB", "GZMA", "PRF1", "NKG7", "GNLY", "FGFBP2", "CX3CR1", "ZNF683"], "k": 3, "exclude": ["CCR7"]},
15
+ {"name": "Granulocyte-like (LDG)", "kind": "markers", "parent": ["ALL"], "genes": ["ELANE", "MPO", "CTSG", "CAMP", "LCN2", "MMP9", "CSF3R", "CXCR2", "FCGR3B"], "k": 2},
16
+ {"name": "Platelet signal in monocytes (negative control)", "kind": "markers", "parent": ["Monocyte"], "genes": ["PPBP", "PF4", "TUBB1", "GP9", "NRGN"], "k": 2}
17
+ ]
paper-releases/pbisc-diffusion/updates/20261004T165054Z-rare-states-screen/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/work/corpus_v1.err ADDED
File without changes
paper-releases/pbisc-diffusion/updates/20261004T165054Z-rare-states-screen/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/work/corpus_v1.log ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ state ABC / DN2 B C1Q-high monocyte (reference) Cytotoxic CD4 T GZMK+ CD8 T Granulocyte-like (LDG) ISG-high monocyte MS1 monocyte Plasmablast (label) Plasmablast (markers) Platelet-bound monocyte Progenitor (label) Proliferating T (label)
2
+ short
3
+ 001_A_collection_436154da-bcf1-4130-9c8b 2.86 1.72 1.17 19.00 0.37 13.39 7.71 0.16 1.11 3.68 0.06 1.19
4
+ 005_A_collection_dde06e0f-ab3b-46be-96a2 3.69 1.97 1.75 23.30 0.16 6.23 9.84 0.31 3.01 3.93 0.16 0.97
5
+ 006_A_collection_ced320a1-29f3-47c1-a735 14.73 2.41 1.43 23.19 0.97 12.88 14.37 0.00 6.52 1.70 0.00 0.21
6
+ 007_A_collection_e1a9ca56-f2ee-435d-980a 0.86 0.41 0.00 6.03 0.01 1.09 0.54 0.04 0.00 0.00 0.02 0.19
7
+ 009_A_Human_Immune_Health_Atlas_Human_Im 10.71 0.99 0.77 27.63 1.34 16.49 19.01 0.09 1.76 1.68 0.12 0.52
8
+ 010_A_collection_4a9fd4d7-d870-4265-89a5 26.33 0.40 0.00 13.06 0.81 4.09 0.74 0.16 0.39 0.34 0.08 1.19
9
+ 053_B_collection_b0cf0afa-ec40-4d65-b570 24.59 2.69 3.41 20.74 4.40 34.97 28.90 0.25 7.42 5.54 0.15 0.60
10
+ 058_B_collection_eb735cc9-d0a7-48fa-b255 10.28 2.61 1.01 19.22 1.94 11.52 27.25 1.16 12.53 7.56 0.39 2.64
11
+ 061_A_GSE274680_Savage_Allen_RA_at-risk_ 11.48 1.40 1.17 30.28 1.71 11.21 19.49 0.06 3.07 3.87 0.06 0.57
12
+ 065_A_GSE271896_GSE271896_Sound_Life_dee 8.78 0.83 0.35 16.37 2.30 20.81 22.98 0.00 1.22 1.17 0.10 0.96
13
+ 071_C_JDM_CITE-seq_PBMC_CELLxGENE_JDM_CI 13.06 0.32 0.35 4.42 1.27 24.07 25.18 0.34 4.16 5.00 0.14 0.59
14
+ 074_A_COMBAT_CELLxGENE_collection_COMBAT 8.87 3.82 1.05 29.22 2.40 28.84 34.98 1.19 19.22 0.12 0.20 4.41
15
+ 081_B_Single-cell_atlas_of_peripheral_im 8.30 0.69 0.43 2.75 2.31 35.24 19.20 2.35 16.85 2.51 0.30 6.71
16
+ 093_C_Local_and_systemic_SARS-CoV-2_resp 9.80 2.34 0.30 13.97 0.68 21.69 13.51 0.46 4.51 3.58 0.32 0.36
17
+ 200_A_GSE275067_Immunobiology_of_Aging_C NaN 1.19 1.57 14.71 2.33 28.40 20.36 0.00 NaN 4.27 0.12 2.23
18
+ 202_B_GSE161918_Time-resolved_Systems_Im 5.00 1.94 2.05 24.48 1.64 10.82 29.82 0.24 3.50 0.68 0.08 0.42
19
+ 203_B_CELLxGENE_665714af_Ancestral_and_e 14.69 1.56 0.92 14.80 0.46 6.89 9.55 0.61 7.18 2.11 0.00 0.18
20
+ 204_B_CELLxGENE_cHSPC_aging_MDS_Human_ci 11.31 0.58 0.00 0.00 1.63 12.57 8.77 0.05 0.70 11.40 64.38 0.62
21
+ 300b_A_GSE132802_DRESS_DiHS_PBMC_only_sc 9.75 14.94 0.18 12.07 1.61 7.29 21.96 0.86 12.27 1.29 0.18 21.34
22
+ 301_A_GSE163121_SLE_healthy_Bcell_PBMC_s 12.33 0.00 0.00 4.00 0.11 6.11 24.05 1.39 1.80 6.11 0.19 0.19
23
+ 302_A_GSE314010_SLE_IL36_stim_PBMC_scRNA 8.84 5.69 0.62 13.95 0.55 18.05 8.99 0.11 2.95 0.45 0.04 0.06
24
+ 304_A_Parse_10M_PBMC_12donor_90cytokines 16.20 4.67 0.04 4.71 0.10 70.09 1.97 0.59 1.05 0.73 0.55 1.27
25
+ state_cells parent_cells pct
26
+ state
27
+ ABC / DN2 B 2940 24494 12.003
28
+ C1Q-high monocyte (reference) 808 32766 2.466
29
+ Cytotoxic CD4 T 435 47390 0.918
30
+ GZMK+ CD8 T 4274 25675 16.647
31
+ Granulocyte-like (LDG) 2357 179750 1.311
32
+ ISG-high monocyte 6664 32766 20.338
33
+ MS1 monocyte 6227 32766 19.004
34
+ Plasmablast (label) 837 179750 0.466
35
+ Plasmablast (markers) 967 24494 3.948
36
+ Platelet-bound monocyte 902 32766 2.753
37
+ Progenitor (label) 5896 179750 3.280
38
+ Proliferating T (label) 2245 93391 2.404
39
+ dataset_id state missing_genes
40
+ 007_A_collection_e1a9ca56-f2ee-435d-980a-4f49ab7a95_Miao_et_al._RA_PBMC_disease_activity-associated_PBMC_subsets Platelet-bound monocyte PPBP PF4
41
+ 007_A_collection_e1a9ca56-f2ee-435d-980a-4f49ab7a95_Miao_et_al._RA_PBMC_disease_activity-associated_PBMC_subsets Granulocyte-like (LDG) MPO
42
+ 010_A_collection_4a9fd4d7-d870-4265-89a5-ad51ab811d_ScaleBio_single-cell_RNA_sequencing_of_human_PBMCs Granulocyte-like (LDG) LCN2
43
+ 301_A_GSE163121_SLE_healthy_Bcell_PBMC_scRNAseq C1Q-high monocyte (reference) C1QC
44
+ 304_A_Parse_10M_PBMC_12donor_90cytokines Platelet-bound monocyte GP9
45
+ 304_A_Parse_10M_PBMC_12donor_90cytokines Granulocyte-like (LDG) CAMP LCN2