Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/81d2e64740e87da5/liu2021_assemble.py +742 -0
- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/aggregate_loco.py +142 -0
- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/prepare_loco_extra.py +166 -0
- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/score_pending.sh +100 -0
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/81d2e64740e87da5/liu2021_assemble.py
ADDED
|
@@ -0,0 +1,742 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Assemble the Liu 2021 (GSE161918) paired bulk <-> scRNA fine-tuning files (CPU only).
|
| 3 |
+
|
| 4 |
+
Adapted from the Giroux 2022 build (processing/giroux2022_v1_20260928/code/giroux2022_assemble.py); same output files,
|
| 5 |
+
keys and semantics. Study-specific differences:
|
| 6 |
+
* one row = one subject at one timepoint (author labels T0-T3, or HC); a COVID-19 subject has 1-4 rows;
|
| 7 |
+
donor_ids = subject; timepoints = the author timepoint label (string; days since onset is a separate key);
|
| 8 |
+
* bulk_raw is NaN where bulk_valid is False (the task contract; ImMicro does the same; Giroux/Ye/Imperial store 0,
|
| 9 |
+
and tools/prepare_dataset.py accepts both via drop_unmeasured_nan); pseudo_raw_sum is 0 where sc_valid is False;
|
| 10 |
+
* all four Y genes are rows of the author bulk table, so bulk and sc use the same 4-gene Y score (the Ye rule);
|
| 11 |
+
where the sc pseudobulk call is ambiguous (pooled lanes: ambient pool-mate RNA; low 5' XIST capture) the sc call
|
| 12 |
+
falls back to per-cell detection, verbatim the Imperial ESKD rule;
|
| 13 |
+
* the donor-sensitive expression test ranks SUBJECTS (a subject's other timepoints are the same person), removes
|
| 14 |
+
k = 5 sample PCs per modality (70 sc samples / 73 bulk columns; k = 3 and 10 are sensitivity), and leaves chrY
|
| 15 |
+
genes out so it is independent of the sex check; the null pool includes the unpaired technical-control and
|
| 16 |
+
author-excluded samples (CHI014, HD_ML/HD_VO, SHD8), whose subjects are normalised to one label per person.
|
| 17 |
+
|
| 18 |
+
Inputs (processing run, produced by liu2021_pipeline.py):
|
| 19 |
+
pairing/pairs_primary.csv, pairing/bulk_count_columns.csv, pairing/sc_samples.csv, pairing/sc_cell_obs.parquet,
|
| 20 |
+
bulk/GSE161918_htseq/harmonized.h5ad, bulk/bulk_source_counts.npz,
|
| 21 |
+
singlecell/<sample>/{canonical.h5ad, pseudobulk_per_published_sample.h5, source_axis_pseudobulk.npz,
|
| 22 |
+
cell_sex_gene_counts.npz, summary.json}
|
| 23 |
+
Outputs (OUT):
|
| 24 |
+
features.npz, cells_panel6k.npz, cells_obs.parquet, samples.csv, pairs.csv, identity_sex_bulk_all.csv,
|
| 25 |
+
identity_sex_sc_all.csv, identity_expression.csv, MANIFEST.json (QC_REPORT.md is written by hand)
|
| 26 |
+
Processing-run extras: identity/ (full residual correlation matrices).
|
| 27 |
+
|
| 28 |
+
Rows = accepted pairs ordered by bulk GSM. Retained cells = flag_conservative_review_pass (qc_core: >= 200 genes,
|
| 29 |
+
>= 500 UMIs, <= 20 % mito), the ImMicro definition, applied to the author's unsorted HTO-singlet cells. Identity checks
|
| 30 |
+
are reported, never used to drop rows.
|
| 31 |
+
"""
|
| 32 |
+
from __future__ import annotations
|
| 33 |
+
|
| 34 |
+
import hashlib
|
| 35 |
+
import json
|
| 36 |
+
import os
|
| 37 |
+
import re
|
| 38 |
+
import shutil
|
| 39 |
+
import sys
|
| 40 |
+
from datetime import datetime, timezone
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
|
| 43 |
+
import h5py
|
| 44 |
+
import numpy as np
|
| 45 |
+
import pandas as pd
|
| 46 |
+
import scipy.sparse as sp
|
| 47 |
+
from scipy.stats import rankdata
|
| 48 |
+
|
| 49 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 50 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 51 |
+
|
| 52 |
+
DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
|
| 53 |
+
RUN = DATALAKE / "processing/liu2021_v1_20261002"
|
| 54 |
+
REFERENCE = DATALAKE / "processing/strict_qc_v1_20260913/reference"
|
| 55 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 56 |
+
TASK = M8 / "plans/paired_finetune_intradataset_20260927"
|
| 57 |
+
OUT = TASK / "data/liu2021"
|
| 58 |
+
POSITIONS = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy"
|
| 59 |
+
POSITIONS_SHA = "653ffa45ac519000baa41086c52408009391d6e68cfb218bc6a50d34163fcb24"
|
| 60 |
+
SELECTED = POSITIONS.parent / "selected_genes.csv"
|
| 61 |
+
REF_PANEL = TASK / "data/giroux2022/cells_panel6k.npz" # the panel order every built dataset uses
|
| 62 |
+
TMP = RUN / "assemble_tmp"
|
| 63 |
+
IDENT = RUN / "identity"
|
| 64 |
+
SEX_GENES = ["XIST", "RPS4Y1", "DDX3Y", "UTY", "KDM5D"]
|
| 65 |
+
SEX_IDS = {"XIST": "ENSG00000229807", "RPS4Y1": "ENSG00000129824", "DDX3Y": "ENSG00000067048",
|
| 66 |
+
"UTY": "ENSG00000183878", "KDM5D": "ENSG00000012817"}
|
| 67 |
+
Y_GENES = ["RPS4Y1", "DDX3Y", "UTY", "KDM5D"]
|
| 68 |
+
TOP_N = 2000
|
| 69 |
+
RESID_K = (5, 3, 10) # k = 5 primary; 3 and 10 sensitivity
|
| 70 |
+
K_PRIMARY = 5
|
| 71 |
+
SUBJ_TOP = 3 # verdict: own subject 1st in one direction and within the top 3 subjects in the other
|
| 72 |
+
ISG_GENES = ["IFI27", "IFI44L", "ISG15", "RSAD2", "IFIT1", "IFIT3", "MX1", "OAS1", "OAS3", "SIGLEC1", "IFI6", "HERC5"]
|
| 73 |
+
MIN_CELLS = 200 # tools/prepare_dataset.py MIN_CELLS (rows below it are written and flagged)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def sha256_file(path: Path) -> str:
|
| 77 |
+
h = hashlib.sha256()
|
| 78 |
+
with open(path, "rb") as f:
|
| 79 |
+
for block in iter(lambda: f.read(1 << 24), b""):
|
| 80 |
+
h.update(block)
|
| 81 |
+
return h.hexdigest()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def text(values) -> np.ndarray:
|
| 85 |
+
return np.asarray([v.decode() if isinstance(v, bytes) else str(v) for v in values])
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def require(ok: bool, msg: str) -> None:
|
| 89 |
+
if not ok:
|
| 90 |
+
raise SystemExit(msg)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def sex_call(xist_cpm: float, y_cpm: float) -> tuple[str, float]:
|
| 94 |
+
"""female if log2(XIST+1)-log2(Ysum+1) > 2, male if < -2, else ambiguous (the Ye 2026 rule)."""
|
| 95 |
+
score = float(np.log2(xist_cpm + 1) - np.log2(y_cpm + 1))
|
| 96 |
+
return ("female" if score > 2 else "male" if score < -2 else "ambiguous"), score
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def spearman_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
|
| 100 |
+
ra = rankdata(a, axis=1)
|
| 101 |
+
rb = rankdata(b, axis=1)
|
| 102 |
+
ra = (ra - ra.mean(1, keepdims=True)) / ra.std(1, keepdims=True)
|
| 103 |
+
rb = (rb - rb.mean(1, keepdims=True)) / rb.std(1, keepdims=True)
|
| 104 |
+
return ra @ rb.T / a.shape[1]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def pearson_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
|
| 108 |
+
a = (a - a.mean(1, keepdims=True)) / a.std(1, keepdims=True)
|
| 109 |
+
b = (b - b.mean(1, keepdims=True)) / b.std(1, keepdims=True)
|
| 110 |
+
return a @ b.T / a.shape[1]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def subject_rank(scores: np.ndarray, subjects: np.ndarray, own: str) -> tuple[int, str, float]:
|
| 114 |
+
"""Rank of subject `own` when every subject is scored by its best-matching sample (1 = best)."""
|
| 115 |
+
best = pd.Series(scores).groupby(subjects).max().sort_values(ascending=False, kind="mergesort")
|
| 116 |
+
return int(np.flatnonzero(best.index.to_numpy() == own)[0]) + 1, str(best.index[0]), float(best.iloc[0])
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def person(label: str) -> str:
|
| 120 |
+
"""One identity label per person for the unpaired controls (CHI014 in three batches; the HD_ML / HD_VO donors'
|
| 121 |
+
buffy-coat and PBMC aliquots); every other subject keeps its own name."""
|
| 122 |
+
m = re.fullmatch(r"HD_?(ML|VO)(_(bc|PBMC))?", label)
|
| 123 |
+
if m:
|
| 124 |
+
return "HD" + m.group(1)
|
| 125 |
+
return "CHI014" if re.fullmatch(r"CHI-?014(_B\d)?", label) else label
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def tp_order(t: str) -> int:
|
| 129 |
+
return int(t[1:]) if re.fullmatch(r"T\d", t) else -1
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def fnum(v) -> float:
|
| 133 |
+
try:
|
| 134 |
+
return float(v)
|
| 135 |
+
except (TypeError, ValueError):
|
| 136 |
+
return float("nan")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def main() -> int:
|
| 140 |
+
t0 = datetime.now(timezone.utc)
|
| 141 |
+
require(sha256_file(POSITIONS) == POSITIONS_SHA, "gene_positions.npy sha differs from the final run's")
|
| 142 |
+
positions = np.load(POSITIONS).astype(np.int64)
|
| 143 |
+
canonical = pd.read_csv(REFERENCE / "canonical_genes.tsv", sep="\t", dtype=str)
|
| 144 |
+
gene_ids = canonical.gene_id.to_numpy().astype("U15")
|
| 145 |
+
require(gene_ids.dtype.kind == "U" and all(len(x) == 15 for x in gene_ids), "gene id dtype")
|
| 146 |
+
require(len(gene_ids) == 20097 and canonical.panel_index.astype(int).tolist() == list(range(20097)), "axis")
|
| 147 |
+
chr_y = canonical.chromosome.astype(str).isin(["Y", "chrY"]).to_numpy()
|
| 148 |
+
selected = pd.read_csv(SELECTED)
|
| 149 |
+
require(np.array_equal(selected.gene_id.to_numpy(), gene_ids[positions]), "panel ids differ from positions")
|
| 150 |
+
with np.load(REF_PANEL, allow_pickle=False) as z:
|
| 151 |
+
ref_panel = z["panel_gene_ids"].astype(str)
|
| 152 |
+
require(np.array_equal(ref_panel, gene_ids[positions]), "panel ids differ from giroux2022 cells_panel6k.npz")
|
| 153 |
+
|
| 154 |
+
pairs = pd.read_csv(RUN / "pairing/pairs_primary.csv", dtype=str, keep_default_na=False)
|
| 155 |
+
cols = pd.read_csv(RUN / "pairing/bulk_count_columns.csv", dtype=str, keep_default_na=False)
|
| 156 |
+
scs = pd.read_csv(RUN / "pairing/sc_samples.csv", dtype=str, keep_default_na=False)
|
| 157 |
+
summaries = {g: json.loads((RUN / "singlecell" / g / "summary.json").read_text()) for g in scs.sc_sample}
|
| 158 |
+
bad = [g for g, s in summaries.items() if s["status"] != "PASS"]
|
| 159 |
+
quarantined_pairs = sorted(set(bad) & set(pairs.sc_sample))
|
| 160 |
+
pairs = pairs[~pairs.sc_sample.isin(bad)].sort_values("bulk_gsm").reset_index(drop=True)
|
| 161 |
+
n = len(pairs)
|
| 162 |
+
|
| 163 |
+
# ---------------- bulk (canonical, harmonized by qc_bulk.harmonize)
|
| 164 |
+
import anndata as ad
|
| 165 |
+
bad_ = ad.read_h5ad(RUN / "bulk/GSE161918_htseq/harmonized.h5ad")
|
| 166 |
+
bX = np.asarray(bad_.X, dtype=np.float64)
|
| 167 |
+
b_valid = np.asarray(bad_.layers["harmonization_valid"]).astype(bool)
|
| 168 |
+
b_index = bad_.obs_names.to_numpy().astype(str) # author column names
|
| 169 |
+
b_gsm = bad_.obs["source_GSM"].astype(str).to_numpy()
|
| 170 |
+
require(np.array_equal(bad_.var_names.to_numpy().astype(str), gene_ids), "bulk gene order")
|
| 171 |
+
require(str(bad_.uns["units"]) == "htseq_count_raw_gene_counts", "bulk units")
|
| 172 |
+
require(bool(bad_.uns["raw_count_eligible"]), "bulk not raw-count eligible")
|
| 173 |
+
del bad_
|
| 174 |
+
bcol = {c: i for i, c in enumerate(b_index)}
|
| 175 |
+
require(len(bcol) == len(b_index), "duplicate bulk column")
|
| 176 |
+
inside = bX[b_valid]
|
| 177 |
+
require(np.isfinite(inside).all() and (inside >= 0).all() and np.array_equal(inside, np.rint(inside)),
|
| 178 |
+
"bulk values inside the measured mask must be nonnegative integers")
|
| 179 |
+
require(np.isnan(bX[~b_valid]).all(), "bulk values outside the mask must be NaN in the harmonized file")
|
| 180 |
+
bulk_all = np.where(b_valid, bX, 0.0)
|
| 181 |
+
cmeta = cols.set_index("bulk_column")
|
| 182 |
+
require(list(cmeta.index) == list(b_index), "bulk column order")
|
| 183 |
+
b_subject = np.asarray([person(s) for s in cmeta.loc[b_index, "subject"]])
|
| 184 |
+
b_label = b_index.copy()
|
| 185 |
+
|
| 186 |
+
# ---------------- sc per sample: pseudobulk sums and masks for every PASS sample
|
| 187 |
+
sc_ids = [g for g in scs.sc_sample if summaries[g]["status"] == "PASS"]
|
| 188 |
+
sc_meta = scs.set_index("sc_sample")
|
| 189 |
+
s_subject = np.asarray([person(s) for s in sc_meta.loc[sc_ids, "Subject"]])
|
| 190 |
+
s_label = sc_meta.loc[sc_ids, "sample_name"].to_numpy()
|
| 191 |
+
sc_sum = np.zeros((len(sc_ids), 20097))
|
| 192 |
+
sc_valid_all = np.zeros((len(sc_ids), 20097), dtype=bool)
|
| 193 |
+
sc_n = np.zeros(len(sc_ids), dtype=np.int64)
|
| 194 |
+
for i, g in enumerate(sc_ids):
|
| 195 |
+
with h5py.File(RUN / "singlecell" / g / "pseudobulk_per_published_sample.h5", "r") as f:
|
| 196 |
+
require(np.array_equal(text(f["gene_id"][:]), gene_ids), f"{g}: gene order")
|
| 197 |
+
require(len(f["sample_id"]) == 1, f"{g}: exactly one sample per library")
|
| 198 |
+
require(text(f["sample_id"][:])[0] == g, f"{g}: sample id")
|
| 199 |
+
require(f.attrs["units"] == "UMI_counts", f"{g}: units")
|
| 200 |
+
sc_sum[i] = f["qc_review_pass_cells_sum"][0]
|
| 201 |
+
sc_valid_all[i] = f["harmonization_valid"][:].astype(bool)
|
| 202 |
+
sc_n[i] = int(f["n_cells"][1, 0])
|
| 203 |
+
require(np.array_equal(sc_sum[i], np.rint(sc_sum[i])) and (sc_sum[i] >= 0).all(), f"{g}: noninteger sum")
|
| 204 |
+
require((sc_sum[i][~sc_valid_all[i]] == 0).all(), f"{g}: mass outside the measured mask")
|
| 205 |
+
srow = {g: i for i, g in enumerate(sc_ids)}
|
| 206 |
+
|
| 207 |
+
# ---------------- per-pair feature rows
|
| 208 |
+
bi = np.asarray([bcol[c] for c in pairs.bulk_column])
|
| 209 |
+
si = np.asarray([srow[g] for g in pairs.sc_sample])
|
| 210 |
+
require(np.array_equal(b_gsm[bi], pairs.bulk_gsm.to_numpy()), "bulk column -> GSM join")
|
| 211 |
+
require(np.array_equal(b_subject[bi], pairs.Subject.to_numpy()), "bulk subject join")
|
| 212 |
+
require(np.array_equal(s_subject[si], pairs.Subject.to_numpy()), "sc subject join")
|
| 213 |
+
bulk_all_rows = bulk_all[bi]
|
| 214 |
+
bulk_valid = b_valid[bi]
|
| 215 |
+
bulk_raw = np.where(bulk_valid, bulk_all_rows, np.nan) # NaN = not measured (task contract)
|
| 216 |
+
pseudo_raw_sum = sc_sum[si]
|
| 217 |
+
sc_valid = sc_valid_all[si]
|
| 218 |
+
qc_cell_counts = sc_n[si]
|
| 219 |
+
|
| 220 |
+
# ---------------- sex check (source axis; XIST is not protein-coding)
|
| 221 |
+
bsrc = np.load(RUN / "bulk/bulk_source_counts.npz")
|
| 222 |
+
bids = list(bsrc["gene_ids"])
|
| 223 |
+
bcounts = bsrc["counts"]
|
| 224 |
+
require(list(bsrc["sample_ids"]) == list(b_index), "bulk source-axis sample order")
|
| 225 |
+
bcpm = bcounts / bcounts.sum(1, keepdims=True) * 1e6
|
| 226 |
+
sex_rows = []
|
| 227 |
+
for g in sc_ids:
|
| 228 |
+
z = np.load(RUN / "singlecell" / g / "source_axis_pseudobulk.npz")
|
| 229 |
+
fid = list(z["feature_ids"])
|
| 230 |
+
tot = z["qc_pass_sum"][z["rna"]].sum()
|
| 231 |
+
rec = {"sc_sample": g}
|
| 232 |
+
for gene in SEX_GENES:
|
| 233 |
+
rec["sc_" + gene + "_cpm"] = float(z["qc_pass_sum"][fid.index(SEX_IDS[gene])] / tot * 1e6)
|
| 234 |
+
rec["sc_Ysum_cpm"] = sum(rec["sc_" + x + "_cpm"] for x in Y_GENES)
|
| 235 |
+
rec["sc_sex_call_pseudobulk"], rec["sc_sex_score"] = sex_call(rec["sc_XIST_cpm"], rec["sc_Ysum_cpm"])
|
| 236 |
+
# Per-cell detection, verbatim the Imperial ESKD rule (pooled 10x lanes carry ambient RNA of the pool-mates,
|
| 237 |
+
# which inflates the opposite-sex pseudobulk signal; 5' capture of XIST is low): fraction of retained cells
|
| 238 |
+
# with >=1 XIST UMI and with >=1 Y-gene UMI. Used only where the pseudobulk call is ambiguous.
|
| 239 |
+
sx = np.load(RUN / "singlecell" / g / "cell_sex_gene_counts.npz")
|
| 240 |
+
with h5py.File(RUN / "singlecell" / g / "canonical.h5ad", "r") as f:
|
| 241 |
+
keep = f["obs/flag_conservative_review_pass"][:].astype(bool)
|
| 242 |
+
cnt = sx["counts"][:, keep]
|
| 243 |
+
f_xist = float((cnt[0] >= 1).mean())
|
| 244 |
+
f_y = float((cnt[1:].sum(0) >= 1).mean())
|
| 245 |
+
rec["sc_frac_cells_XIST"], rec["sc_frac_cells_Y"] = f_xist, f_y
|
| 246 |
+
rec["sc_sex_call_cells"] = ("female" if f_y < 0.2 and f_xist >= 0.05 else
|
| 247 |
+
"male" if f_y >= 0.4 and f_xist < 0.2 else "ambiguous")
|
| 248 |
+
if rec["sc_sex_call_pseudobulk"] != "ambiguous":
|
| 249 |
+
rec["sc_sex_call"], rec["sc_sex_call_method"] = rec["sc_sex_call_pseudobulk"], "pseudobulk"
|
| 250 |
+
else:
|
| 251 |
+
rec["sc_sex_call"], rec["sc_sex_call_method"] = rec["sc_sex_call_cells"], "per-cell (pseudobulk ambiguous)"
|
| 252 |
+
sex_rows.append(rec)
|
| 253 |
+
sc_sex = pd.DataFrame(sex_rows).set_index("sc_sample")
|
| 254 |
+
bulk_sex_rows = []
|
| 255 |
+
for j, c in enumerate(b_index):
|
| 256 |
+
rec = {"bulk_column": c, "bulk_gsm": b_gsm[j]}
|
| 257 |
+
for gene in SEX_GENES:
|
| 258 |
+
require(gene in bids, f"{gene} not a row of the bulk table")
|
| 259 |
+
rec["bulk_" + gene + "_cpm"] = float(bcpm[j, bids.index(gene)])
|
| 260 |
+
rec["bulk_Ysum_cpm"] = sum(rec["bulk_" + x + "_cpm"] for x in Y_GENES)
|
| 261 |
+
rec["bulk_sex_call"], rec["bulk_sex_score"] = sex_call(rec["bulk_XIST_cpm"], rec["bulk_Ysum_cpm"])
|
| 262 |
+
bulk_sex_rows.append(rec)
|
| 263 |
+
bulk_sex = pd.DataFrame(bulk_sex_rows).set_index("bulk_column")
|
| 264 |
+
|
| 265 |
+
# ---------------- expression identity: every bulk column vs every sc pseudobulk (retained cells)
|
| 266 |
+
common = b_valid.all(0) & sc_valid_all.all(0) & ~chr_y
|
| 267 |
+
|
| 268 |
+
def logcpm(m: np.ndarray) -> np.ndarray:
|
| 269 |
+
x = m[:, common]
|
| 270 |
+
return np.log2(x / x.sum(1, keepdims=True) * 1e6 + 1)
|
| 271 |
+
|
| 272 |
+
lb_all, ls_all = logcpm(bulk_all), logcpm(sc_sum)
|
| 273 |
+
mean_score = 0.5 * (lb_all.mean(0) + ls_all.mean(0))
|
| 274 |
+
top = np.argsort(-mean_score, kind="mergesort")[:TOP_N]
|
| 275 |
+
rho = spearman_matrix(lb_all[bi][:, top], ls_all[:, top]) # paired bulks x all sc
|
| 276 |
+
rho_rev = spearman_matrix(ls_all[si][:, top], lb_all[:, top]) # paired sc x all bulks
|
| 277 |
+
cb = lb_all - lb_all.mean(0)
|
| 278 |
+
cs = ls_all - ls_all.mean(0)
|
| 279 |
+
rho_c = spearman_matrix(cb[bi][:, top], cs[:, top]) # modality-centred sensitivity
|
| 280 |
+
rho_c_rev = spearman_matrix(cs[si][:, top], cb[:, top])
|
| 281 |
+
expr = []
|
| 282 |
+
for r in range(n):
|
| 283 |
+
own = si[r]
|
| 284 |
+
order = np.argsort(-rho[r]); order_c = np.argsort(-rho_c[r])
|
| 285 |
+
rev = np.argsort(-rho_rev[r]); rev_c = np.argsort(-rho_c_rev[r])
|
| 286 |
+
expr.append({"sample_id": pairs.sample_id[r], "bulk_gsm": pairs.bulk_gsm[r], "sc_sample": pairs.sc_sample[r],
|
| 287 |
+
"rho_own": rho[r, own], "best_sc_sample": sc_ids[order[0]], "rho_best": rho[r, order[0]],
|
| 288 |
+
"own_rank_among_sc": int(np.flatnonzero(order == own)[0]) + 1,
|
| 289 |
+
"best_is_own": bool(order[0] == own),
|
| 290 |
+
"rho_second": rho[r, order[1]],
|
| 291 |
+
"centred_rho_own": rho_c[r, own], "centred_best_sc_sample": sc_ids[order_c[0]],
|
| 292 |
+
"centred_own_rank_among_sc": int(np.flatnonzero(order_c == own)[0]) + 1,
|
| 293 |
+
"centred_best_is_own": bool(order_c[0] == own),
|
| 294 |
+
"reverse_best_bulk": b_label[rev[0]], "reverse_own_rank_among_bulk": int(np.flatnonzero(rev == bi[r])[0]) + 1,
|
| 295 |
+
"reverse_best_is_own": bool(rev[0] == bi[r]),
|
| 296 |
+
"centred_reverse_best_bulk": b_label[rev_c[0]],
|
| 297 |
+
"centred_reverse_own_rank_among_bulk": int(np.flatnonzero(rev_c == bi[r])[0]) + 1,
|
| 298 |
+
"centred_reverse_best_is_own": bool(rev_c[0] == bi[r])})
|
| 299 |
+
expr = pd.DataFrame(expr)
|
| 300 |
+
|
| 301 |
+
# Residualised donor-identity test (unsupervised w.r.t. pairing): within each modality centre log CPM, remove
|
| 302 |
+
# the top-k sample PCs (computed on expressed genes), keep the 2,000 genes with the highest residual variance
|
| 303 |
+
# in both modalities, Pearson. Ranks are reported per sample and per subject (best sample of a subject).
|
| 304 |
+
expressed = (lb_all.mean(0) > 3) & (ls_all.mean(0) > 1)
|
| 305 |
+
ex = np.flatnonzero(expressed)
|
| 306 |
+
|
| 307 |
+
def resid(x: np.ndarray, k: int) -> np.ndarray:
|
| 308 |
+
xc = x - x.mean(0)
|
| 309 |
+
u = np.linalg.svd(xc[:, ex], full_matrices=False)[0][:, :k]
|
| 310 |
+
return xc - u @ (u.T @ xc)
|
| 311 |
+
|
| 312 |
+
IDENT.mkdir(exist_ok=True)
|
| 313 |
+
for k in RESID_K:
|
| 314 |
+
rb_, rs_ = resid(lb_all, k), resid(ls_all, k)
|
| 315 |
+
vb = np.where(expressed, rb_.var(0), -1.0); vs = np.where(expressed, rs_.var(0), -1.0)
|
| 316 |
+
sel = np.argsort(rankdata(-vb) + rankdata(-vs), kind="mergesort")[:TOP_N]
|
| 317 |
+
fw_all = pearson_matrix(rb_[:, sel], rs_[:, sel]) # all bulks x all sc
|
| 318 |
+
pd.DataFrame(fw_all, index=b_label, columns=list(sc_ids)).to_csv(IDENT / f"residual_k{k}_pearson_bulk_x_sc.csv")
|
| 319 |
+
fw = fw_all[bi]; bw = fw_all[:, si].T
|
| 320 |
+
c = {x: [] for x in ("lib_b2s", "lib_s2b", "subj_b2s", "subj_s2b", "best_sc", "best_subj_b2s",
|
| 321 |
+
"best_subj_s2b", "r_own", "r_best", "day_b2s", "day_s2b", "n_days")}
|
| 322 |
+
for r in range(n):
|
| 323 |
+
o = np.argsort(-fw[r]); o2 = np.argsort(-bw[r])
|
| 324 |
+
subj = pairs.Subject[r]
|
| 325 |
+
c["lib_b2s"].append(int(np.flatnonzero(o == si[r])[0]) + 1)
|
| 326 |
+
c["lib_s2b"].append(int(np.flatnonzero(o2 == bi[r])[0]) + 1)
|
| 327 |
+
rk, best, _ = subject_rank(fw[r], s_subject, subj); c["subj_b2s"].append(rk); c["best_subj_b2s"].append(best)
|
| 328 |
+
rk, best, _ = subject_rank(bw[r], b_subject, subj); c["subj_s2b"].append(rk); c["best_subj_s2b"].append(best)
|
| 329 |
+
c["best_sc"].append(sc_ids[o[0]]); c["r_own"].append(float(fw[r, si[r]])); c["r_best"].append(float(fw[r, o[0]]))
|
| 330 |
+
# within-subject timepoint check: among this subject's paired samples, is the own timepoint the best?
|
| 331 |
+
own_s = np.flatnonzero((s_subject == subj) & np.isin(np.arange(len(sc_ids)), si))
|
| 332 |
+
own_b = np.flatnonzero((b_subject == subj) & np.isin(np.arange(len(b_index)), bi))
|
| 333 |
+
c["day_b2s"].append(int((fw[r, own_s] > fw[r, si[r]]).sum()) + 1)
|
| 334 |
+
c["day_s2b"].append(int((bw[r, own_b] > bw[r, bi[r]]).sum()) + 1)
|
| 335 |
+
c["n_days"].append(len(own_s))
|
| 336 |
+
for key, name in (("lib_b2s", "own_rank_bulk_to_sc"), ("lib_s2b", "own_rank_sc_to_bulk"),
|
| 337 |
+
("subj_b2s", "own_subject_rank_bulk_to_sc"), ("subj_s2b", "own_subject_rank_sc_to_bulk"),
|
| 338 |
+
("best_sc", "best_sc_sample"), ("best_subj_b2s", "best_subject_bulk_to_sc"),
|
| 339 |
+
("best_subj_s2b", "best_subject_sc_to_bulk"), ("r_own", "r_own"), ("r_best", "r_best"),
|
| 340 |
+
("day_b2s", "own_day_rank_within_subject_bulk_to_sc"),
|
| 341 |
+
("day_s2b", "own_day_rank_within_subject_sc_to_bulk"), ("n_days", "subject_paired_days")):
|
| 342 |
+
expr[f"resid_k{k}_{name}"] = c[key]
|
| 343 |
+
|
| 344 |
+
# Timepoint check on disease-state signal (centred, NOT residualised): within the subject's paired rows only.
|
| 345 |
+
vb = cb.var(0); vs = cs.var(0)
|
| 346 |
+
selc = np.argsort(rankdata(-np.where(expressed, vb, -1)) + rankdata(-np.where(expressed, vs, -1)), kind="mergesort")[:TOP_N]
|
| 347 |
+
cfw = pearson_matrix(cb[:, selc], cs[:, selc])
|
| 348 |
+
dd1, dd2 = [], []
|
| 349 |
+
for r in range(n):
|
| 350 |
+
subj = pairs.Subject[r]
|
| 351 |
+
rows_subj = np.flatnonzero(pairs.Subject.to_numpy() == subj)
|
| 352 |
+
dd1.append(int((cfw[bi[r], si[rows_subj]] > cfw[bi[r], si[r]]).sum()) + 1)
|
| 353 |
+
dd2.append(int((cfw[bi[rows_subj], si[r]] > cfw[bi[r], si[r]]).sum()) + 1)
|
| 354 |
+
expr["centred_own_day_rank_within_subject_bulk_to_sc"] = dd1
|
| 355 |
+
expr["centred_own_day_rank_within_subject_sc_to_bulk"] = dd2
|
| 356 |
+
|
| 357 |
+
# Interferon-stimulated-gene score (informational): mean log2(CPM+1) of a fixed ISG set on the canonical axis.
|
| 358 |
+
sym = canonical.gene_symbol.astype(str).to_numpy()
|
| 359 |
+
isg_idx = np.flatnonzero(np.isin(sym, ISG_GENES))
|
| 360 |
+
require(len(isg_idx) == len(ISG_GENES), "ISG genes missing from the canonical axis")
|
| 361 |
+
require(bool(b_valid[:, isg_idx].all() and sc_valid_all[:, isg_idx].all()), "ISG genes not measured everywhere")
|
| 362 |
+
isg_b = np.log2(bulk_all[:, isg_idx] / bulk_all.sum(1, keepdims=True) * 1e6 + 1).mean(1)
|
| 363 |
+
isg_s = np.log2(sc_sum[:, isg_idx] / sc_sum.sum(1, keepdims=True) * 1e6 + 1).mean(1)
|
| 364 |
+
expr["isg_score_bulk"] = isg_b[bi]
|
| 365 |
+
expr["isg_score_sc"] = isg_s[si]
|
| 366 |
+
peak_b, peak_s = {}, {}
|
| 367 |
+
for subj in pairs.Subject.unique():
|
| 368 |
+
rows_subj = np.flatnonzero(pairs.Subject.to_numpy() == subj)
|
| 369 |
+
peak_b[subj] = pairs.Timepoint[rows_subj[np.argmax(isg_b[bi[rows_subj]])]]
|
| 370 |
+
peak_s[subj] = pairs.Timepoint[rows_subj[np.argmax(isg_s[si[rows_subj]])]]
|
| 371 |
+
expr["isg_peak_day_bulk"] = [peak_b[s] for s in pairs.Subject]
|
| 372 |
+
expr["isg_peak_day_sc"] = [peak_s[s] for s in pairs.Subject]
|
| 373 |
+
|
| 374 |
+
# ---------------- cells on the 6k panel (two passes: per-sample temp files, then one CSR)
|
| 375 |
+
cell_types = pd.read_parquet(RUN / "pairing/sc_cell_obs.parquet",
|
| 376 |
+
columns=["cell", "sample_id", "selected", "WCTcoursecelltype", "WCTmergedcelltype"])
|
| 377 |
+
cell_types = cell_types[cell_types.selected].set_index("cell")
|
| 378 |
+
TMP.mkdir(exist_ok=True)
|
| 379 |
+
nnz_per, obs_blocks = [], []
|
| 380 |
+
for r in range(n):
|
| 381 |
+
g = pairs.sc_sample[r]
|
| 382 |
+
h5 = RUN / "singlecell" / g / "canonical.h5ad"
|
| 383 |
+
with h5py.File(h5, "r") as f:
|
| 384 |
+
X = f["X"]
|
| 385 |
+
ncell = len(X["indptr"]) - 1
|
| 386 |
+
full = sp.csr_matrix((X["data"][:], X["indices"][:], X["indptr"][:]), shape=(ncell, 20097))
|
| 387 |
+
o = f["obs"]
|
| 388 |
+
keep = o["flag_conservative_review_pass"][:].astype(bool)
|
| 389 |
+
obs = pd.DataFrame({"cell_index": np.arange(ncell), "barcode": text(o["_index"][:]),
|
| 390 |
+
"raw_gex_total": o["cell_total"][:], "n_genes": o["cell_detected"][:],
|
| 391 |
+
"mito_pct": o["cell_mito_percent"][:],
|
| 392 |
+
"flag_low_total_mad": o["flag_low_total_mad"][:].astype(bool),
|
| 393 |
+
"flag_low_genes_mad": o["flag_low_genes_mad"][:].astype(bool),
|
| 394 |
+
"flag_high_mito_mad": o["flag_high_mito_mad"][:].astype(bool),
|
| 395 |
+
"flag_high_total_review_only": o["flag_high_total_review_only"][:].astype(bool)})
|
| 396 |
+
require(np.array_equal(text(o["sample_id"][:]), np.full(ncell, g)), f"{g}: sample id")
|
| 397 |
+
require(int(keep.sum()) == qc_cell_counts[r], f"{g}: retained-cell count differs from pseudobulk file")
|
| 398 |
+
kept = full[np.flatnonzero(keep)]
|
| 399 |
+
require(np.array_equal(np.asarray(kept.sum(0)).ravel(), pseudo_raw_sum[r]), f"{g}: canonical sum differs")
|
| 400 |
+
sub = kept[:, positions].tocsr()
|
| 401 |
+
sub.sort_indices()
|
| 402 |
+
require(np.array_equal(sub.data, np.rint(sub.data)) and (sub.data >= 0).all() and
|
| 403 |
+
(sub.data.max(initial=0) < 2**31), f"{g}: non-integer or overflowing counts")
|
| 404 |
+
require(np.array_equal(np.asarray(sub.sum(0)).ravel(), pseudo_raw_sum[r, positions]), f"{g}: panel sum")
|
| 405 |
+
np.save(TMP / f"{r:03d}_data.npy", sub.data.astype(np.int32))
|
| 406 |
+
np.save(TMP / f"{r:03d}_indices.npy", sub.indices.astype(np.int32))
|
| 407 |
+
np.save(TMP / f"{r:03d}_indptr.npy", sub.indptr.astype(np.int64))
|
| 408 |
+
sx = np.load(RUN / "singlecell" / g / "cell_sex_gene_counts.npz")
|
| 409 |
+
require(list(sx["genes"]) == SEX_GENES and sx["found"].all(), f"{g}: sex genes")
|
| 410 |
+
obs = obs[keep].reset_index(drop=True)
|
| 411 |
+
obs["cell_total_canonical"] = np.asarray(kept.sum(1)).ravel()
|
| 412 |
+
obs["lib_panel"] = np.asarray(sub.sum(1)).ravel()
|
| 413 |
+
for k, gene in enumerate(SEX_GENES):
|
| 414 |
+
obs[("xist" if gene == "XIST" else "y_" + gene)] = sx["counts"][k][keep]
|
| 415 |
+
obs["y_sum"] = obs[["y_" + x for x in Y_GENES]].sum(1)
|
| 416 |
+
obs.insert(2, "library_id", g)
|
| 417 |
+
obs.insert(3, "sample_id", pairs.sample_id[r])
|
| 418 |
+
obs.insert(4, "donor_id", pairs.Subject[r])
|
| 419 |
+
obs.insert(5, "group", pairs.Class[r])
|
| 420 |
+
ct = cell_types.reindex(obs.barcode)
|
| 421 |
+
require(ct.sample_id.eq(g).all(), f"{g}: author cell-type join")
|
| 422 |
+
obs["author_cell_type"] = ct.WCTcoursecelltype.to_numpy().astype(str)
|
| 423 |
+
obs["row_sample"] = np.int32(r)
|
| 424 |
+
obs["author_cell_type_fine"] = ct.WCTmergedcelltype.to_numpy().astype(str)
|
| 425 |
+
obs_blocks.append(obs)
|
| 426 |
+
nnz_per.append(sub.nnz)
|
| 427 |
+
print(f"{g} {pairs.sample_id[r]}: {sub.shape[0]} cells, nnz {sub.nnz}", flush=True)
|
| 428 |
+
del full, kept, sub
|
| 429 |
+
total_nnz = int(sum(nnz_per))
|
| 430 |
+
total_cells = int(qc_cell_counts.sum())
|
| 431 |
+
data = np.lib.format.open_memmap(TMP / "all_data.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
|
| 432 |
+
indices = np.lib.format.open_memmap(TMP / "all_indices.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
|
| 433 |
+
indptr = np.empty(total_cells + 1, dtype=np.int64)
|
| 434 |
+
indptr[0] = 0
|
| 435 |
+
at, cell_at = 0, 0
|
| 436 |
+
for r in range(n):
|
| 437 |
+
d = np.load(TMP / f"{r:03d}_data.npy"); ix = np.load(TMP / f"{r:03d}_indices.npy")
|
| 438 |
+
ip = np.load(TMP / f"{r:03d}_indptr.npy")
|
| 439 |
+
data[at:at + len(d)] = d
|
| 440 |
+
indices[at:at + len(d)] = ix
|
| 441 |
+
indptr[cell_at + 1:cell_at + len(ip)] = ip[1:] + at
|
| 442 |
+
at += len(d); cell_at += len(ip) - 1
|
| 443 |
+
require(at == total_nnz and cell_at == total_cells, "assembly size")
|
| 444 |
+
cobs = pd.concat(obs_blocks, ignore_index=True)
|
| 445 |
+
row_sample = cobs.row_sample.to_numpy(np.int32)
|
| 446 |
+
require(np.all(np.diff(row_sample) >= 0), "cells must be grouped by row")
|
| 447 |
+
require(np.array_equal(np.bincount(row_sample, minlength=n), qc_cell_counts), "assembled cell counts")
|
| 448 |
+
starts = np.concatenate([[0], np.cumsum(qc_cell_counts)])
|
| 449 |
+
for r in range(n):
|
| 450 |
+
a, b = indptr[starts[r]], indptr[starts[r + 1]]
|
| 451 |
+
s_r = np.bincount(indices[a:b], weights=data[a:b].astype(np.float64), minlength=len(positions))
|
| 452 |
+
require(np.array_equal(s_r, pseudo_raw_sum[r, positions]), f"row {r}: assembled panel sum differs")
|
| 453 |
+
require(np.all(np.diff(indptr) >= 0) and indptr[-1] == total_nnz, "indptr")
|
| 454 |
+
|
| 455 |
+
# ---------------- write
|
| 456 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 457 |
+
meta_arrays = {
|
| 458 |
+
"gene_ids": gene_ids, "sample_ids": pairs.sample_id.to_numpy().astype(str),
|
| 459 |
+
"donor_ids": pairs.Subject.to_numpy().astype(str), "groups": pairs.Class.to_numpy().astype(str),
|
| 460 |
+
"timepoints": pairs.Timepoint.to_numpy().astype(str),
|
| 461 |
+
"bulk_raw": bulk_raw.astype(np.float64), "pseudo_raw_sum": pseudo_raw_sum.astype(np.float64),
|
| 462 |
+
"bulk_valid": bulk_valid, "sc_valid": sc_valid, "pair_valid": bulk_valid & sc_valid,
|
| 463 |
+
"qc_cell_counts": qc_cell_counts.astype(np.int64),
|
| 464 |
+
"bulk_gsm": pairs.bulk_gsm.to_numpy().astype(str), "bulk_count_column": pairs.bulk_column.to_numpy().astype(str),
|
| 465 |
+
"bulk_title": pairs.bulk_title.to_numpy().astype(str),
|
| 466 |
+
"sc_sample": pairs.sc_sample.to_numpy().astype(str), "id_match": pairs.id_match.to_numpy().astype(str),
|
| 467 |
+
"batch": pairs.Batch.to_numpy().astype(str),
|
| 468 |
+
"geo_bulk_timepoint": pairs.geo_timepoint_characteristic.to_numpy().astype(str),
|
| 469 |
+
"severity": np.where(pairs.Class == "HC", "HC", pairs.severity).astype(str),
|
| 470 |
+
"outcome": np.where(pairs.Class == "HC", "HC", pairs.outcome).astype(str),
|
| 471 |
+
"status_meta": pairs.Status.to_numpy().astype(str),
|
| 472 |
+
"days_since_onset": np.asarray([fnum(v) for v in pairs.days_since_onset], dtype=np.float64),
|
| 473 |
+
"days_since_hospitalized": np.asarray([fnum(v) for v in pairs.days_since_hospitalized], dtype=np.float64),
|
| 474 |
+
"ever_admitted_to_icu": pairs.ever_admitted_to_icu.to_numpy().astype(str),
|
| 475 |
+
"ward": pairs.Ward.to_numpy().astype(str),
|
| 476 |
+
"sex_meta": pairs.Gender.to_numpy().astype(str),
|
| 477 |
+
"age_meta": np.asarray([fnum(v) for v in pairs.Age], dtype=np.float64),
|
| 478 |
+
"below_200_cells": qc_cell_counts < MIN_CELLS,
|
| 479 |
+
}
|
| 480 |
+
panel_gene_ids = gene_ids[positions]
|
| 481 |
+
tmp = OUT / "cells_panel6k.npz.tmp"
|
| 482 |
+
with open(tmp, "wb") as h:
|
| 483 |
+
np.savez_compressed(h, data=data, indices=indices, indptr=indptr,
|
| 484 |
+
shape=np.array([total_cells, len(positions)], dtype=np.int64), row_sample=row_sample,
|
| 485 |
+
panel_gene_ids=panel_gene_ids, panel_measured=sc_valid[:, positions])
|
| 486 |
+
os.replace(tmp, OUT / "cells_panel6k.npz")
|
| 487 |
+
cobs.to_parquet(OUT / "cells_obs.parquet", index=False)
|
| 488 |
+
pd.DataFrame({"row": np.arange(n), "sample_id": meta_arrays["sample_ids"], "donor_id": meta_arrays["donor_ids"],
|
| 489 |
+
"group": meta_arrays["groups"], "n_cells": qc_cell_counts}).to_csv(OUT / "samples.csv", index=False)
|
| 490 |
+
|
| 491 |
+
# pairs.csv with identity results
|
| 492 |
+
p = pairs[["sample_id", "bulk_gsm", "sc_sample", "Subject", "bulk_title", "bulk_column", "id_match", "Class",
|
| 493 |
+
"Timepoint", "Batch", "geo_timepoint_characteristic", "severity", "outcome", "Status", "days_since_onset",
|
| 494 |
+
"days_since_hospitalized", "Gender", "Age"]].copy()
|
| 495 |
+
p = p.rename(columns={"Subject": "donor_id", "bulk_column": "bulk_count_column", "Class": "group",
|
| 496 |
+
"Timepoint": "timepoint", "Batch": "batch", "geo_timepoint_characteristic": "geo_bulk_timepoint",
|
| 497 |
+
"Status": "status_meta", "Gender": "sex_meta", "Age": "age_meta"})
|
| 498 |
+
p["severity"] = meta_arrays["severity"]
|
| 499 |
+
p["outcome"] = meta_arrays["outcome"]
|
| 500 |
+
p.insert(4, "row", np.arange(n))
|
| 501 |
+
p["n_cells_object_sample"] = pairs.n_cells_object.astype(int).to_numpy()
|
| 502 |
+
p["n_sorted_dropped"] = pairs.n_sorted_dropped.astype(int).to_numpy()
|
| 503 |
+
p["n_unsorted"] = pairs.n_unsorted.astype(int).to_numpy()
|
| 504 |
+
p["n_hto_doublet_dropped"] = pairs.n_unsorted_hto_doublet.astype(int).to_numpy()
|
| 505 |
+
p["n_hto_negative_dropped"] = pairs.n_unsorted_hto_negative.astype(int).to_numpy()
|
| 506 |
+
p["n_cells_library"] = [summaries[g]["n_cells"] for g in p.sc_sample]
|
| 507 |
+
p["n_cells_retained"] = qc_cell_counts
|
| 508 |
+
p["below_200_cells"] = meta_arrays["below_200_cells"]
|
| 509 |
+
p["bulk_assigned_counts"] = bcounts[bi].sum(1)
|
| 510 |
+
p["bulk_canonical_counts"] = bulk_all_rows.sum(1)
|
| 511 |
+
p["sc_retained_umis_canonical"] = pseudo_raw_sum.sum(1)
|
| 512 |
+
for c in ("bulk_XIST_cpm", "bulk_Ysum_cpm", "bulk_sex_score", "bulk_sex_call"):
|
| 513 |
+
p[c] = bulk_sex.loc[p.bulk_count_column, c].to_numpy()
|
| 514 |
+
for c in ("sc_XIST_cpm", "sc_Ysum_cpm", "sc_sex_score", "sc_sex_call_pseudobulk", "sc_frac_cells_XIST",
|
| 515 |
+
"sc_frac_cells_Y", "sc_sex_call_cells", "sc_sex_call_method", "sc_sex_call"):
|
| 516 |
+
p[c] = sc_sex.loc[p.sc_sample, c].to_numpy()
|
| 517 |
+
meta_sex = p.sex_meta.str.lower()
|
| 518 |
+
p["sex_concordant"] = (p.bulk_sex_call == p.sc_sex_call) & (p.sc_sex_call == meta_sex)
|
| 519 |
+
p["bulk_possible_mixture"] = ((p.bulk_sex_call == "female") & (p.bulk_Ysum_cpm > 20)) | \
|
| 520 |
+
((p.bulk_sex_call == "male") & (p.bulk_XIST_cpm > 50))
|
| 521 |
+
e = expr.set_index("bulk_gsm")
|
| 522 |
+
for c in ("rho_own", "rho_best", "own_rank_among_sc", "best_is_own", "best_sc_sample", "centred_own_rank_among_sc",
|
| 523 |
+
"centred_best_is_own", "reverse_own_rank_among_bulk", "reverse_best_is_own",
|
| 524 |
+
"centred_own_day_rank_within_subject_bulk_to_sc", "centred_own_day_rank_within_subject_sc_to_bulk",
|
| 525 |
+
"isg_score_bulk", "isg_score_sc", "isg_peak_day_bulk", "isg_peak_day_sc"):
|
| 526 |
+
p["expr_" + c] = e.loc[p.bulk_gsm, c].to_numpy()
|
| 527 |
+
for k in RESID_K:
|
| 528 |
+
for c in ("own_rank_bulk_to_sc", "own_rank_sc_to_bulk", "own_subject_rank_bulk_to_sc",
|
| 529 |
+
"own_subject_rank_sc_to_bulk", "best_subject_bulk_to_sc", "best_subject_sc_to_bulk",
|
| 530 |
+
"best_sc_sample", "r_own", "r_best", "own_day_rank_within_subject_bulk_to_sc",
|
| 531 |
+
"own_day_rank_within_subject_sc_to_bulk", "subject_paired_days"):
|
| 532 |
+
p[f"expr_resid_k{k}_{c}"] = e.loc[p.bulk_gsm, f"resid_k{k}_{c}"].to_numpy()
|
| 533 |
+
kp = K_PRIMARY
|
| 534 |
+
n_sc_subj, n_b_subj = len(set(s_subject)), len(set(b_subject))
|
| 535 |
+
|
| 536 |
+
def day_ranks(row) -> tuple[int, int, int, int]:
|
| 537 |
+
return (row[f"expr_resid_k{kp}_own_day_rank_within_subject_bulk_to_sc"],
|
| 538 |
+
row[f"expr_resid_k{kp}_own_day_rank_within_subject_sc_to_bulk"],
|
| 539 |
+
row.expr_centred_own_day_rank_within_subject_bulk_to_sc,
|
| 540 |
+
row.expr_centred_own_day_rank_within_subject_sc_to_bulk)
|
| 541 |
+
|
| 542 |
+
def verdict(row) -> str:
|
| 543 |
+
"""pass: sex concordant AND (residualised, k=5) own SUBJECT ranked 1st in one direction and within the top 3
|
| 544 |
+
subjects in the other AND no timepoint failure. fail: sex discordant, or own subject ranked below 3rd in both
|
| 545 |
+
directions, or a timepoint failure = within the subject's paired rows another timepoint beats the own one in
|
| 546 |
+
BOTH directions on BOTH the residualised (k=5) and the centred expression test. Otherwise borderline."""
|
| 547 |
+
r1 = row[f"expr_resid_k{kp}_own_subject_rank_bulk_to_sc"]
|
| 548 |
+
r2 = row[f"expr_resid_k{kp}_own_subject_rank_sc_to_bulk"]
|
| 549 |
+
d1, d2, c1, c2 = day_ranks(row)
|
| 550 |
+
issues = []
|
| 551 |
+
if not row.sex_concordant:
|
| 552 |
+
issues.append(f"sex bulk={row.bulk_sex_call} sc={row.sc_sex_call} meta={row.sex_meta.lower()}")
|
| 553 |
+
if min(r1, r2) > SUBJ_TOP:
|
| 554 |
+
issues.append(f"expression: own subject rank {r1} (bulk->{n_sc_subj} sc subjects) and {r2} "
|
| 555 |
+
f"(sc->{n_b_subj} bulk subjects); bulk best subject = "
|
| 556 |
+
f"{row[f'expr_resid_k{kp}_best_subject_bulk_to_sc']}")
|
| 557 |
+
if min(d1, d2, c1, c2) > 1:
|
| 558 |
+
issues.append(f"timepoint: within subject {row.donor_id}, own timepoint {row.timepoint} ranks {d1}/{d2} "
|
| 559 |
+
f"(residualised k={kp}, bulk->sc/sc->bulk) and {c1}/{c2} (centred) among "
|
| 560 |
+
f"{row[f'expr_resid_k{kp}_subject_paired_days']} paired timepoints; ISG peak bulk="
|
| 561 |
+
f"{row.expr_isg_peak_day_bulk} sc={row.expr_isg_peak_day_sc}")
|
| 562 |
+
if issues:
|
| 563 |
+
return "fail: " + "; ".join(issues)
|
| 564 |
+
if min(r1, r2) == 1 and max(r1, r2) <= SUBJ_TOP:
|
| 565 |
+
return "pass"
|
| 566 |
+
return f"borderline: own subject rank {r1} (bulk->sc) and {r2} (sc->bulk)"
|
| 567 |
+
p["identity_check"] = p.apply(verdict, axis=1)
|
| 568 |
+
p["identity_pass"] = p.identity_check == "pass"
|
| 569 |
+
notes = []
|
| 570 |
+
for _, row in p.iterrows():
|
| 571 |
+
nt = []
|
| 572 |
+
if row.bulk_possible_mixture:
|
| 573 |
+
nt.append("bulk has opposite-sex signal (possible minor admixture)")
|
| 574 |
+
if row.sc_sex_call_method != "pseudobulk":
|
| 575 |
+
nt.append(f"sc sex from per-cell detection (pseudobulk ambiguous: ambient pool-mate RNA / low 5' XIST "
|
| 576 |
+
f"capture; {row.sc_frac_cells_Y:.3f} of cells with Y UMIs, {row.sc_frac_cells_XIST:.3f} with XIST)")
|
| 577 |
+
if row.bulk_sex_call == row.sc_sex_call != row.sex_meta.lower():
|
| 578 |
+
nt.append(f"bulk and sc agree ({row.bulk_sex_call}) but the author metadata says {row.sex_meta}; the sc cells "
|
| 579 |
+
"were assigned by demuxlet with SNPs called from this subject's bulk RNA-seq, so the metadata sex "
|
| 580 |
+
"is the likely error")
|
| 581 |
+
d1, d2, c1, c2 = day_ranks(row)
|
| 582 |
+
if max(d1, d2, c1, c2) > 1 and min(d1, d2, c1, c2) == 1:
|
| 583 |
+
nt.append(f"within subject, another timepoint beats the own one in some tests (residualised {d1}/{d2}, "
|
| 584 |
+
f"centred {c1}/{c2}); not a timepoint failure")
|
| 585 |
+
if row.expr_isg_peak_day_bulk != row.expr_isg_peak_day_sc:
|
| 586 |
+
nt.append(f"subject ISG peak timepoint differs between assays (bulk {row.expr_isg_peak_day_bulk}, "
|
| 587 |
+
f"sc {row.expr_isg_peak_day_sc})")
|
| 588 |
+
if row.id_match != "exact_subject_timepoint":
|
| 589 |
+
nt.append(row.id_match)
|
| 590 |
+
if row.below_200_cells:
|
| 591 |
+
nt.append(f"only {row.n_cells_retained} retained cells (< {MIN_CELLS}; excluded by prepare_dataset)")
|
| 592 |
+
if row.bulk_assigned_counts < 2e6:
|
| 593 |
+
nt.append(f"low-depth bulk ({int(row.bulk_assigned_counts):,} assigned reads)")
|
| 594 |
+
notes.append("; ".join(nt))
|
| 595 |
+
p["identity_notes"] = notes
|
| 596 |
+
p.to_csv(OUT / "pairs.csv", index=False)
|
| 597 |
+
require(np.array_equal(p.bulk_gsm.to_numpy(), meta_arrays["bulk_gsm"]), "pairs/features row order")
|
| 598 |
+
meta_arrays["identity_pass"] = p.identity_pass.to_numpy().astype(bool)
|
| 599 |
+
meta_arrays["identity_check"] = p.identity_check.to_numpy().astype(str)
|
| 600 |
+
meta_arrays["sex_bulk_expr"] = p.bulk_sex_call.to_numpy().astype(str)
|
| 601 |
+
meta_arrays["sex_sc_expr"] = p.sc_sex_call.to_numpy().astype(str)
|
| 602 |
+
tmp = OUT / "features.npz.tmp"
|
| 603 |
+
with open(tmp, "wb") as h:
|
| 604 |
+
np.savez_compressed(h, **meta_arrays)
|
| 605 |
+
os.replace(tmp, OUT / "features.npz")
|
| 606 |
+
bsex_out = bulk_sex.copy()
|
| 607 |
+
bsex_out["subject"] = cmeta.loc[b_index, "subject"].to_numpy()
|
| 608 |
+
bsex_out["kind"] = cmeta.loc[b_index, "kind"].to_numpy()
|
| 609 |
+
sex_by_subject = scs.drop_duplicates("Subject").set_index("Subject").Gender
|
| 610 |
+
bsex_out["meta_sex"] = [sex_by_subject.get(s, "") for s in bsex_out.subject]
|
| 611 |
+
bsex_out["paired"] = bsex_out.index.isin(set(p.bulk_count_column))
|
| 612 |
+
bsex_out.to_csv(OUT / "identity_sex_bulk_all.csv")
|
| 613 |
+
sc_sex.join(scs.set_index("sc_sample")[["sample_name", "Subject", "Gender", "kind"]]).assign(
|
| 614 |
+
paired=lambda d: d.index.isin(set(p.sc_sample))).to_csv(OUT / "identity_sex_sc_all.csv")
|
| 615 |
+
expr.to_csv(OUT / "identity_expression.csv", index=False)
|
| 616 |
+
|
| 617 |
+
# ---------------- manifest
|
| 618 |
+
unmatched_sc = scs[~scs.sc_sample.isin(set(p.sc_sample))]
|
| 619 |
+
sc_un = pd.read_csv(RUN / "pairing/sc_without_bulk.csv", dtype=str, keep_default_na=False)
|
| 620 |
+
unmatched_cols = cols[cols.paired != "True"][["bulk_column", "bulk_gsm", "kind", "unpaired_reason"]]
|
| 621 |
+
rk = f"expr_resid_k{kp}"
|
| 622 |
+
multi = p[p[f"{rk}_subject_paired_days"] > 1]
|
| 623 |
+
checks = {
|
| 624 |
+
"gene_positions_sha256_ok": True,
|
| 625 |
+
"panel_gene_ids_match_selected_genes_csv": True,
|
| 626 |
+
"panel_gene_ids_match_giroux2022_cells_panel6k": True,
|
| 627 |
+
"bulk_integer_nonnegative_inside_mask": True,
|
| 628 |
+
"bulk_raw_nan_exactly_outside_bulk_valid": bool(np.array_equal(np.isnan(bulk_raw), ~bulk_valid)),
|
| 629 |
+
"pseudo_raw_sum_equals_sum_of_retained_cells_full_axis": True,
|
| 630 |
+
"cells_panel_sums_equal_pseudo_raw_sum_positions_exactly": True,
|
| 631 |
+
"cells_per_row_equal_qc_cell_counts": True,
|
| 632 |
+
"no_sc_mass_outside_sc_valid": True,
|
| 633 |
+
"one_sample_id_per_library": True,
|
| 634 |
+
"sc_cells_are_unsorted_hto_singlet_demuxlet_singlet": True,
|
| 635 |
+
"sex_concordant_pairs": f"{int(p.sex_concordant.sum())}/{n}",
|
| 636 |
+
"expression_best_match_is_own_pair": f"{int(p.expr_best_is_own.sum())}/{n}",
|
| 637 |
+
"expression_best_match_is_own_pair_centred": f"{int(p.expr_centred_best_is_own.sum())}/{n}",
|
| 638 |
+
"expression_reverse_best_match_is_own_pair": f"{int(p.expr_reverse_best_is_own.sum())}/{n}",
|
| 639 |
+
**{f"expression_residualised_k{k}_own_subject_top1_bulk_to_sc": f"{int((p[f'expr_resid_k{k}_own_subject_rank_bulk_to_sc'] == 1).sum())}/{n}" for k in RESID_K},
|
| 640 |
+
**{f"expression_residualised_k{k}_own_subject_top1_sc_to_bulk": f"{int((p[f'expr_resid_k{k}_own_subject_rank_sc_to_bulk'] == 1).sum())}/{n}" for k in RESID_K},
|
| 641 |
+
**{f"expression_residualised_k{k}_own_library_top1_bulk_to_sc": f"{int((p[f'expr_resid_k{k}_own_rank_bulk_to_sc'] == 1).sum())}/{n}" for k in RESID_K},
|
| 642 |
+
f"expression_residualised_k{kp}_own_timepoint_best_within_subject_bulk_to_sc_multi_timepoint_rows": f"{int((multi[f'{rk}_own_day_rank_within_subject_bulk_to_sc'] == 1).sum())}/{len(multi)}",
|
| 643 |
+
f"expression_residualised_k{kp}_own_timepoint_best_within_subject_sc_to_bulk_multi_timepoint_rows": f"{int((multi[f'{rk}_own_day_rank_within_subject_sc_to_bulk'] == 1).sum())}/{len(multi)}",
|
| 644 |
+
"expression_centred_own_timepoint_best_within_subject_bulk_to_sc_multi_timepoint_rows": f"{int((multi.expr_centred_own_day_rank_within_subject_bulk_to_sc == 1).sum())}/{len(multi)}",
|
| 645 |
+
"expression_centred_own_timepoint_best_within_subject_sc_to_bulk_multi_timepoint_rows": f"{int((multi.expr_centred_own_day_rank_within_subject_sc_to_bulk == 1).sum())}/{len(multi)}",
|
| 646 |
+
"isg_peak_timepoint_same_in_both_assays_multi_timepoint_subjects": f"{int((multi.drop_duplicates('donor_id').expr_isg_peak_day_bulk == multi.drop_duplicates('donor_id').expr_isg_peak_day_sc).sum())}/{multi.donor_id.nunique()}",
|
| 647 |
+
"identity_check_pass": f"{int((p.identity_check == 'pass').sum())}/{n}",
|
| 648 |
+
"identity_check_fail": p[p.identity_check.str.startswith('fail')].sample_id.tolist(),
|
| 649 |
+
"identity_check_borderline": p[p.identity_check.str.startswith('borderline')].sample_id.tolist(),
|
| 650 |
+
"rows_below_200_cells": p[p.below_200_cells].sample_id.tolist(),
|
| 651 |
+
"usable_rows_identity_pass_and_ge_200_cells": int((p.identity_pass & ~p.below_200_cells).sum()),
|
| 652 |
+
}
|
| 653 |
+
manifest = {
|
| 654 |
+
"schema": "liu2021_paired_ft_v1",
|
| 655 |
+
"written_utc": datetime.now(timezone.utc).isoformat(), "started_utc": t0.isoformat(),
|
| 656 |
+
"study": ("Liu C, Martins AJ, Lau WW, et al. Time-resolved systems immunology reveals a late juncture linked to "
|
| 657 |
+
"fatal COVID-19. Cell 2021;184:1836-1857 (doi 10.1016/j.cell.2021.02.018; PMID 33713619); GEO GSE161918 "
|
| 658 |
+
"(bulk RNA-seq and CITE-seq in one series)"),
|
| 659 |
+
"use": "extra TRAINING cohort only (its single cells are in the model's pretraining corpus); never a test cohort",
|
| 660 |
+
"bulk_material": "PBMC (GEO source 'Peripheral Blood Mononuclear Cells', 'Unsorted'; 100,000 cells per sample)",
|
| 661 |
+
"rows": n, "subjects": int(pairs.Subject.nunique()), "row_order": "bulk GSM ascending",
|
| 662 |
+
"pairs_by_group": p.group.value_counts().to_dict(),
|
| 663 |
+
"pairs_by_timepoint": p.timepoint.value_counts().to_dict(),
|
| 664 |
+
"pairs_by_batch": p.batch.value_counts().to_dict(),
|
| 665 |
+
"pairs_by_subject": p.groupby("donor_id").timepoint.apply(lambda s: ",".join(s)).to_dict(),
|
| 666 |
+
"pairs_by_id_match": p.id_match.value_counts().to_dict(),
|
| 667 |
+
"cells": {"n_cells": total_cells, "nnz": total_nnz, "per_row_min": int(qc_cell_counts.min()),
|
| 668 |
+
"per_row_median": float(np.median(qc_cell_counts)), "per_row_max": int(qc_cell_counts.max()),
|
| 669 |
+
"median_umi_per_cell_canonical": float(np.median(cobs.cell_total_canonical)),
|
| 670 |
+
"median_umi_per_cell_source": float(np.median(cobs.raw_gex_total))},
|
| 671 |
+
"cell_selection": ("author Seurat object cells with Sorted == 'N' (unsorted fraction), HTO_classification.global "
|
| 672 |
+
"== 'Singlet' and DROPLET.TYPE == 'SNG'; then flag_conservative_review_pass"),
|
| 673 |
+
"retained_cells_rule": "flag_conservative_review_pass = genes>=200 & UMIs>=500 & mito<=20% (qc_core, ImMicro definition); MAD flags are review-only columns",
|
| 674 |
+
"features_semantics": {
|
| 675 |
+
"bulk_raw": "author htseq-count raw gene counts (STAR / UCSC hg19) mapped by gene symbol to the canonical axis; NaN where bulk_valid is False (task contract; ImMicro also uses NaN; Giroux/Ye/Imperial store 0); many-to-one symbol groups summed (bundle policy for verified integer counts)",
|
| 676 |
+
"pseudo_raw_sum": "sum of retained cells' UMI counts on the canonical axis; storage 0 where sc_valid is False",
|
| 677 |
+
"bulk_valid": "harmonization_valid from qc_bulk.harmonize (symbol in the author table maps uniquely to the canonical gene)",
|
| 678 |
+
"sc_valid": "harmonization_valid from qc_singlecell.canonical_export (gene in the hg19-1.2.0 10x features table, mapped by Ensembl ID)",
|
| 679 |
+
"pair_valid": "bulk_valid & sc_valid",
|
| 680 |
+
"sample_ids": "<subject>_<timepoint>, e.g. HGR0000083_T0 or SHD1_HC (= author sample_name)",
|
| 681 |
+
"donor_ids": "author Subject; a COVID-19 subject has 1-4 rows (timepoints)",
|
| 682 |
+
"timepoints": "author timepoint label (T0, T1, T2, T3; HC for healthy controls), string",
|
| 683 |
+
"groups": "author Class: COVID or HC",
|
| 684 |
+
"extra_keys": ("bulk_gsm, bulk_count_column, bulk_title, sc_sample (author sample_id = batch_subject_timepoint), "
|
| 685 |
+
"id_match, batch, geo_bulk_timepoint (GEO characteristic of the bulk GSM), severity (author: "
|
| 686 |
+
"Moderate/Severe/Critical; HC), outcome (author 'outcome': alive/deceased; HC), status_meta "
|
| 687 |
+
"(author HTO-metadata 'Status': Alive/Deceased/na), days_since_onset, days_since_hospitalized "
|
| 688 |
+
"(float, NaN when not given), ever_admitted_to_icu, ward, sex_meta, age_meta, below_200_cells, "
|
| 689 |
+
"identity_pass, identity_check, sex_bulk_expr, sex_sc_expr")},
|
| 690 |
+
"identity": {"sex_rule": ("CPM on the source axis (bulk: all 55,765 author-table genes; sc: retained cells, all 32,738 RNA features); "
|
| 691 |
+
"score=log2(XIST+1)-log2(Ysum+1), Ysum = RPS4Y1+DDX3Y+UTY+KDM5D in both; female>2, male<-2, else ambiguous (the Ye 2026 rule). "
|
| 692 |
+
"sc only, verbatim the Imperial ESKD rule: where the pseudobulk call is ambiguous, the call falls back to per-cell detection "
|
| 693 |
+
"(female if <20 % of retained cells have a Y-gene UMI and >=5 % have an XIST UMI; male if >=40 % have a Y-gene UMI and "
|
| 694 |
+
"<20 % an XIST UMI), because pooled 10x lanes carry the pool-mates' ambient RNA and 5' capture of XIST is low. "
|
| 695 |
+
"Concordant = bulk call = sc call = author metadata Gender. Opposite-sex flag: female call with Y CPM>20 or male call "
|
| 696 |
+
"with XIST CPM>50 (bulk)"),
|
| 697 |
+
"expression_rule": f"log2(CPM+1) over the {int(common.sum())} non-chrY canonical genes measured in all {len(b_index)} bulk columns and all {len(sc_ids)} sc samples; top {TOP_N} by the mean of the bulk-mean and sc-mean log CPM; Spearman of each paired bulk vs all sc pseudobulks; centred sensitivity; reverse vs all bulks",
|
| 698 |
+
"expression_residualised_rule": f"within each modality: centre log2(CPM+1) (same genes), remove the top k sample PCs computed on expressed genes (bulk mean >3 and sc mean >1 log2 CPM), keep the 2000 genes with the highest residual variance in both modalities (rank sum), Pearson over all {len(b_index)} bulk columns x all {len(sc_ids)} sc samples (controls and SHD8 included as null candidates; one subject label per person). k={K_PRIMARY} primary, k=3 and k=10 sensitivity. Ranks per sample and per subject (each subject scored by its best sample). chrY genes excluded. Uses no pairing information.",
|
| 699 |
+
"verdict_rule": f"pass = sex concordant (bulk, sc, metadata) and residualised k={K_PRIMARY} own subject ranked 1st in one direction and within the top {SUBJ_TOP} subjects in the other and no timepoint failure; fail = sex discordant, or own subject below {SUBJ_TOP} in both directions, or timepoint failure; else borderline",
|
| 700 |
+
"timepoint_check": f"within the subject's paired rows, rank of the own timepoint on the residualised (k={K_PRIMARY}) and on the centred (not residualised) expression correlation, both directions; failure = another timepoint of the same subject beats the own one in all four (the Giroux 2022 rule)",
|
| 701 |
+
"isg_rule": f"informational: mean log2(CPM+1) of {len(ISG_GENES)} ISGs ({', '.join(ISG_GENES)}); per subject the ISG-peak timepoint in bulk and in sc",
|
| 702 |
+
"policy": "reported only; no row dropped on identity results; features.npz carries identity_pass / identity_check"},
|
| 703 |
+
"checks": checks,
|
| 704 |
+
"sc_sex_ambient": {"rule": "see identity.sex_rule",
|
| 705 |
+
"samples_called_per_cell": sc_sex.index[sc_sex.sc_sex_call_method != "pseudobulk"].tolist(),
|
| 706 |
+
"male_meta_frac_cells_Y_min": float(sc_sex.loc[sc_meta.loc[sc_sex.index, "Gender"] == "Male", "sc_frac_cells_Y"].min()),
|
| 707 |
+
"female_meta_frac_cells_Y_max": float(sc_sex.loc[sc_meta.loc[sc_sex.index, "Gender"] == "Female", "sc_frac_cells_Y"].max()),
|
| 708 |
+
"female_meta_samples": sc_sex.loc[sc_meta.loc[sc_sex.index, "Gender"] == "Female",
|
| 709 |
+
["sc_XIST_cpm", "sc_Ysum_cpm", "sc_frac_cells_XIST", "sc_frac_cells_Y",
|
| 710 |
+
"sc_sex_call_pseudobulk", "sc_sex_call"]].round(4).reset_index().to_dict("records")},
|
| 711 |
+
"excluded": {"quarantined_sc_samples_among_pairs": quarantined_pairs,
|
| 712 |
+
"sc_samples_without_pair": sc_un[["sc_sample", "kind", "reason"]].to_dict("records"),
|
| 713 |
+
"sc_samples_not_in_pairs_check": unmatched_sc.sc_sample.tolist(),
|
| 714 |
+
"bulk_count_columns_without_pair": unmatched_cols.to_dict("records")},
|
| 715 |
+
"inputs": {"gene_positions": {"path": str(POSITIONS), "sha256": POSITIONS_SHA},
|
| 716 |
+
"selected_genes": {"path": str(SELECTED), "sha256": sha256_file(SELECTED)},
|
| 717 |
+
"reference_panel": {"path": str(REF_PANEL), "sha256": sha256_file(REF_PANEL)},
|
| 718 |
+
"canonical_genes": {"path": str(REFERENCE / "canonical_genes.tsv"), "sha256": sha256_file(REFERENCE / "canonical_genes.tsv")},
|
| 719 |
+
"bulk_harmonized": {"path": str(RUN / "bulk/GSE161918_htseq/harmonized.h5ad"),
|
| 720 |
+
"sha256": sha256_file(RUN / "bulk/GSE161918_htseq/harmonized.h5ad")},
|
| 721 |
+
"sources": json.loads((RUN / "SOURCES.json").read_text())["files"],
|
| 722 |
+
"hto_metadata": json.loads((RUN / "SOURCES.json").read_text())["hto_metadata"],
|
| 723 |
+
"rds_export": json.loads((RUN / "SOURCES.json").read_text())["rds_export"],
|
| 724 |
+
"crosswalk": json.loads((RUN / "reference_crosswalk/CROSSWALK.json").read_text())["file"]},
|
| 725 |
+
"code": {name: {"path": str(path), "sha256": sha256_file(path)} for name, path in [
|
| 726 |
+
("assemble", Path(__file__).resolve()), ("pipeline", RUN / "code/liu2021_pipeline.py"),
|
| 727 |
+
("rds_export", RUN / "code/liu2021_rds_export.R"), ("run_step", RUN / "code/run_step.sh")] + [
|
| 728 |
+
("bundle/" + q.name, q) for q in sorted((RUN / "code/strict_qc_v1_code_bundle_v5").glob("*.py"))]},
|
| 729 |
+
"processing_dir": str(RUN),
|
| 730 |
+
}
|
| 731 |
+
manifest["outputs"] = {q.name: {"bytes": q.stat().st_size, "sha256": sha256_file(q)}
|
| 732 |
+
for q in sorted(OUT.iterdir()) if q.is_file() and q.name in (
|
| 733 |
+
"features.npz", "cells_panel6k.npz", "cells_obs.parquet", "samples.csv", "pairs.csv",
|
| 734 |
+
"identity_sex_bulk_all.csv", "identity_sex_sc_all.csv", "identity_expression.csv")}
|
| 735 |
+
(OUT / "MANIFEST.json").write_text(json.dumps(manifest, indent=1, default=str) + "\n")
|
| 736 |
+
shutil.rmtree(TMP)
|
| 737 |
+
print(json.dumps({"rows": n, "cells": manifest["cells"], "checks": checks}, indent=1, default=str))
|
| 738 |
+
return 0
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
if __name__ == "__main__":
|
| 742 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/aggregate_loco.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Collect the LOCO scores into one table per held-out cohort (CPU only, reads summary.json / per_donor.csv).
|
| 3 |
+
|
| 4 |
+
Rows per held-out cohort (all scored on the cohort's usable samples against the same frozen reference):
|
| 5 |
+
zero target pairs zs_K1000, zs_K2000 (zero-shot, real bulk), xcal_K<K> (zero-shot + cross-cohort calibration),
|
| 6 |
+
loco_<tag>_K<K> (fine-tuned on the other cohorts' pairs; tag lora16 / lora64 / full)
|
| 7 |
+
with target pairs within-cohort 5-fold pooled arms of plans/paired_finetune_intradataset_20260927 (reference
|
| 8 |
+
only): zs__cal (zero-shot + within-cohort calibration), real_lora__raw (LoRA r16 on the
|
| 9 |
+
training folds' pairs), real_full__raw (full fine-tune; ImMicro and sepsis only)
|
| 10 |
+
Every call must score the same samples against the same reference (reference_sha256); a mismatch stops the script.
|
| 11 |
+
Giroux's disease metrics (logFC r, partial r, top-50 DEG, broadcast) come from the sex-linked-gene-excluded rescore
|
| 12 |
+
(scores_nosex/), as in the deck; Sepsis' within-cohort DEG from scores/ye2026_sepsis/pooled_deg/ (its pooled call
|
| 13 |
+
has no DEG block). Composition L1: paired Wilcoxon over samples of each zero-pair arm vs zs_K1000 and vs the
|
| 14 |
+
within-cohort LoRA.
|
| 15 |
+
Outputs: AGGREGATE.md, aggregate.csv
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import sys
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import pandas as pd
|
| 25 |
+
from scipy.stats import wilcoxon
|
| 26 |
+
|
| 27 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 28 |
+
P = M8 / "plans/paired_crosscohort_20261002"
|
| 29 |
+
SRC = M8 / "plans/paired_finetune_intradataset_20260927"
|
| 30 |
+
COHORTS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
|
| 31 |
+
NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", "giroux2022": "Giroux",
|
| 32 |
+
"ji2025_chili": "Ji (whole blood)"}
|
| 33 |
+
REF_ARMS = {"zs__cal": "within-cohort calibration", "real_lora__raw": "within-cohort LoRA r16",
|
| 34 |
+
"real_full__raw": "within-cohort full FT"}
|
| 35 |
+
DISEASE = ("logfc_r", "broadcast_r", "partial_r", "deg50", "deg50_broadcast", "deg50_max")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def arm_metrics(summ: dict, arm: str) -> dict:
|
| 39 |
+
h = summ["headline"][arm]
|
| 40 |
+
out = {k: h.get(k) for k in ("comp_l1", "precision", "coverage", "precision_dm", "coverage_dm", "pb_r_median")}
|
| 41 |
+
c = (summ["per_arm"][arm].get("contrast") or {}).get("mean_cp10k") or {}
|
| 42 |
+
pt = c.get("per_type") or {}
|
| 43 |
+
out["logfc_r"] = h.get("contrast_mean_cp10k_r_gen")
|
| 44 |
+
out["broadcast_r"] = h.get("contrast_mean_cp10k_r_broadcast")
|
| 45 |
+
pr = [v.get("partial_r_generated_given_broadcast") for v in pt.values()]
|
| 46 |
+
pr = [x for x in pr if x is not None and np.isfinite(x)]
|
| 47 |
+
out["partial_r"] = float(np.mean(pr)) if pr else None
|
| 48 |
+
out["deg50"], out["deg50_broadcast"], out["deg50_max"] = (h.get("deg_top50_sum"), h.get("deg_top50_sum_broadcast"),
|
| 49 |
+
h.get("deg_top50_max"))
|
| 50 |
+
return out
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def md_table(t: pd.DataFrame) -> str:
|
| 54 |
+
def fmt(v):
|
| 55 |
+
if v is None or (isinstance(v, float) and not np.isfinite(v)):
|
| 56 |
+
return ""
|
| 57 |
+
if isinstance(v, (float, np.floating)):
|
| 58 |
+
return f"{v:.3g}"
|
| 59 |
+
return str(v)
|
| 60 |
+
lines = ["| " + " | ".join(t.columns) + " |", "|" + "---|" * len(t.columns)]
|
| 61 |
+
lines += ["| " + " | ".join(fmt(v) for v in row) + " |" for row in t.itertuples(index=False)]
|
| 62 |
+
return "\n".join(lines)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def load(path: Path) -> dict | None:
|
| 66 |
+
return json.loads(path.read_text()) if path.is_file() else None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main() -> int:
|
| 70 |
+
rows, md = [], ["# Cross-cohort (LOCO) benchmark: scores", "",
|
| 71 |
+
"Generated by `tools/aggregate_loco.py`; do not edit. Zero-pair arms first, then within-cohort "
|
| 72 |
+
"references that used the held-out cohort's own pairs.", ""]
|
| 73 |
+
for c in COHORTS:
|
| 74 |
+
donors = set(Path(P / "data" / c / "usable_samples.txt").read_text().split())
|
| 75 |
+
calls = {}
|
| 76 |
+
for d in sorted((P / "scores" / c).glob("*/summary.json")) if (P / "scores" / c).is_dir() else []:
|
| 77 |
+
calls[d.parent.name] = (load(d), d.parent)
|
| 78 |
+
if not calls:
|
| 79 |
+
continue
|
| 80 |
+
src = load(SRC / "scores" / c / "pooled" / "summary.json")
|
| 81 |
+
refsha = {s["reference"]["reference_sha256"] for s, _ in calls.values()} | {src["reference"]["reference_sha256"]}
|
| 82 |
+
if len(refsha) != 1:
|
| 83 |
+
raise SystemExit(f"{c}: calls use different references {refsha}")
|
| 84 |
+
for arm, (s, _) in calls.items():
|
| 85 |
+
if set(s["donors"]) != donors:
|
| 86 |
+
raise SystemExit(f"{c}/{arm}: scored samples differ from usable_samples.txt")
|
| 87 |
+
if set(src["donors"]) != donors:
|
| 88 |
+
raise SystemExit(f"{c}: within-cohort pooled call scored different samples")
|
| 89 |
+
nosex = c == "giroux2022"
|
| 90 |
+
recs = []
|
| 91 |
+
for arm, (s, d) in sorted(calls.items()):
|
| 92 |
+
m = arm_metrics(s, arm)
|
| 93 |
+
if nosex:
|
| 94 |
+
ns = load(P / "scores_nosex" / c / arm / "summary.json")
|
| 95 |
+
mm = arm_metrics(ns, arm) if ns else {k: None for k in DISEASE}
|
| 96 |
+
for k in DISEASE:
|
| 97 |
+
m[k] = mm[k]
|
| 98 |
+
pdon = pd.read_csv(d / "per_donor.csv").set_index("donor")["comp_l1"]
|
| 99 |
+
recs.append({"cohort": c, "arm": arm, "uses_target_pairs": False, **m, "_l1": pdon})
|
| 100 |
+
src_pd = pd.read_csv(SRC / "scores" / c / "pooled" / "per_donor.csv")
|
| 101 |
+
src_ns = load(SRC / "scores_nosex" / c / "pooled" / "summary.json") if nosex else None
|
| 102 |
+
src_deg = load(SRC / "scores" / c / "pooled_deg" / "summary.json") if c == "ye2026_sepsis" else None
|
| 103 |
+
for arm, label in REF_ARMS.items():
|
| 104 |
+
if arm not in src["arms"]:
|
| 105 |
+
continue
|
| 106 |
+
m = arm_metrics(src, arm)
|
| 107 |
+
if src_ns:
|
| 108 |
+
mm = arm_metrics(src_ns, arm)
|
| 109 |
+
for k in DISEASE:
|
| 110 |
+
m[k] = mm[k]
|
| 111 |
+
if src_deg and arm in src_deg["arms"]:
|
| 112 |
+
if set(src_deg["donors"]) != donors:
|
| 113 |
+
raise SystemExit("sepsis pooled_deg scored different samples")
|
| 114 |
+
mm = arm_metrics(src_deg, arm)
|
| 115 |
+
for k in ("deg50", "deg50_broadcast", "deg50_max"):
|
| 116 |
+
m[k] = mm[k]
|
| 117 |
+
pdon = src_pd[src_pd.arm == arm].set_index("donor")["comp_l1"]
|
| 118 |
+
recs.append({"cohort": c, "arm": f"[{label}] {arm}", "uses_target_pairs": True, **m, "_l1": pdon})
|
| 119 |
+
base = next((r["_l1"] for r in recs if r["arm"] == "zs_K1000"), None)
|
| 120 |
+
wlora = next((r["_l1"] for r in recs if r["arm"].endswith("real_lora__raw")), None)
|
| 121 |
+
for r in recs:
|
| 122 |
+
for nm, ref in (("p_l1_vs_zs_K1000", base), ("p_l1_vs_within_lora", wlora)):
|
| 123 |
+
if ref is None or r["_l1"] is ref:
|
| 124 |
+
r[nm] = None
|
| 125 |
+
continue
|
| 126 |
+
a, b = r["_l1"].align(ref, join="inner")
|
| 127 |
+
r[nm] = float(wilcoxon(a, b).pvalue) if len(a) > 5 and (a != b).any() else None
|
| 128 |
+
rows.append({k: v for k, v in r.items() if k != "_l1"})
|
| 129 |
+
t = pd.DataFrame([{k: v for k, v in r.items() if k != "_l1"} for r in recs])
|
| 130 |
+
md += [f"## {NAME[c]} ({len(donors)} samples; reference {next(iter(refsha))[:12]})", ""]
|
| 131 |
+
cols = ["arm", "comp_l1", "p_l1_vs_zs_K1000", "precision", "coverage", "coverage_dm", "pb_r_median"]
|
| 132 |
+
if c != "immicro":
|
| 133 |
+
cols += ["logfc_r", "broadcast_r", "partial_r", "deg50", "deg50_broadcast", "deg50_max"]
|
| 134 |
+
md += [md_table(t[cols]), ""]
|
| 135 |
+
pd.DataFrame(rows).to_csv(P / "scores" / "aggregate.csv", index=False)
|
| 136 |
+
(P / "scores" / "AGGREGATE.md").write_text("\n".join(md) + "\n")
|
| 137 |
+
print("\n".join(md))
|
| 138 |
+
return 0
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/prepare_loco_extra.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Add training-only cohorts to the LOCO benchmark as a second split family (CPU only).
|
| 3 |
+
|
| 4 |
+
usage: prepare_loco_extra.py liu2021 [more cohorts]
|
| 5 |
+
|
| 6 |
+
A training-only cohort is a paired cohort that may never be a test cohort, e.g. Liu 2021, whose single cells are in
|
| 7 |
+
the pretraining corpus. For every held-out cohort X of prepare_loco.py this writes a split hoL_<X> whose training
|
| 8 |
+
pool = ho_<X>'s pool + the extra cohorts (all their usable pairs; inner-validation donors by the same rule), with
|
| 9 |
+
the same test files as ho_<X> (data/<X>/test_raw_K<K>.npz) and its own cross-cohort calibration (alpha over the
|
| 10 |
+
enlarged pool, cohort-balanced, same rule). Existing files are never rewritten: running jobs read them.
|
| 11 |
+
|
| 12 |
+
Writes: data/<extra>/conditions_raw_K<K>.npz, inner_val_donors.txt, usable_samples.txt,
|
| 13 |
+
training_excluded.txt (rows dropped by EXCLUDE, never trained on);
|
| 14 |
+
splits/hoL_<X>.json, splits/hoL_<X>/{alpha_xcal.npy, test_xcal_K<K>.npz}; PREPARE_EXTRA.json
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import sys
|
| 21 |
+
from datetime import datetime, timezone
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import pandas as pd
|
| 26 |
+
|
| 27 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 28 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 29 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 30 |
+
import prepare_loco as L # noqa: E402
|
| 31 |
+
|
| 32 |
+
PD, RB, PLAN, SRC = L.PD, L.RB, L.PLAN, L.SRC
|
| 33 |
+
PREFIX = "hoL"
|
| 34 |
+
# Rows of a training-only cohort that stay in its dataset but are not used as training pairs, read from the
|
| 35 |
+
# cohort's processing run: Liu 2021 rows whose retained (HTO-singlet) cells lost > 30 % of the unsorted cells to
|
| 36 |
+
# HTO-negative calls (weakly stained pools B2 HTO3, B3 HTO5). Negatives carry ~20 points fewer classical monocytes,
|
| 37 |
+
# so these rows' retained cells over-represent monocytes against a bulk made from all cells (QC_REPORT.md).
|
| 38 |
+
EXCLUDE = {"liu2021": {"file": Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/"
|
| 39 |
+
"liu2021_v1_20261002/identity/hto_negative_sensitivity.csv"),
|
| 40 |
+
"column": "negative_fraction", "max": 0.30,
|
| 41 |
+
"reason": "HTO-negative cells > 30 % of the row's unsorted cells: retained-cell composition "
|
| 42 |
+
"is biased against the all-cell bulk"}}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def training_exclusions(cohort: str) -> tuple[list[str], dict]:
|
| 46 |
+
rule = EXCLUDE.get(cohort)
|
| 47 |
+
if not rule:
|
| 48 |
+
return [], {}
|
| 49 |
+
t = pd.read_csv(rule["file"])
|
| 50 |
+
ex = sorted(t.loc[t[rule["column"]] > rule["max"], "sample_id"].astype(str))
|
| 51 |
+
info = {**{k: str(v) for k, v in rule.items()}, "file_sha256": L.sha256_file(rule["file"]), "sample_ids": ex}
|
| 52 |
+
return ex, info
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def new_file(path: Path) -> Path:
|
| 56 |
+
if path.exists():
|
| 57 |
+
raise SystemExit(f"{path} exists; this script never rewrites files")
|
| 58 |
+
return path
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def main(extra: list[str]) -> int:
|
| 62 |
+
if not extra or set(extra) & set(L.COHORTS):
|
| 63 |
+
raise SystemExit("name one or more training-only cohorts that are not LOCO cohorts")
|
| 64 |
+
man = {"schema": "pbisc_sdd.crosscohort.extra.v1", "written_utc": datetime.now(timezone.utc).isoformat(),
|
| 65 |
+
"extra_training_cohorts": extra, "split_prefix": PREFIX, "script_sha256": L.sha256_file(Path(__file__)),
|
| 66 |
+
"prepare_loco_sha256": L.sha256_file(PLAN / "tools/prepare_loco.py"), "inputs": {}, "files": {},
|
| 67 |
+
"cohorts": {}}
|
| 68 |
+
data, folds_of = {}, {}
|
| 69 |
+
for c in L.PBMC:
|
| 70 |
+
data[c] = PD.load(SRC / "data" / c)
|
| 71 |
+
folds_of[c] = pd.read_csv(SRC / "data" / c / "folds.csv")
|
| 72 |
+
base_spec = {c: json.loads((PLAN / "splits" / f"ho_{c}.json").read_text()) for c in L.COHORTS}
|
| 73 |
+
for i, c in enumerate(extra):
|
| 74 |
+
ds = SRC / "data" / c
|
| 75 |
+
d = PD.load(ds)
|
| 76 |
+
folds = pd.read_csv(ds / "folds.csv")
|
| 77 |
+
if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), d["sample_ids"]):
|
| 78 |
+
raise SystemExit(f"{c}: folds.csv rows differ from features.npz")
|
| 79 |
+
if not np.array_equal(folds["fold"].to_numpy() >= 0, d["use"]):
|
| 80 |
+
raise SystemExit(f"{c}: folds.csv usable rows differ from prepare_dataset.load")
|
| 81 |
+
for f in ("features.npz", "folds.csv", "cells_panel6k.npz"):
|
| 82 |
+
man["inputs"][f"{c}/{f}"] = L.sha256_file((ds / f).resolve())
|
| 83 |
+
data[c], folds_of[c] = d, folds
|
| 84 |
+
out = PLAN / "data" / c
|
| 85 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 86 |
+
all_rows = np.arange(len(folds))
|
| 87 |
+
usable = folds.index[folds["fold"] >= 0].to_numpy()
|
| 88 |
+
for k in L.KS:
|
| 89 |
+
raw = L.counts_at_k(d["bulk"], d["bulk_valid"], k)
|
| 90 |
+
man["files"][f"data/{c}/conditions_raw_K{k}.npz"] = L.write_npz(
|
| 91 |
+
new_file(out / f"conditions_raw_K{k}.npz"), d, all_rows, raw, d["bulk_valid"], k, "raw")
|
| 92 |
+
excl, excl_info = training_exclusions(c)
|
| 93 |
+
if excl:
|
| 94 |
+
if not set(excl) <= set(folds["sample_id"].astype(str)):
|
| 95 |
+
raise SystemExit(f"{c}: excluded sample ids not in folds.csv")
|
| 96 |
+
# excluded rows leave the training pool before inner-validation donors are drawn
|
| 97 |
+
folds = folds.assign(fold=np.where(folds["sample_id"].astype(str).isin(excl), -2, folds["fold"]))
|
| 98 |
+
folds_of[c] = folds
|
| 99 |
+
new_file(out / "training_excluded.txt").write_text("".join(f"{x}\n" for x in excl))
|
| 100 |
+
inner = L.inner_val_donors(folds, len(L.COHORTS) + i)
|
| 101 |
+
new_file(out / "inner_val_donors.txt").write_text("".join(f"{x}\n" for x in inner))
|
| 102 |
+
new_file(out / "usable_samples.txt").write_text("".join(f"{x}\n" for x in d["sample_ids"][usable]))
|
| 103 |
+
pool = folds.index[folds["fold"] >= 0].to_numpy() # usable rows minus training exclusions
|
| 104 |
+
u = folds.loc[pool]
|
| 105 |
+
man["cohorts"][c] = {"role": "training only", "training_exclusion": excl_info,
|
| 106 |
+
"usable_rows": int(len(usable)), "training_pool_rows": int(len(pool)),
|
| 107 |
+
"training_pool_donors": int(u["donor_id"].nunique()), "inner_val_donors": inner,
|
| 108 |
+
"inner_val_rows": int(u["donor_id"].astype(str).isin(inner).sum()),
|
| 109 |
+
"groups": u.groupby("group")["donor_id"].nunique().to_dict()}
|
| 110 |
+
for held in L.COHORTS:
|
| 111 |
+
base = base_spec[held]
|
| 112 |
+
name = f"{PREFIX}_{held}"
|
| 113 |
+
sd = PLAN / "splits" / name
|
| 114 |
+
sd.mkdir(exist_ok=True)
|
| 115 |
+
tc = list(base["training_cohorts"])
|
| 116 |
+
for c in extra:
|
| 117 |
+
f = folds_of[c]
|
| 118 |
+
use = f[f["fold"] >= 0]
|
| 119 |
+
is_inner = use["donor_id"].astype(str).isin(set(man["cohorts"][c]["inner_val_donors"]))
|
| 120 |
+
tc.append({"cohort": c, "dataset_dir": str(SRC / "data" / c),
|
| 121 |
+
"condition_npz": {str(k): str(PLAN / "data" / c / f"conditions_raw_K{k}.npz") for k in L.KS},
|
| 122 |
+
"train_sample_ids": use.loc[~is_inner, "sample_id"].astype(str).tolist(),
|
| 123 |
+
"inner_val_sample_ids": use.loc[is_inner, "sample_id"].astype(str).tolist()})
|
| 124 |
+
bmean, pmean, valid = [], [], np.ones(20097, dtype=bool)
|
| 125 |
+
for x in tc:
|
| 126 |
+
d, f = data[x["cohort"]], folds_of[x["cohort"]]
|
| 127 |
+
rows = f.index[f["fold"] >= 0].to_numpy()
|
| 128 |
+
valid &= d["bulk_valid"][rows].all(axis=0) & d["sc_valid"][rows].all(axis=0)
|
| 129 |
+
bmean.append(RB.cpm(d["bulk"][rows]).mean(axis=0))
|
| 130 |
+
pmean.append(RB.cpm(d["pseudo"][rows]).mean(axis=0))
|
| 131 |
+
b, p = np.mean(bmean, axis=0), np.mean(pmean, axis=0)
|
| 132 |
+
alpha = np.ones_like(b)
|
| 133 |
+
est = valid & (b >= 1.0) & (p >= 1.0)
|
| 134 |
+
alpha[est] = p[est] / b[est]
|
| 135 |
+
np.save(new_file(sd / "alpha_xcal.npy"), alpha)
|
| 136 |
+
dh = PD.load(SRC / "data" / held)
|
| 137 |
+
fh = pd.read_csv(SRC / "data" / held / "folds.csv")
|
| 138 |
+
usable = fh.index[fh["fold"] >= 0].to_numpy()
|
| 139 |
+
test = {}
|
| 140 |
+
for k in L.KS:
|
| 141 |
+
cal = L.counts_at_k(RB.cpm(dh["bulk"]) * alpha[None, :], dh["bulk_valid"], k)
|
| 142 |
+
man["files"][f"splits/{name}/test_xcal_K{k}.npz"] = L.write_npz(
|
| 143 |
+
new_file(sd / f"test_xcal_K{k}.npz"), dh, usable, cal, dh["bulk_valid"], k, "xcal")
|
| 144 |
+
test[str(k)] = {"raw": base["test"]["condition_npz"][str(k)]["raw"], "xcal": str(sd / f"test_xcal_K{k}.npz")}
|
| 145 |
+
spec = {**base, "split": name, "training_cohorts": tc,
|
| 146 |
+
"test": {**base["test"], "condition_npz": test},
|
| 147 |
+
"xcal": {"alpha": str(sd / "alpha_xcal.npy"), "genes_estimated": int(est.sum()),
|
| 148 |
+
"rule": "cohort-balanced mean CPM of the training cohorts' usable pairs"},
|
| 149 |
+
"extra_training_cohorts": extra, "base_split": f"ho_{held}",
|
| 150 |
+
"n_train_rows": int(sum(len(x["train_sample_ids"]) for x in tc)),
|
| 151 |
+
"n_inner_val_rows": int(sum(len(x["inner_val_sample_ids"]) for x in tc))}
|
| 152 |
+
tr_ids = {s for x in tc for s in x["train_sample_ids"] + x["inner_val_sample_ids"]}
|
| 153 |
+
if tr_ids & set(spec["test"]["sample_ids"]) or held in {x["cohort"] for x in tc}:
|
| 154 |
+
raise SystemExit(f"{name}: held-out rows in the training inputs")
|
| 155 |
+
new_file(PLAN / "splits" / f"{name}.json").write_text(json.dumps(spec, indent=1))
|
| 156 |
+
man["files"][f"splits/{name}.json"] = L.sha256_file(PLAN / "splits" / f"{name}.json")
|
| 157 |
+
per = ", ".join("%s %d" % (x["cohort"], len(x["train_sample_ids"])) for x in tc)
|
| 158 |
+
print(f"{name}: train {spec['n_train_rows']} rows ({per}), inner-val {spec['n_inner_val_rows']}, "
|
| 159 |
+
f"test {len(spec['test']['sample_ids'])}, xcal genes {int(est.sum())}")
|
| 160 |
+
new_file(PLAN / "PREPARE_EXTRA.json").write_text(json.dumps(man, indent=1, default=str))
|
| 161 |
+
print(json.dumps(man["cohorts"], indent=1, default=str))
|
| 162 |
+
return 0
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
if __name__ == "__main__":
|
| 166 |
+
sys.exit(main(sys.argv[1:]))
|
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/score_pending.sh
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Score every finished LOCO arm on server_1 (CPU), one arm per score_ft.py call, as soon as it exists.
|
| 3 |
+
# Each call scores the held-out cohort's usable samples (data/<cohort>/usable_samples.txt) against the cohort's frozen
|
| 4 |
+
# reference (scoring_cache of the within-cohort benchmark), so calls are comparable with each other and with that
|
| 5 |
+
# benchmark's pooled 5-fold call (same donors, same reference; checked by aggregate_loco.py).
|
| 6 |
+
# arms: zs_K1000 (the within-cohort benchmark's zero-shot on all usable rows; same model, sampler, seed and bulk
|
| 7 |
+
# arrays as zs_K2000 apart from K), zs_K2000, xcal_K<K>, loco_<tag>_K<K>, and with training-only cohorts
|
| 8 |
+
# added to the pool (splits hoL_*) xcalL_K<K>, locoL_<tag>_K<K>
|
| 9 |
+
# out: scores/<cohort>/<arm>/ ; Giroux also scores_nosex/giroux2022/<arm>/ (sex-linked genes excluded from the
|
| 10 |
+
# disease metrics, labels reused), as the deck reports Giroux
|
| 11 |
+
# Runs until both LOCO queues (server_1 loco-queue-s1, server_2 loco-queue-s2) are inactive and nothing is pending.
|
| 12 |
+
set -uo pipefail
|
| 13 |
+
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
| 14 |
+
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
|
| 15 |
+
M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
|
| 16 |
+
P=$M8/plans/paired_crosscohort_20261002
|
| 17 |
+
SRC=$M8/plans/paired_finetune_intradataset_20260927
|
| 18 |
+
PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
|
| 19 |
+
SEX=$SRC/data/sex_linked_genes/sex_linked_genes_exclude.csv
|
| 20 |
+
COHORTS=(immicro ye2026_sepsis imperial_eskd giroux2022 ji2025_chili)
|
| 21 |
+
LOG=$P/logs/score_pending_$(date +%Y%m%dT%H%M%S).log
|
| 22 |
+
mkdir -p "$P/logs"
|
| 23 |
+
log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
|
| 24 |
+
|
| 25 |
+
zs1000() { # the within-cohort benchmark's zero-shot NPZ (Imperial's lives on server_2: copied once, sha-checked)
|
| 26 |
+
local c=$1 f=$SRC/generated/$1/fewshot_n5/zs__raw_all.npz
|
| 27 |
+
if [[ -s $f ]]; then echo "$f"; return; fi
|
| 28 |
+
local d=$P/inputs_server2/$c; f=$d/zs__raw_all.npz
|
| 29 |
+
if [[ ! -s $f ]]; then
|
| 30 |
+
mkdir -p "$d" && rsync -a "spark-0110:$SRC/generated/$c/fewshot_n5/zs__raw_all.npz" \
|
| 31 |
+
"spark-0110:$SRC/generated/$c/fewshot_n5/zs__raw_all.log" "$d/" || { rm -f "$f"; return 1; }
|
| 32 |
+
fi
|
| 33 |
+
echo "$f"
|
| 34 |
+
}
|
| 35 |
+
arms_of() { # prints "ARM NPZ" for every arm of cohort $1 whose NPZ and receipt exist
|
| 36 |
+
# split ho_<c>: arms xcal_K<K>, loco_<tag>_K<K>; split hoL_<c> (training pool + training-only cohorts such as
|
| 37 |
+
# Liu 2021, tools/prepare_loco_extra.py): arms xcalL_K<K>, locoL_<tag>_K<K>
|
| 38 |
+
local c=$1 f K tag b s suf
|
| 39 |
+
f=$(zs1000 "$c") && echo "zs_K1000 $f"
|
| 40 |
+
f=$P/generated/$c/zs_K2000.npz
|
| 41 |
+
[[ -s $f && -s ${f%.npz}.log ]] && echo "zs_K2000 $f"
|
| 42 |
+
for s in "ho_$c" "hoL_$c"; do
|
| 43 |
+
suf=""; [[ $s == hoL_* ]] && suf=L
|
| 44 |
+
for f in "$P/generated/$c/$s"/xcal_K*.npz "$P/generated/$c/$s"/K*_*.npz; do
|
| 45 |
+
[[ -s $f && -s ${f%.npz}.log ]] || continue
|
| 46 |
+
b=$(basename "$f" .npz)
|
| 47 |
+
if [[ $b == xcal_K* ]]; then echo "xcal${suf}_${b#xcal_} $f"
|
| 48 |
+
else K=${b%%_*}; tag=${b#*_}; echo "loco${suf}_${tag}_${K} $f"; fi
|
| 49 |
+
done
|
| 50 |
+
done
|
| 51 |
+
}
|
| 52 |
+
score_one() { # cohort arm npz [extra args]
|
| 53 |
+
local c=$1 arm=$2 npz=$3; shift 3
|
| 54 |
+
local name=score-${c}-${arm}-$(date +%H%M%S)
|
| 55 |
+
local avail; avail=$(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo)
|
| 56 |
+
(( avail >= 56 )) || { log "MemAvailable $avail GiB < 56: $c $arm waits"; return 1; }
|
| 57 |
+
read -r -a cargs <<< "$(bash "$SRC/tools/contrast_args.sh" "$c")"
|
| 58 |
+
systemd-run --user --unit="$name" --working-directory="$P" --wait --collect --quiet \
|
| 59 |
+
-p MemoryMax=24G -p MemorySwapMax=0 -p CPUQuota=800% -p Nice=10 \
|
| 60 |
+
-p StandardOutput=append:"$P/logs/$name.log" -p StandardError=append:"$P/logs/$name.log" \
|
| 61 |
+
--setenv=CUDA_VISIBLE_DEVICES= --setenv=PYTHONNOUSERSITE=1 --setenv=PYTHONDONTWRITEBYTECODE=1 \
|
| 62 |
+
--setenv=PYTHONUNBUFFERED=1 --setenv=OMP_NUM_THREADS=8 --setenv=OPENBLAS_NUM_THREADS=8 \
|
| 63 |
+
--setenv=MKL_NUM_THREADS=8 --setenv=NUMBA_NUM_THREADS=8 \
|
| 64 |
+
"$PY" "$SRC/tools/score_ft.py" --dataset "$c" --threads 8 --donors "$P/data/$c/usable_samples.txt" \
|
| 65 |
+
--arm "$arm=$npz" "${cargs[@]}" "$@"
|
| 66 |
+
}
|
| 67 |
+
queues_active() {
|
| 68 |
+
systemctl --user is-active --quiet loco-queue-s1 && return 0
|
| 69 |
+
ssh -n spark-0110 'XDG_RUNTIME_DIR=/run/user/$(id -u) systemctl --user is-active loco-queue-s2' 2>/dev/null | grep -q '^active' && return 0
|
| 70 |
+
return 1
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
log "start"
|
| 74 |
+
while true; do
|
| 75 |
+
active=0; queues_active && active=1
|
| 76 |
+
pending=0
|
| 77 |
+
for c in "${COHORTS[@]}"; do
|
| 78 |
+
while read -r arm npz; do
|
| 79 |
+
[[ -n $arm ]] || continue
|
| 80 |
+
out=$P/scores/$c/$arm
|
| 81 |
+
# a failed call leaves <out>.FAILED and is not retried (inspect logs/score-<cohort>-<arm>-*.log, then remove it)
|
| 82 |
+
if [[ ! -s $out/summary.json && ! -e $out.FAILED ]]; then
|
| 83 |
+
pending=1
|
| 84 |
+
log "score $c $arm"
|
| 85 |
+
if score_one "$c" "$arm" "$npz" --out "$out"; then log "scored $c $arm"
|
| 86 |
+
else log "WARN: scoring $c $arm failed (logs/score-$c-$arm-*.log)"; date -Is > "$out.FAILED"; fi
|
| 87 |
+
fi
|
| 88 |
+
nos=$P/scores_nosex/$c/$arm
|
| 89 |
+
if [[ $c == giroux2022 && -s $out/summary.json && ! -s $nos/summary.json && ! -e $nos.FAILED ]]; then
|
| 90 |
+
pending=1
|
| 91 |
+
mkdir -p "$(dirname "$nos")"
|
| 92 |
+
if score_one "$c" "$arm" "$npz" --out "$nos" --exclude-genes "$SEX" --reuse-labels "$out"; then
|
| 93 |
+
log "scored $c $arm (sex-linked genes excluded)"
|
| 94 |
+
else log "WARN: no-sex rescore $c $arm failed"; date -Is > "$nos.FAILED"; fi
|
| 95 |
+
fi
|
| 96 |
+
done < <(arms_of "$c")
|
| 97 |
+
done
|
| 98 |
+
if (( ! active && ! pending )); then log "queues inactive and nothing pending: done"; break; fi
|
| 99 |
+
sleep 600
|
| 100 |
+
done
|