Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261015T141849Z-rare-cell-7k-8k-panels/diffusion/dataset/server_1/model8/plans/rare_gene_context_expansion_20261015/audit_local.py +137 -0
- paper-releases/pbisc-diffusion/updates/20261015T141849Z-rare-cell-7k-8k-panels/diffusion/dataset/server_1/model8/plans/rare_gene_context_expansion_20261015/audit_measurement_and_labels.py +75 -0
- paper-releases/pbisc-diffusion/updates/20261015T141849Z-rare-cell-7k-8k-panels/diffusion/dataset/server_1/model8/plans/rare_gene_context_expansion_20261015/audited_gene_universe.csv +0 -0
- paper-releases/pbisc-diffusion/updates/20261015T141849Z-rare-cell-7k-8k-panels/diffusion/dataset/server_1/model8/plans/rare_gene_context_expansion_20261015/build_panels.py +254 -0
paper-releases/pbisc-diffusion/updates/20261015T141849Z-rare-cell-7k-8k-panels/diffusion/dataset/server_1/model8/plans/rare_gene_context_expansion_20261015/audit_local.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bounded CPU metadata audit; does not import torch or read expression matrices."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
OUT = Path(__file__).resolve().parent
|
| 13 |
+
M = OUT.parents[1]
|
| 14 |
+
LADDER = M / "artifacts/panel_ladder_floor01_1m_20260923"
|
| 15 |
+
RAW = M.parent / "model_7_no_annotation_sh_hwang/data/e2_full_source/metadata/var.parquet"
|
| 16 |
+
ANNOT = M / "plans/aifi_scanvi_rebuild_20260916/runs/aifi_scanvi_f01common_v1"
|
| 17 |
+
SCORES = M / "plans/paired_finetune_intradataset_20260927/scores"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def sha(path: Path) -> str:
|
| 21 |
+
h = hashlib.sha256()
|
| 22 |
+
with path.open("rb") as handle:
|
| 23 |
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
| 24 |
+
h.update(chunk)
|
| 25 |
+
return h.hexdigest()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def binding(path: Path) -> dict:
|
| 29 |
+
return {"path": str(path), "bytes": path.stat().st_size, "sha256": sha(path)}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def write_json(name: str, value: object) -> None:
|
| 33 |
+
(OUT / name).write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def parameters(g: int, widths: list[int], c: int = 512, t: int = 128) -> int:
|
| 37 |
+
linear = lambda a, b: a * b + b
|
| 38 |
+
block = lambda a, b: linear(a, b) + linear(c, b) + 2 * b
|
| 39 |
+
total = linear(t, c) + linear(c, c)
|
| 40 |
+
# SubsetAnnotationFreeConditioner emits G normalized bulk genes + 6 scalars.
|
| 41 |
+
# Two G-wide measurement channels are appended in experiment.py.
|
| 42 |
+
total += linear(3 * g + 6, c) + 2 * c + linear(c, c)
|
| 43 |
+
total += 2 * c + linear(c, c)
|
| 44 |
+
total += block(4 * g, widths[0])
|
| 45 |
+
total += sum(block(a, b) for a, b in zip(widths[:-1], widths[1:]))
|
| 46 |
+
total += sum(block(b, a) for a, b in zip(widths[:-1], widths[1:]))
|
| 47 |
+
total += linear(widths[0], widths[0]) + 2 * widths[0]
|
| 48 |
+
return total + 2 * linear(widths[0], g)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def main() -> None:
|
| 52 |
+
raw = pd.read_parquet(RAW)
|
| 53 |
+
stats = pd.read_csv(LADDER / "full_gene_statistics.csv")
|
| 54 |
+
panel = pd.read_csv(LADDER / "tiers/6k/selected_genes.csv")
|
| 55 |
+
pos = np.load(LADDER / "tiers/6k/gene_positions.npy", allow_pickle=False)
|
| 56 |
+
assert len(raw) == len(stats) == 20097
|
| 57 |
+
assert raw.gene_id.is_unique and panel.gene_id.is_unique
|
| 58 |
+
assert np.array_equal(raw.gene_id.to_numpy(), stats.gene_id.to_numpy())
|
| 59 |
+
assert np.array_equal(panel.panel_position.to_numpy(), pos)
|
| 60 |
+
assert np.array_equal(raw.iloc[pos].gene_id.to_numpy(), panel.gene_id.to_numpy())
|
| 61 |
+
manifest = json.loads((LADDER / "manifest.json").read_text())
|
| 62 |
+
source_checks = {}
|
| 63 |
+
for filename in ["full_gene_statistics", "ranked_gene_positions", "leakage_audit", "ordered_train_recipes", "sampled_cell_references"]:
|
| 64 |
+
p = LADDER / {"full_gene_statistics": "full_gene_statistics.csv", "ranked_gene_positions": "ranked_gene_positions.npy", "leakage_audit": "leakage_audit.json", "ordered_train_recipes": "ordered_train_recipes.csv", "sampled_cell_references": "sampled_cell_references.csv"}[filename]
|
| 65 |
+
expected = manifest.get(filename + "_sha256", manifest["provenance"].get(filename + "_sha256"))
|
| 66 |
+
source_checks[filename] = binding(p) | {"expected_sha256": expected, "matches": sha(p) == expected}
|
| 67 |
+
assert source_checks[filename]["matches"]
|
| 68 |
+
recipes = pd.read_csv(LADDER / "ordered_train_recipes.csv")
|
| 69 |
+
assert set(recipes.split) == {"train"} and not recipes.heldout.any()
|
| 70 |
+
recipes.groupby("platform").agg(recipes=("recipe_id", "size"), unique_sample_keys=("sample_key", "nunique"), dataset_ids=("dataset_id", "nunique"), donor_labels=("donor_id", "nunique")).reset_index().to_csv(OUT / "training_sampler_support.csv", index=False)
|
| 71 |
+
raw[raw.gene_symbol.duplicated(keep=False)].to_csv(OUT / "ambiguous_raw_symbols.csv", index=False)
|
| 72 |
+
annot_genes = pd.read_csv(ANNOT / "genes.csv")
|
| 73 |
+
stats["in_frozen_1005_annotator"] = stats.gene_id.isin(annot_genes.gene_id)
|
| 74 |
+
panels = {
|
| 75 |
+
"final2k": LADDER / "tiers/2k/selected_genes.csv",
|
| 76 |
+
"final6k": LADDER / "tiers/6k/selected_genes.csv",
|
| 77 |
+
"floor01_15114": LADDER / "tiers/p15k/selected_genes.csv",
|
| 78 |
+
"legacy2k_32768sample": M / "artifacts/hvg_2000_train256x128_seed20260627/selected_genes.csv",
|
| 79 |
+
"legacy3k_32768sample": M / "artifacts/hvg_3000_train256x128_seed20260627/selected_genes.csv",
|
| 80 |
+
"legacy6k_v3": M / "artifacts/panel_ladder_train256x128_seed20260627_v3/tiers/6k/selected_genes.csv",
|
| 81 |
+
}
|
| 82 |
+
panel_summary = []
|
| 83 |
+
for name, path in panels.items():
|
| 84 |
+
p = pd.read_csv(path)
|
| 85 |
+
stats["in_" + name] = stats.gene_id.isin(p.gene_id)
|
| 86 |
+
panel_summary.append({"panel": name, "n_genes": len(p), "overlap_final6k": int(p.gene_id.isin(panel.gene_id).sum()), **binding(path)})
|
| 87 |
+
pd.DataFrame(panel_summary).to_csv(OUT / "prior_panel_comparison.csv", index=False)
|
| 88 |
+
ilc = "IL7R KLRB1 RORA RORC GATA3 PTGDR2 IL1RL1 IL17RB CRLF2 KIT IL23R IL1R1 NCR2 NCR1 KLRD1 TBX21 EOMES ZBTB16 BCL11B TCF7 ID2 IL2RA AHR IL22 IL5 IL13 IL17A IL17F IL12RB1 IL12RB2 IL18R1 IL18RAP CCR6 CXCR6 ICOS CD3D CD3E TRAC CD247 NKG7 GNLY PRF1 GZMB".split()
|
| 89 |
+
rows = []
|
| 90 |
+
for gene in ilc:
|
| 91 |
+
found = stats[stats.gene_symbol == gene]
|
| 92 |
+
if found.empty:
|
| 93 |
+
rows.append({"requested_symbol": gene, "resolution": "absent_raw_axis", "raw_available": False})
|
| 94 |
+
else:
|
| 95 |
+
for r in found.to_dict("records"):
|
| 96 |
+
rows.append({"requested_symbol": gene, "resolution": "exact_symbol_multiple_loci" if len(found) > 1 else "exact_symbol", "raw_available": True, **r})
|
| 97 |
+
pd.DataFrame(rows).to_csv(OUT / "ilc_marker_audit.csv", index=False)
|
| 98 |
+
stats.to_csv(OUT / "audited_gene_universe.csv", index=False)
|
| 99 |
+
confusion = pd.read_csv(ANNOT / "confusion_l2.csv", index_col=0)
|
| 100 |
+
config_paths = [M / "runs/f01_6k_1x_seed20260627/effective_config.json", M / "plans/f01_trunk4x_complete_20261013/configs/train.json"]
|
| 101 |
+
config_audit = []
|
| 102 |
+
for path in config_paths:
|
| 103 |
+
config = json.loads(path.read_text())
|
| 104 |
+
config_audit.append(binding(path) | {"n_genes": config["data"]["n_genes"], "positions_sha256": config["data"]["gene_positions_sha256"], "same_final6k": config["data"]["gene_positions_sha256"] == sha(LADDER / "tiers/6k/gene_positions.npy")})
|
| 105 |
+
annotation = {"model_manifest": binding(ANNOT / "MODEL_MANIFEST.json"), "genes": binding(ANNOT / "genes.csv"), "confusion": binding(ANNOT / "confusion_l2.csv"), "n_input_genes": len(annot_genes), "all_inputs_in_final6k": bool(annot_genes.gene_id.isin(panel.gene_id).all()), "ilc_reference_true": int(confusion.loc["ILC"].sum()), "ilc_reference_true_positive": int(confusion.loc["ILC", "ILC"]), "ilc_reference_predicted": int(confusion.ILC.sum()), "ilc_reference_recall": float(confusion.loc["ILC", "ILC"] / confusion.loc["ILC"].sum()), "ilc_reference_precision": float(confusion.loc["ILC", "ILC"] / confusion.ILC.sum()), "score_gate": ["T cell", "B cell", "Monocyte", "NK cell", "DC", "Other"], "ILC_broad_mapping": "Other", "limitation": "Reference performance is not generated-cell biological validation; new genes are ignored by this fixed 1005-gene model."}
|
| 106 |
+
label_rows, label_sources = [], []
|
| 107 |
+
for cohort in ["immicro", "ye2026_sepsis", "imperial_eskd"]:
|
| 108 |
+
score_dir = SCORES / cohort / "fewshot_n5/draw0"
|
| 109 |
+
assert (score_dir / "summary.json").exists()
|
| 110 |
+
for arm in ["lora5", "zs_raw"]:
|
| 111 |
+
f = score_dir / "arms" / arm / "labels/labels.parquet"
|
| 112 |
+
mf = f.parent / "labels.manifest.json"
|
| 113 |
+
labels = pd.read_parquet(f, columns=["sample_id", "aifi_l1", "aifi_l2", "celltype_l1_pred", "aifi_l2_confidence"])
|
| 114 |
+
lm = json.loads(mf.read_text())
|
| 115 |
+
is_ilc = labels.aifi_l1.eq("ILC")
|
| 116 |
+
assert int(is_ilc.sum()) == lm["label_counts"]["aifi_l1"].get("ILC", 0)
|
| 117 |
+
assert labels.loc[is_ilc, "celltype_l1_pred"].eq("Other").all()
|
| 118 |
+
label_rows.append({"cohort": cohort, "support_draw": 0, "arm": arm, "generated_cell_rows": len(labels), "sample_ids": labels.sample_id.nunique(), "ILC_classifier_calls": int(is_ilc.sum()), "ILC_fraction": float(is_ilc.mean()), "Other_broad_calls": int(labels.celltype_l1_pred.eq("Other").sum()), "samples_with_ILC_calls": labels.loc[is_ilc, "sample_id"].nunique(), "ILC_l2_confidence_mean": labels.loc[is_ilc, "aifi_l2_confidence"].mean(), "ILC_calls_l2_confidence_ge_09": int((is_ilc & labels.aifi_l2_confidence.ge(0.9)).sum()), "claim": "saved_classifier_calls_only_not_validated_ILC_identity"})
|
| 119 |
+
label_sources.append({"cohort": cohort, "arm": arm, "labels": binding(f), "manifest": binding(mf), "score_summary": binding(score_dir / "summary.json"), "recorded_generation_source": lm["query_build"], "recorded_annotator": lm["model"]["model_pt_sha256"], "gene_space": lm["gene_space"], "new_inference_or_annotation": False, "large_npz_rehashed": False})
|
| 120 |
+
pd.DataFrame(label_rows).to_csv(OUT / "existing_generated_ilc_calls.csv", index=False)
|
| 121 |
+
write_json("existing_generated_ilc_calls_sources.json", label_sources)
|
| 122 |
+
costs = []
|
| 123 |
+
for name, widths in [("trunk1x", [1024, 1024, 512, 256]), ("trunk4x", [4096, 4096, 2048, 1024])]:
|
| 124 |
+
base = parameters(6000, widths)
|
| 125 |
+
for g in [6000, 7000, 8000]:
|
| 126 |
+
p = parameters(g, widths)
|
| 127 |
+
costs.append({"architecture": name, "genes": g, "parameters_analytic": p, "extra_parameters_vs6k": p - base, "parameter_ratio_vs6k": p / base, "gene_axis_activation_ratio_vs6k": g / 6000, "fp32_weights_extra_MiB": (p - base) * 4 / 2**20, "assumed_20bytes_training_state_extra_MiB": (p - base) * 20 / 2**20, "runtime_measured": False})
|
| 128 |
+
assert costs[0]["parameters_analytic"] == 54185184
|
| 129 |
+
pd.DataFrame(costs).to_csv(OUT / "analytic_cost.csv", index=False)
|
| 130 |
+
p = 16439 / 33141380
|
| 131 |
+
pd.DataFrame([{"N_generated": n, "assumed_prevalence": p, "expected_ILC": n * p, "prob_zero_iid": (1 - p) ** n, "assumption": "hypothetical IID exact source-label prevalence; not observed generation"} for n in [150, 256, 1000, 1500, 4000, math.ceil(math.log(0.05) / math.log(1 - p))]]).to_csv(OUT / "rare_sampling_sensitivity.csv", index=False)
|
| 132 |
+
write_json("local_audit.json", {"status": "CPU_metadata_verified", "raw_axis": binding(RAW), "n_raw_genes": len(raw), "n_final_genes": len(panel), "selected_csv": binding(LADDER / "tiers/6k/selected_genes.csv"), "positions": binding(LADDER / "tiers/6k/gene_positions.npy"), "source_hash_checks": source_checks, "configs": config_audit, "sampler": {"expression_scope": "train_only", "sampled_occurrences": 1048576, "recipes": len(recipes), "datasets": recipes.dataset_id.nunique(), "donor_labels": recipes.donor_id.nunique(), "sample_keys": recipes.sample_key.nunique(), "gene_by_donor_detection_not_available": True, "counts_are_sampled_occurrences_not_proven_unique_cells": True}, "annotation": annotation, "training_source_ILC_cells": 16439, "training_total_cells": 33141380, "training_ILC_fraction": p, "no_cuda_imports": True, "no_expression_reprocessing": True})
|
| 133 |
+
print(json.dumps({"status": "audit_complete", "label_diagnostics": label_rows, "parameters": costs}, indent=2, default=lambda x: x.item()))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20261015T141849Z-rare-cell-7k-8k-panels/diffusion/dataset/server_1/model8/plans/rare_gene_context_expansion_20261015/audit_measurement_and_labels.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audit small precomputed assay masks and existing labels, never expression."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
from audit_local import M, OUT, RAW, SCORES, binding, write_json
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def main() -> None:
|
| 14 |
+
raw = pd.read_parquet(RAW, columns=["gene_id", "gene_symbol"])
|
| 15 |
+
root = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing")
|
| 16 |
+
table = raw.copy()
|
| 17 |
+
receipts = []
|
| 18 |
+
summaries = []
|
| 19 |
+
for cohort, version in [("ye2026_sepsis", "20260927"), ("imperial_eskd", "20260928"), ("giroux2022", "20260928"), ("ji2025_chili", "20260928")]:
|
| 20 |
+
base = root / f"{cohort}_v1_{version}"
|
| 21 |
+
for modality in ["singlecell", "bulk"]:
|
| 22 |
+
masks = sorted((base / modality).glob("**/*.presence_mask.tsv"))
|
| 23 |
+
assert masks, (cohort, modality)
|
| 24 |
+
total = np.zeros(len(raw), dtype=np.int64)
|
| 25 |
+
for f in masks:
|
| 26 |
+
d = pd.read_csv(f, sep="\t", usecols=["gene_id", "source_feature_present"])
|
| 27 |
+
assert d.gene_id.is_unique
|
| 28 |
+
v = d.set_index("gene_id").source_feature_present.reindex(raw.gene_id)
|
| 29 |
+
assert not v.isna().any(), str(f)
|
| 30 |
+
assert set(v.unique()) <= {True, False}
|
| 31 |
+
total += v.to_numpy(dtype=np.int64)
|
| 32 |
+
receipts.append({"cohort": cohort, "modality": modality, **binding(f)})
|
| 33 |
+
prefix = f"{cohort}_{modality}"
|
| 34 |
+
table[prefix + "_measured_masks"] = total
|
| 35 |
+
table[prefix + "_mask_count"] = len(masks)
|
| 36 |
+
table[prefix + "_fraction"] = total / len(masks)
|
| 37 |
+
summaries.append({"cohort": cohort, "modality": modality, "mask_count": len(masks), "genes_present_in_any": int((total > 0).sum()), "genes_present_in_all": int((total == len(masks)).sum()), "scope": "assay-feature availability metadata across source libraries; not expression or train-only abundance", "mask_count_is_sample_count": cohort != "imperial_eskd" and modality == "singlecell"})
|
| 38 |
+
table.to_csv(OUT / "cohort_measurement_masks.csv", index=False)
|
| 39 |
+
write_json("cohort_measurement_mask_sources.json", receipts)
|
| 40 |
+
write_json("cohort_measurement_mask_summary.json", summaries)
|
| 41 |
+
|
| 42 |
+
observations = []
|
| 43 |
+
observation_sources = []
|
| 44 |
+
for cohort in ["immicro", "ye2026_sepsis", "imperial_eskd"]:
|
| 45 |
+
score = SCORES / cohort / "fewshot_n5/draw0/summary.json"
|
| 46 |
+
scored = set(json.loads(score.read_text())["donors"])
|
| 47 |
+
if cohort == "immicro":
|
| 48 |
+
f = M / "plans/utility_studies_final6k_20260925/immicro/labels/observed_immicro/labels.parquet"
|
| 49 |
+
cells = M / "plans/paired_finetune_intradataset_20260927/data/immicro/cells_obs.parquet"
|
| 50 |
+
obs = pd.read_parquet(cells, columns=["cell_index", "donor_id"])
|
| 51 |
+
d = pd.read_parquet(f, columns=["cell_index", "aifi_l1", "aifi_l2", "celltype_l1_pred"])
|
| 52 |
+
d = obs[obs.donor_id.isin(scored)].merge(d, on="cell_index", validate="one_to_one")
|
| 53 |
+
assert len(d) == int(obs.donor_id.isin(scored).sum())
|
| 54 |
+
observation_sources.append({"cohort": cohort, "cell_index_to_donor": binding(cells)})
|
| 55 |
+
else:
|
| 56 |
+
f = M / "plans/paired_finetune_intradataset_20260927/scoring_cache" / cohort / "observed_labels/labels/labels.parquet"
|
| 57 |
+
d = pd.read_parquet(f, columns=["sample_id", "aifi_l1", "aifi_l2", "celltype_l1_pred"])
|
| 58 |
+
d = d[d.sample_id.isin(scored)].copy()
|
| 59 |
+
d["donor_id"] = d.sample_id
|
| 60 |
+
ilc = d.aifi_l1.eq("ILC")
|
| 61 |
+
assert d.loc[ilc, "celltype_l1_pred"].eq("Other").all()
|
| 62 |
+
observations.append({"cohort": cohort, "support_draw": 0, "observed_cell_rows": len(d), "scored_sample_ids": len(scored), "observed_sample_ids": d.donor_id.nunique(), "ILC_classifier_calls": int(ilc.sum()), "ILC_fraction": float(ilc.mean()), "samples_with_ILC_calls": d.loc[ilc, "donor_id"].nunique(), "claim": "saved_observed_classifier_calls_not_author_gold_and_not_donor_balanced"})
|
| 63 |
+
observation_sources.append({"cohort": cohort, "labels": binding(f), "labels_manifest": binding(f.parent / "labels.manifest.json"), "same_scored_donors": binding(score)})
|
| 64 |
+
pd.DataFrame(observations).to_csv(OUT / "existing_observed_ilc_calls.csv", index=False)
|
| 65 |
+
write_json("existing_observed_ilc_calls_sources.json", observation_sources)
|
| 66 |
+
corpus_file = Path("/home/sj_server_1/PBISC/paper-release-20260928/manuscript/source_data/corpus/corpus_cellgroups.csv")
|
| 67 |
+
c = pd.read_csv(corpus_file)
|
| 68 |
+
flu = c[c.condition.eq("Influenza")]
|
| 69 |
+
flu.groupby(["dataset_prefix", "platform", "assay", "split", "condition", "source_disease", "handling"]).agg(n_cells=("n_cells", "sum"), sample_keys=("sample_key", "nunique")).reset_index().to_csv(OUT / "influenza_source_metadata.csv", index=False)
|
| 70 |
+
write_json("influenza_source_metadata_provenance.json", {"source": binding(corpus_file), "dataset_074_A": "COMBAT CELLxGENE collection", "train_cells": int(flu.loc[flu.split.eq("train"), "n_cells"].sum()), "all_cells": int(flu.n_cells.sum()), "expression_accessed": False})
|
| 71 |
+
print(json.dumps({"mask_groups": summaries, "observed_diagnostics": observations}, indent=2))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if __name__ == "__main__":
|
| 75 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20261015T141849Z-rare-cell-7k-8k-panels/diffusion/dataset/server_1/model8/plans/rare_gene_context_expansion_20261015/audited_gene_universe.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
paper-releases/pbisc-diffusion/updates/20261015T141849Z-rare-cell-7k-8k-panels/diffusion/dataset/server_1/model8/plans/rare_gene_context_expansion_20261015/build_panels.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build review-only 7k/8k nested panels from frozen evidence and train HVG stats.
|
| 2 |
+
|
| 3 |
+
Never edits active configs; never imports torch; never reads expression arrays.
|
| 4 |
+
Canonical raw coordinates stay panel_position; CSV row number is new tensor axis.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import collections
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
|
| 16 |
+
from audit_local import ANNOT, LADDER, M, OUT, RAW, binding, sha, write_json
|
| 17 |
+
|
| 18 |
+
HGNC = OUT / "reference/hgnc_complete_set_downloaded.tsv"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def make_resolver(raw: pd.DataFrame):
|
| 22 |
+
hgnc = pd.read_csv(HGNC, sep="\t", usecols=["symbol", "alias_symbol", "prev_symbol", "ensembl_gene_id", "status"], dtype=str).fillna("")
|
| 23 |
+
approved, aliases = collections.defaultdict(set), collections.defaultdict(set)
|
| 24 |
+
raw_ids = set(raw.gene_id)
|
| 25 |
+
symbols = raw.groupby("gene_symbol").gene_id.apply(set).to_dict()
|
| 26 |
+
for row in hgnc.itertuples(index=False):
|
| 27 |
+
if row.status != "Approved" or not row.ensembl_gene_id:
|
| 28 |
+
continue
|
| 29 |
+
approved[row.symbol].add(row.ensembl_gene_id)
|
| 30 |
+
for name in [row.symbol, *row.alias_symbol.split("|"), *row.prev_symbol.split("|")]:
|
| 31 |
+
if name:
|
| 32 |
+
aliases[name].add(row.ensembl_gene_id)
|
| 33 |
+
|
| 34 |
+
def resolve(symbol: str) -> tuple[str, str, str]:
|
| 35 |
+
direct = symbols.get(symbol, set())
|
| 36 |
+
if len(direct) == 1:
|
| 37 |
+
if approved.get(symbol) and not direct & approved[symbol]:
|
| 38 |
+
return "", "raw_symbol_conflicts_current_HGNC_Ensembl_review_required", ";".join(sorted(direct | approved[symbol]))
|
| 39 |
+
return next(iter(direct)), "exact_raw_symbol", ""
|
| 40 |
+
if len(direct) > 1:
|
| 41 |
+
main = direct & approved.get(symbol, set())
|
| 42 |
+
if len(main) == 1:
|
| 43 |
+
return next(iter(main)), "HGNC_primary_Ensembl_resolves_multiple_raw_loci", ";".join(sorted(direct))
|
| 44 |
+
return "", "ambiguous_raw_symbol_unresolved", ";".join(sorted(direct))
|
| 45 |
+
known = approved.get(symbol, set()) or aliases.get(symbol, set())
|
| 46 |
+
if len(known) > 1:
|
| 47 |
+
return "", "ambiguous_HGNC_alias_unresolved", ";".join(sorted(known))
|
| 48 |
+
match = known & raw_ids
|
| 49 |
+
if len(match) == 1:
|
| 50 |
+
return next(iter(match)), "downloaded_HGNC_symbol_or_alias_to_Ensembl", ""
|
| 51 |
+
if len(match) > 1:
|
| 52 |
+
return "", "ambiguous_HGNC_alias_unresolved", ";".join(sorted(match))
|
| 53 |
+
return "", "HGNC_gene_absent_raw_axis" if known else "unresolved_symbol_absent_raw_axis", ";".join(sorted(known))
|
| 54 |
+
|
| 55 |
+
return resolve
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def evidence_rank(row: pd.Series) -> tuple:
|
| 59 |
+
"""Order within one source program; do not compare cross-study effect sizes."""
|
| 60 |
+
stat = {}
|
| 61 |
+
if row.get("source_statistic", ""):
|
| 62 |
+
try:
|
| 63 |
+
stat = json.loads(row.source_statistic)
|
| 64 |
+
except (ValueError, TypeError):
|
| 65 |
+
pass
|
| 66 |
+
for key in ["source_rank", "rank"]:
|
| 67 |
+
value = row.get(key, "") if key == "source_rank" else stat.get(key, "")
|
| 68 |
+
try:
|
| 69 |
+
if value != "" and math.isfinite(float(value)):
|
| 70 |
+
return (0, float(value), row.gene_id)
|
| 71 |
+
except (ValueError, TypeError):
|
| 72 |
+
pass
|
| 73 |
+
for key in ["log2FC", "avg_logFC", "avg_diff"]:
|
| 74 |
+
value = stat.get(key, row.get(key, ""))
|
| 75 |
+
try:
|
| 76 |
+
if value != "" and math.isfinite(float(value)):
|
| 77 |
+
return (1, -abs(float(value)), row.gene_id)
|
| 78 |
+
except (ValueError, TypeError):
|
| 79 |
+
pass
|
| 80 |
+
return (2, int(row.evidence_order), row.gene_id)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def round_robin(groups: dict[str, list[str]]) -> list[str]:
|
| 84 |
+
queues = {key: collections.deque(value) for key, value in sorted(groups.items())}
|
| 85 |
+
result, seen = [], set()
|
| 86 |
+
while queues:
|
| 87 |
+
for key in list(queues):
|
| 88 |
+
queue = queues[key]
|
| 89 |
+
while queue and queue[0] in seen:
|
| 90 |
+
queue.popleft()
|
| 91 |
+
if queue:
|
| 92 |
+
gene = queue.popleft()
|
| 93 |
+
result.append(gene)
|
| 94 |
+
seen.add(gene)
|
| 95 |
+
if not queue:
|
| 96 |
+
del queues[key]
|
| 97 |
+
return result
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def main() -> None:
|
| 101 |
+
raw = pd.read_parquet(RAW)
|
| 102 |
+
stats = pd.read_csv(OUT / "audited_gene_universe.csv")
|
| 103 |
+
old = pd.read_csv(LADDER / "tiers/6k/selected_genes.csv")
|
| 104 |
+
old_ids = set(old.gene_id)
|
| 105 |
+
resolve = make_resolver(raw)
|
| 106 |
+
frames, input_sources = [], []
|
| 107 |
+
for path in sorted(OUT.glob("research/*/evidence.csv")):
|
| 108 |
+
e = pd.read_csv(path, dtype=str).fillna("")
|
| 109 |
+
e["evidence_file"] = str(path.relative_to(OUT))
|
| 110 |
+
e["evidence_csv_row"] = np.arange(len(e)) + 2
|
| 111 |
+
frames.append(e)
|
| 112 |
+
input_sources.append(binding(path))
|
| 113 |
+
assert len(frames) == 2, "Both research agents' evidence.csv files are required"
|
| 114 |
+
e = pd.concat(frames, ignore_index=True).fillna("")
|
| 115 |
+
e["evidence_order"] = np.arange(len(e))
|
| 116 |
+
e["gene_symbol"] = e.gene_symbol.str.strip()
|
| 117 |
+
resolved = [resolve(symbol) for symbol in e.gene_symbol]
|
| 118 |
+
e[["gene_id", "resolution", "ambiguity_or_absent_gene_ids"]] = pd.DataFrame(resolved, index=e.index)
|
| 119 |
+
e["canonical_gene_symbol"] = e.gene_id.map(raw.set_index("gene_id").gene_symbol).fillna("")
|
| 120 |
+
e["raw_available"] = e.gene_id.ne("")
|
| 121 |
+
e["in_final6k"] = e.gene_id.isin(old_ids)
|
| 122 |
+
e["symbol_family_in_final6k"] = e.gene_symbol.isin(old.gene_symbol)
|
| 123 |
+
e["in_frozen_1005_annotator"] = e.gene_id.isin(pd.read_csv(ANNOT / "genes.csv").gene_id)
|
| 124 |
+
for field in ["panel_position", "measured_cells", "detected_cells", "eligible", "universal_rank"]:
|
| 125 |
+
e["train1m_" + field] = e.gene_id.map(stats.set_index("gene_id")[field])
|
| 126 |
+
e["train_support_status"] = np.select([~e.raw_available, e.train1m_measured_cells.eq(0), e.train1m_detected_cells.eq(0)], ["raw_unavailable_or_unresolved", "unmeasured_in_train1m", "measured_but_zero_detected_in_train1m_not_full_corpus_absence"], default="positive_in_train1m")
|
| 127 |
+
# Disease authors' bounded ranked programs get the same fair queue level as
|
| 128 |
+
# supporting blood identity programs, rather than all losing to a large DC list.
|
| 129 |
+
tiers = {"core": 0, "supporting": 1, "optional": 1, "optional_state": 2, "optional_tissue": 3}
|
| 130 |
+
unknown = set(e.priority) - set(tiers)
|
| 131 |
+
assert not unknown, f"Unrecognized evidence priority: {unknown}"
|
| 132 |
+
e["selection_tier"] = e.priority.map(tiers)
|
| 133 |
+
e["program_key"] = e.apply(lambda r: "|".join([r.get("source_id", "") or r.doi or r.primary_source_url, r.get("program", "") or r.population]), axis=1)
|
| 134 |
+
e["source_scope_class"] = e.apply(lambda r: "same_benchmark_source_endpoint_informed" if "same_benchmark" in str(r.get("selection_scope", "")) or any(x in str(r.get("population", "")) for x in ["Ye_", "Imperial_", "Giroux", "Ji_"]) else "external_reference_exposure_not_fully_audited", axis=1)
|
| 135 |
+
sentinel_path = OUT / "research/ilc_dc/protected_sentinels.csv"
|
| 136 |
+
sentinel_symbols = set()
|
| 137 |
+
if sentinel_path.exists():
|
| 138 |
+
sentinels = pd.read_csv(sentinel_path).fillna("")
|
| 139 |
+
sentinel_symbols = set(sentinels.gene_symbol)
|
| 140 |
+
assert sentinel_symbols <= set(e.gene_symbol), "Sentinels need source-supported evidence rows"
|
| 141 |
+
input_sources.append(binding(sentinel_path))
|
| 142 |
+
# Protect assay capability without relabelling tissue/cytokine evidence as
|
| 143 |
+
# universal core identity or as constitutive resting-blood expression.
|
| 144 |
+
e.loc[e.gene_symbol.isin(sentinel_symbols), "selection_tier"] = 0
|
| 145 |
+
e["protected_functional_sentinel"] = e.gene_symbol.isin(sentinel_symbols)
|
| 146 |
+
e["coverage_class"] = np.select([
|
| 147 |
+
e.priority.eq("optional_tissue"),
|
| 148 |
+
e.priority.eq("optional_state"),
|
| 149 |
+
e.source_scope_class.eq("same_benchmark_source_endpoint_informed"),
|
| 150 |
+
e.priority.eq("core") & e.role.str.contains("state|program", case=False, regex=True),
|
| 151 |
+
e.priority.eq("core"),
|
| 152 |
+
], ["optional_tissue", "independent_optional_state", "same_benchmark_targeted_state", "core_state_program", "core_identity_boundary"], default="blood_supporting")
|
| 153 |
+
available = e[e.raw_available & e.train1m_measured_cells.gt(0)].copy()
|
| 154 |
+
priority_order = []
|
| 155 |
+
for tier in sorted(available.selection_tier.unique()):
|
| 156 |
+
populations = {}
|
| 157 |
+
for population, group in available[available.selection_tier.eq(tier)].groupby("population", sort=True):
|
| 158 |
+
programs = {}
|
| 159 |
+
for program, pg in group.groupby("program_key", sort=True):
|
| 160 |
+
rows = sorted([r for _, r in pg.iterrows()], key=evidence_rank)
|
| 161 |
+
programs[program] = list(dict.fromkeys(r.gene_id for r in rows if r.gene_id not in old_ids))
|
| 162 |
+
populations[population] = round_robin(programs)
|
| 163 |
+
priority_order.extend(round_robin(populations))
|
| 164 |
+
priority_order = list(dict.fromkeys(priority_order))
|
| 165 |
+
e["addition_priority_rank"] = e.gene_id.map({g: i + 1 for i, g in enumerate(priority_order)})
|
| 166 |
+
sources = input_sources + [binding(RAW), binding(HGNC), binding(OUT / "reference/hgnc_download_receipt.json"), binding(LADDER / "manifest.json"), binding(LADDER / "full_gene_statistics.csv"), binding(LADDER / "ranked_gene_positions.npy"), binding(LADDER / "tiers/6k/selected_genes.csv"), binding(LADDER / "tiers/6k/gene_positions.npy"), binding(OUT / "audited_gene_universe.csv"), binding(Path(__file__))]
|
| 167 |
+
backfill = stats[stats.eligible & stats.measured_cells.gt(0)].sort_values(["universal_rank", "gene_id"]).gene_id.tolist()
|
| 168 |
+
all_additions = list(dict.fromkeys(priority_order + [g for g in backfill if g not in old_ids]))
|
| 169 |
+
assert len(all_additions) >= 2000
|
| 170 |
+
chosen = {6000: old_ids}
|
| 171 |
+
panels = []
|
| 172 |
+
for size in [7000, 8000]:
|
| 173 |
+
additions = all_additions[:size - 6000]
|
| 174 |
+
selected_ids = old_ids | set(additions)
|
| 175 |
+
chosen[size] = selected_ids
|
| 176 |
+
assert len(selected_ids) == size
|
| 177 |
+
selected = stats[stats.gene_id.isin(selected_ids)].sort_values("panel_position").copy()
|
| 178 |
+
selected["tensor_index"] = np.arange(size)
|
| 179 |
+
selected["selection_reason"] = np.where(selected.gene_id.isin(old_ids), "preserved_final6k", np.where(selected.gene_id.isin(priority_order), "primary_literature_curated", "train_only_HVG_ranked_backfill_not_literature_curated"))
|
| 180 |
+
selected["addition_priority_rank"] = selected.gene_id.map({g: i + 1 for i, g in enumerate(all_additions)})
|
| 181 |
+
subset = e[e.raw_available]
|
| 182 |
+
for column in ["population", "priority", "role", "primary_source_url", "source_scope_class"]:
|
| 183 |
+
lookup = subset.groupby("gene_id")[column].agg(lambda x: ";".join(sorted(set(v for v in x if v)))).to_dict()
|
| 184 |
+
selected["evidence_" + column] = selected.gene_id.map(lookup).fillna("")
|
| 185 |
+
dest = OUT / "panels" / f"{size // 1000}k"
|
| 186 |
+
dest.mkdir(parents=True, exist_ok=True)
|
| 187 |
+
csv_path, pos_path = dest / "selected_genes.csv", dest / "gene_positions.npy"
|
| 188 |
+
selected.to_csv(csv_path, index=False)
|
| 189 |
+
np.save(pos_path, selected.panel_position.to_numpy(dtype=np.int64), allow_pickle=False)
|
| 190 |
+
positions = selected.set_index("gene_id").tensor_index
|
| 191 |
+
mapping = pd.DataFrame({"gene_id": old.gene_id, "gene_symbol": old.gene_symbol, "raw_panel_position": old.panel_position, "old_tensor_index": np.arange(6000), "new_tensor_index": old.gene_id.map(positions)})
|
| 192 |
+
mapping.to_csv(dest / "old_to_new.csv", index=False)
|
| 193 |
+
selected[~selected.gene_id.isin(old_ids)].to_csv(dest / "additions.csv", index=False)
|
| 194 |
+
reason_counts = selected.selection_reason.value_counts().to_dict()
|
| 195 |
+
tier_manifest = {"schema": "pbisc.rare_gene_expansion.candidate.v1", "status": "research_candidate_only_no_training_or_active_config_change", "n_selected_genes": size, "old_n_genes": 6000, "tensor_order": "ascending canonical raw panel_position; CSV row=tensor axis", "gene_id_key": "Ensembl stable ID; duplicate biological symbols are distinct loci, flagged separately", "source_preservation": "all original 6000 Ensembl IDs preserved", "gene_positions_path": str(pos_path), "gene_positions_sha256": sha(pos_path), "selected_genes_path": str(csv_path), "selected_genes_sha256": sha(csv_path), "old_to_new": binding(dest / "old_to_new.csv"), "reason_counts": reason_counts, "source_bindings": sources, "legacy_loader_compatible_manifest": False, "loader_gate": "The existing explicit_train_only_hvg_manifest loader rejects this evidence-driven selector. A reviewed loader/manifest extension is required before training; do not disguise it as train-only HVG.", "gene_selection_expression_scope": "frozen pretraining-train-only HVG statistics; no local held-out expression accessed", "literature_scope": "includes benchmark-author endpoint-informed markers; not fully independent unbiased feature selection", "priority_policy": "core first; fair population and source-program round robin among supporting blood and bounded disease lists; optional stimulation then optional tissue; eligible train-only HVG backfill only if needed", "known_limitations": ["A source-defined program is a candidate feature list, not a complete or sufficient identity test", "1M sampled detection is not population-specific, not full-corpus abundance, and zero is inconclusive", "Official HGNC snapshot fetched 2026-10-15; raw canonical axis remains the existing project freeze", "Raw-unavailable genes require new preprocessing and cannot be appended as zero-valued columns"]}
|
| 196 |
+
(dest / "selection_manifest.json").write_text(json.dumps(tier_manifest, indent=2) + "\n")
|
| 197 |
+
panels.append({"size": size, "n_literature_additions": int(sum(g in priority_order for g in additions)), "n_backfill_additions": int(sum(g not in priority_order for g in additions)), "selected_genes_sha256": sha(csv_path), "gene_positions_sha256": sha(pos_path), "manifest": binding(dest / "selection_manifest.json")})
|
| 198 |
+
assert chosen[6000] < chosen[7000] < chosen[8000]
|
| 199 |
+
for size in [7000, 8000]:
|
| 200 |
+
e[f"in_{size // 1000}k"] = e.gene_id.isin(chosen[size])
|
| 201 |
+
e.to_csv(OUT / "evidence_resolved.csv", index=False)
|
| 202 |
+
e[~e.raw_available].to_csv(OUT / "unavailable_or_ambiguous_evidence.csv", index=False)
|
| 203 |
+
coverage = []
|
| 204 |
+
for population, group in e.groupby("population", sort=True):
|
| 205 |
+
unique = group.drop_duplicates("gene_symbol")
|
| 206 |
+
core = group[group.priority.eq("core")]
|
| 207 |
+
available_ids = set(group.loc[group.raw_available, "gene_id"])
|
| 208 |
+
core_ids = set(core.loc[core.raw_available, "gene_id"])
|
| 209 |
+
row = {"population": population, "core_required_symbols": core.gene_symbol.nunique(), "all_candidate_program_symbols": unique.gene_symbol.nunique(), "raw_available_Ensembl_genes": len(available_ids), "raw_unavailable_or_unresolved_symbols": ";".join(sorted(set(group.loc[~group.raw_available, "gene_symbol"]))), "core_raw_unavailable_or_unresolved_symbols": ";".join(sorted(set(core.loc[~core.raw_available, "gene_symbol"]))), "train1m_positive_genes": group.loc[group.train_support_status.eq("positive_in_train1m"), "gene_id"].nunique(), "train1m_measured_zero_detected_genes": group.loc[group.train_support_status.str.startswith("measured_but_zero"), "gene_id"].nunique(), "gene_specific_donor_platform_signal": "not persisted in frozen pooled statistics; unknown", "source_scope": ";".join(sorted(set(group.source_scope_class)))}
|
| 210 |
+
for size in [6000, 7000, 8000]:
|
| 211 |
+
suffix = str(size // 1000) + "k"
|
| 212 |
+
row["available_" + suffix] = len(available_ids & chosen[size])
|
| 213 |
+
row["core_available_" + suffix] = len(core_ids & chosen[size])
|
| 214 |
+
row["core_missing_available_raw_" + suffix] = ";".join(sorted(set(core.loc[core.raw_available & ~core.gene_id.isin(chosen[size]), "gene_symbol"])))
|
| 215 |
+
row["program_missing_available_raw_" + suffix] = ";".join(sorted(set(group.loc[group.raw_available & ~group.gene_id.isin(chosen[size]), "gene_symbol"])))
|
| 216 |
+
row["program_genes_gained_8k_over_7k"] = len(available_ids & (chosen[8000] - chosen[7000]))
|
| 217 |
+
coverage.append(row)
|
| 218 |
+
coverage_df = pd.DataFrame(coverage)
|
| 219 |
+
coverage_df.to_csv(OUT / "coverage.csv", index=False)
|
| 220 |
+
category_rows = []
|
| 221 |
+
for category, group in e.groupby("coverage_class", sort=True):
|
| 222 |
+
ids = set(group.loc[group.raw_available, "gene_id"])
|
| 223 |
+
row = {"coverage_class": category, "requested_symbols": group.gene_symbol.nunique(), "available_raw_genes": len(ids), "core_available_raw_genes": group.loc[group.raw_available & group.priority.eq("core"), "gene_id"].nunique(), "unresolved_symbols": group.loc[~group.raw_available, "gene_symbol"].nunique(), "interpretation": "overlapping gene sets; category counts must not be added"}
|
| 224 |
+
for size in [6000, 7000, 8000]:
|
| 225 |
+
row[f"available_{size // 1000}k"] = len(ids & chosen[size])
|
| 226 |
+
category_rows.append(row)
|
| 227 |
+
pd.DataFrame(category_rows).to_csv(OUT / "coverage_by_evidence_class.csv", index=False)
|
| 228 |
+
# Every panel gene, including HVG-only backfill, receives measured-source audit fields.
|
| 229 |
+
masks = pd.read_csv(OUT / "cohort_measurement_masks.csv")
|
| 230 |
+
panel_gene_audit = stats[stats.gene_id.isin(chosen[8000])].merge(masks.drop(columns="gene_symbol"), on="gene_id", validate="one_to_one")
|
| 231 |
+
panel_gene_audit["in_7k"] = panel_gene_audit.gene_id.isin(chosen[7000])
|
| 232 |
+
panel_gene_audit["in_8k"] = True
|
| 233 |
+
panel_gene_audit.to_csv(OUT / "panel_gene_measurement_audit.csv", index=False)
|
| 234 |
+
mask_coverage = []
|
| 235 |
+
for cohort in ["ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]:
|
| 236 |
+
for size in [6000, 7000, 8000]:
|
| 237 |
+
d = masks[masks.gene_id.isin(chosen[size])]
|
| 238 |
+
a, b = d[f"{cohort}_singlecell_fraction"], d[f"{cohort}_bulk_fraction"]
|
| 239 |
+
mask_coverage.append({"cohort": cohort, "panel_genes": size, "sc_measured_all_audited_masks": int(a.eq(1).sum()), "bulk_measured_all_audited_masks": int(b.eq(1).sum()), "both_measured_all_audited_masks": int((a.eq(1) & b.eq(1)).sum()), "unavailable_evaluation_policy": "NA or masked; never zero-filled as true absence", "used_for_selection": False})
|
| 240 |
+
pd.DataFrame(mask_coverage).to_csv(OUT / "panel_cohort_measurement_coverage.csv", index=False)
|
| 241 |
+
required_ids = set(available.loc[available.priority.eq("core"), "gene_id"])
|
| 242 |
+
protected_ids = set(available.loc[available.selection_tier.eq(0), "gene_id"])
|
| 243 |
+
positive_ids = set(available.loc[available.train1m_detected_cells.gt(0), "gene_id"])
|
| 244 |
+
summary = {"schema": "pbisc.rare_gene_expansion.v1", "status": "review_only_panels_built", "evidence_rows": len(e), "evidence_requested_symbols": e.gene_symbol.nunique(), "resolved_Ensembl_genes": available.gene_id.nunique(), "curated_missing_from_final6k": len(priority_order), "curated_missing_train1m_positive": len(set(priority_order) & positive_ids), "curated_missing_train1m_zero_detected": len(set(priority_order) - positive_ids), "core_raw_available_unique_genes": len(required_ids), "core_missing_from6k": len(required_ids - old_ids), "protected_functional_sentinel_symbols": sorted(sentinel_symbols), "minimal6k_plus_core_count": len(old_ids | required_ids), "minimal6k_plus_all_available_program_count": len(old_ids | set(priority_order)), "panels": panels, "core_loss_7k": len(required_ids - chosen[7000]), "core_loss_8k": len(required_ids - chosen[8000]), "remaining_full_program_genes_7k": len(set(priority_order) - chosen[7000]), "remaining_full_program_genes_8k": len(set(priority_order) - chosen[8000]), "decision_rule": "Both preserve core. Choose 7k for compact capability, or 8k for additional documented blood/state program coverage; neither panel size is proven necessary or sufficient for biological recovery. Full optional literature union is not a requirement.", "no_active_configs_modified": True, "training_launched": False, "source_bindings": sources, "selection_uses_local_heldout_expression": False, "selection_includes_benchmark_published_endpoint_markers": True}
|
| 245 |
+
write_json("selection_manifest.json", summary)
|
| 246 |
+
summary["minimal6k_plus_core_and_protected_sentinels_count"] = len(old_ids | protected_ids)
|
| 247 |
+
summary["core_and_protected_loss_7k"] = len(protected_ids - chosen[7000])
|
| 248 |
+
summary["core_and_protected_loss_8k"] = len(protected_ids - chosen[8000])
|
| 249 |
+
write_json("selection_manifest.json", summary)
|
| 250 |
+
print(json.dumps({k: v for k, v in summary.items() if k != "source_bindings"}, indent=2))
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
main()
|