Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/1e605e8033024686/liu2021_finalize.py +72 -0
- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/2e9f4baf0e18957c/liu2021_findings.py +204 -0
- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/8a4485ba51f51c7e/liu2021_hto_sensitivity.py +102 -0
- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/981b08078aab70e8/liu2021_full_cells.py +124 -0
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/1e605e8033024686/liu2021_finalize.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Record the post-assembly outputs in data/liu2021/MANIFEST.json (CPU only, small); the Imperial ESKD pattern.
|
| 3 |
+
|
| 4 |
+
Adds `post_assembly`: cells_full.npz (from cells_full.BUILD.json, re-hashed here), the tools/prepare_dataset.py run
|
| 5 |
+
(PREPARE.json, folds.csv), the sanity comparison (SANITY.json) and the HTO-negative sensitivity summary.
|
| 6 |
+
Nothing else in the manifest is changed.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
from datetime import datetime, timezone
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import pandas as pd
|
| 18 |
+
|
| 19 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 20 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 21 |
+
TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
|
| 22 |
+
OUT = TASK / "data/liu2021"
|
| 23 |
+
RUN = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/liu2021_v1_20261002")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def sha(p: Path) -> str:
|
| 27 |
+
h = hashlib.sha256()
|
| 28 |
+
with open(p, "rb") as f:
|
| 29 |
+
for b in iter(lambda: f.read(1 << 24), b""):
|
| 30 |
+
h.update(b)
|
| 31 |
+
return h.hexdigest()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def main() -> int:
|
| 35 |
+
man = json.loads((OUT / "MANIFEST.json").read_text())
|
| 36 |
+
build = json.loads((OUT / "cells_full.BUILD.json").read_text())
|
| 37 |
+
if sha(OUT / "cells_full.npz") != build["sha256"]:
|
| 38 |
+
raise SystemExit("cells_full.npz differs from its BUILD record")
|
| 39 |
+
prep = json.loads((OUT / "PREPARE.json").read_text())
|
| 40 |
+
if prep["features_sha256"] != man["outputs"]["features.npz"]["sha256"]:
|
| 41 |
+
raise SystemExit("PREPARE.json was made from a different features.npz")
|
| 42 |
+
for name, rec in man["outputs"].items():
|
| 43 |
+
if sha(OUT / name) != rec["sha256"]:
|
| 44 |
+
raise SystemExit(f"{name} changed after assembly")
|
| 45 |
+
folds = pd.read_csv(OUT / "folds.csv")
|
| 46 |
+
sanity = json.loads((RUN / "SANITY.json").read_text())
|
| 47 |
+
man["post_assembly"] = {
|
| 48 |
+
"written_utc": datetime.now(timezone.utc).isoformat(),
|
| 49 |
+
"cells_full": {**build, "bytes": (OUT / "cells_full.npz").stat().st_size},
|
| 50 |
+
"prepare_dataset": {"command": "CUDA_VISIBLE_DEVICES='' python tools/prepare_dataset.py --dataset liu2021 (cxg_corpus env, bounded systemd unit)",
|
| 51 |
+
"tool_sha256": sha(TASK / "tools/prepare_dataset.py"),
|
| 52 |
+
"PREPARE.json_sha256": sha(OUT / "PREPARE.json"), "folds.csv_sha256": sha(OUT / "folds.csv"),
|
| 53 |
+
"fold_sizes": prep["fold_sizes"],
|
| 54 |
+
"usable_rows": int((folds.fold >= 0).sum()),
|
| 55 |
+
"rows_in_fold_minus1": folds[folds.fold == -1].sample_id.tolist(),
|
| 56 |
+
"donors_in_folds": int(folds[folds.fold >= 0].donor_id.nunique()),
|
| 57 |
+
"donors_split_across_folds": int((folds[folds.fold >= 0].groupby("donor_id").fold.nunique() > 1).sum())},
|
| 58 |
+
"sanity_bulk_vs_pseudobulk": {"definition": sanity["definition"],
|
| 59 |
+
**{ds: {k: v for k, v in rec.items() if k != "per_row"} for ds, rec in sanity["datasets"].items()}},
|
| 60 |
+
"hto_negative_sensitivity": json.loads((RUN / "identity/HTO_NEGATIVE_SENSITIVITY.json").read_text()),
|
| 61 |
+
"code": {name: {"path": str(p), "sha256": sha(p)} for name, p in [
|
| 62 |
+
("full_cells", RUN / "code/liu2021_full_cells.py"), ("findings", RUN / "code/liu2021_findings.py"),
|
| 63 |
+
("sanity", RUN / "code/liu2021_sanity.py"), ("hto_sensitivity", RUN / "code/liu2021_hto_sensitivity.py"),
|
| 64 |
+
("run_step", RUN / "code/run_step.sh"), ("finalize", Path(__file__).resolve())]},
|
| 65 |
+
}
|
| 66 |
+
(OUT / "MANIFEST.json").write_text(json.dumps(man, indent=1, default=str) + "\n")
|
| 67 |
+
print(json.dumps(man["post_assembly"]["prepare_dataset"], indent=1))
|
| 68 |
+
return 0
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/2e9f4baf0e18957c/liu2021_findings.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Study-level findings for the Liu 2021 build (CPU only): bulk material and protocol, sc chemistry, author filtering
|
| 3 |
+
in the Seurat object, cell selection (sorted / HTO doublet / HTO negative), why the corpus copy was not used (with a
|
| 4 |
+
numeric spot-check against CELLxGENE raw counts), gene coverage, bulk depth, pairing. Writes
|
| 5 |
+
processing/liu2021_v1_20261002/FINDINGS.json."""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
from collections import Counter
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import h5py
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 18 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 19 |
+
RUN = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/liu2021_v1_20261002")
|
| 20 |
+
OUT = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/liu2021")
|
| 21 |
+
REF = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/canonical_genes.tsv")
|
| 22 |
+
POS = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy")
|
| 23 |
+
CXG_DIR = Path("/home/sj_server_1/gblee/datalake/single-cell-RNA-seq-datasets/PBMC-cells/"
|
| 24 |
+
"202_B_GSE161918_Time-resolved_Systems_Immunology_Reveals_a_Late_Juncture_Linked_to_Fatal_COVID-1")
|
| 25 |
+
CORPUS = Path("/home/sj_server_1/PBISC/PBISC-data/single-cell-data-block-blood")
|
| 26 |
+
EXPORT = RUN / "rds_export"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def text(v) -> np.ndarray:
|
| 30 |
+
return np.asarray([x.decode() if isinstance(x, bytes) else str(x) for x in v])
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def main() -> None:
|
| 34 |
+
soft = pd.read_csv(RUN / "pairing/GSE161918_samples.csv", dtype=str, keep_default_na=False)
|
| 35 |
+
bulk_gsm = soft[soft.Sample_title.str.contains("bulk", case=False)]
|
| 36 |
+
sc_gsm = soft[~soft.Sample_title.str.contains("bulk", case=False)]
|
| 37 |
+
cells = pd.read_parquet(RUN / "pairing/sc_cell_obs.parquet")
|
| 38 |
+
pairs = pd.read_csv(OUT / "pairs.csv")
|
| 39 |
+
f = np.load(OUT / "features.npz", allow_pickle=False)
|
| 40 |
+
folds = pd.read_csv(OUT / "folds.csv")
|
| 41 |
+
pos = np.load(POS)
|
| 42 |
+
for c in ("nCount_RNA", "nFeature_RNA", "percent.mito"):
|
| 43 |
+
cells[c] = cells[c].astype(float)
|
| 44 |
+
|
| 45 |
+
# ---------------- bulk material and protocol (GEO)
|
| 46 |
+
desc = sorted(set(bulk_gsm.Sample_description.str.split("|").str[0]))
|
| 47 |
+
bulk_material = {
|
| 48 |
+
"geo_source_name": sorted(set(bulk_gsm.Sample_source_name_ch1)),
|
| 49 |
+
"geo_unsorted_or_sorted": sorted(set(bulk_gsm["ch_unsorted or sorted t/b cells"])),
|
| 50 |
+
"geo_molecule": sorted(set(bulk_gsm.Sample_molecule_ch1)), "geo_description": desc,
|
| 51 |
+
"conclusion": ("PBMC bulk (not whole blood): every one of the 73 bulk GSMs has source 'Peripheral Blood Mononuclear "
|
| 52 |
+
"Cells' and 'Unsorted'; 100,000 PBMCs per sample in Trizol, miRNeasy micro, Illumina TruSeq "
|
| 53 |
+
"library, STAR, htseq-count 0.9.1 with the UCSC hg19 annotation. The bulk RNA of each sample was "
|
| 54 |
+
"also the SNP reference used by demuxlet to assign single cells to subjects.")}
|
| 55 |
+
# ---------------- sc chemistry
|
| 56 |
+
first = cells.groupby("Batch").BARCODE.min().to_dict()
|
| 57 |
+
sc_chem = {"geo_statement": sorted(set(sc_gsm.Sample_extract_protocol_ch1.str.split("|").str[-1].str.extract(
|
| 58 |
+
r"(10x 5. Chromium Single Cell Immune Profiling Next GEM v1\.1 chemistry)")[0].dropna())),
|
| 59 |
+
"geo_processing": sorted(set(x for v in sc_gsm.Sample_data_processing for x in v.split("|")
|
| 60 |
+
if x.startswith(("mapping", "Genome_build", "sample demultiplexing",
|
| 61 |
+
"secondary analysis")))),
|
| 62 |
+
"first_sorted_barcode_by_batch": first,
|
| 63 |
+
"barcode_suffixes": sorted({b.rsplit("-", 1)[-1] for b in cells.BARCODE.unique()}),
|
| 64 |
+
"conclusion": ("10x 5' Next GEM v1.1 CITE-seq (GEX + 192 ADT + HTO + TCR); Cell Ranger 3.1.0 with the hg19-1.2.0 "
|
| 65 |
+
"reference (32,738 genes; the Seurat RNA rownames equal this table, see reference_crosswalk). "
|
| 66 |
+
"Only the RNA counts are used.")}
|
| 67 |
+
# ---------------- author filtering present in the object
|
| 68 |
+
sel = cells[cells.selected]
|
| 69 |
+
author = {"object_cells": int(len(cells)), "object_min_nFeature_RNA": int(cells.nFeature_RNA.min()),
|
| 70 |
+
"object_max_nFeature_RNA": int(cells.nFeature_RNA.max()), "object_min_nCount_RNA": float(cells.nCount_RNA.min()),
|
| 71 |
+
"object_max_percent_mito": float(100 * cells["percent.mito"].max()),
|
| 72 |
+
"selected_cells": int(len(sel)), "selected_min_nFeature_RNA": int(sel.nFeature_RNA.min()),
|
| 73 |
+
"selected_min_nCount_RNA": float(sel.nCount_RNA.min()), "selected_max_percent_mito": float(100 * sel["percent.mito"].max()),
|
| 74 |
+
"selected_failing_conservative_rule": {"genes_lt_200": int((sel.nFeature_RNA < 200).sum()),
|
| 75 |
+
"umis_lt_500": int((sel.nCount_RNA < 500).sum()),
|
| 76 |
+
"mito_gt_20pct": int((100 * sel["percent.mito"] > 20).sum())},
|
| 77 |
+
"author_cluster_doublets_in_selected": {c: int(v) for c, v in sel.WCTcoursecelltype.value_counts().items() if c in ("Dblt", "dblt")},
|
| 78 |
+
"conclusion": ("The author object is already filtered (every cell has >= 200 genes, author percent.mito is a fraction, "
|
| 79 |
+
"max ~0.3); it still holds HTO doublets/negatives (all demuxlet singlets) and the sorted fractions. "
|
| 80 |
+
"The ImMicro rule (>=200 genes, >=500 UMIs, <=20 % mito) is applied on top. Author cluster-level "
|
| 81 |
+
"'Dblt' cells are not an HTO call and are kept (counted here).")}
|
| 82 |
+
# ---------------- cell selection
|
| 83 |
+
uns = cells[cells.Sorted == "N"]
|
| 84 |
+
b23 = uns[uns.Batch.isin(["B2", "B3"])]
|
| 85 |
+
comp = pd.crosstab(b23.WCTcoursecelltype, b23["HTO_classification.global"], normalize="columns")
|
| 86 |
+
tv = float(0.5 * (comp["Singlet"] - comp["Negative"]).abs().sum())
|
| 87 |
+
diff = (comp["Negative"] - comp["Singlet"]).sort_values()
|
| 88 |
+
selection = {
|
| 89 |
+
"by_batchsort_and_hto": pd.crosstab(cells.BatchSort, cells["HTO_classification.global"]).to_dict(),
|
| 90 |
+
"why_unsorted_only": ("The bulk is unsorted PBMC. Batch 1 lanes pool FACS-sorted B, T, CD14+ monocyte and CD14- innate "
|
| 91 |
+
"cells with unsorted PBMC 1:1:1:1:1 (sorted and unsorted fractions carry different hashtags), and "
|
| 92 |
+
"batches 2-3 have separate lanes of sorted non-naive T and B cells. Sorted cells would distort the "
|
| 93 |
+
"composition, so only Sorted == 'N' cells are used. Consequence: batch-1 samples keep only ~120-490 "
|
| 94 |
+
"cells each."),
|
| 95 |
+
"hto_negative_composition_b2_b3_unsorted": {
|
| 96 |
+
"total_variation_singlet_vs_negative": tv,
|
| 97 |
+
"cell_types_more_frequent_among_negatives": diff.tail(5).round(4).to_dict(),
|
| 98 |
+
"cell_types_less_frequent_among_negatives": diff.head(5).round(4).to_dict(),
|
| 99 |
+
"note": ("HTO 'Negative' cells concentrate in weakly stained pools (B2 HTO3, B3 HTO5: 30-70 % of a sample). "
|
| 100 |
+
"They are dropped per the task rule (their timepoint was assigned by the authors from the max, "
|
| 101 |
+
"below-threshold hashtag); this total-variation distance measures how much their author cell-type "
|
| 102 |
+
"mix differs from the singlets'.")},
|
| 103 |
+
"paired_rows_dropped": {"sorted_cells": int(pairs.n_sorted_dropped.sum()), "hto_doublets": int(pairs.n_hto_doublet_dropped.sum()),
|
| 104 |
+
"hto_negatives": int(pairs.n_hto_negative_dropped.sum()),
|
| 105 |
+
"hto_negative_fraction_of_unsorted_max": float((pairs.n_hto_negative_dropped / pairs.n_unsorted).max()),
|
| 106 |
+
"rows_with_negative_fraction_gt_0.3": int(((pairs.n_hto_negative_dropped / pairs.n_unsorted) > 0.3).sum())}}
|
| 107 |
+
# ---------------- why the corpus / CELLxGENE copy was not used, plus a numeric spot-check of our counts
|
| 108 |
+
exp_ids = json.loads((RUN / "singlecell/feature_axis.json").read_text())["ids"]
|
| 109 |
+
p_arr = np.fromfile(EXPORT / "rna_counts_p.int32", dtype="<i4").astype(np.int64)
|
| 110 |
+
i_arr = np.memmap(EXPORT / "rna_counts_i.int32", dtype="<i4", mode="r")
|
| 111 |
+
x_arr = np.memmap(EXPORT / "rna_counts_x.int32", dtype="<i4", mode="r")
|
| 112 |
+
by_name = pd.Series(cells.col_index.to_numpy(), index=cells.cell.to_numpy())
|
| 113 |
+
cxg, spot = {}, []
|
| 114 |
+
rng = np.random.default_rng(20261002)
|
| 115 |
+
for h5 in sorted(CXG_DIR.glob("*.h5ad")):
|
| 116 |
+
with h5py.File(h5, "r") as h:
|
| 117 |
+
idx = text(h["obs/_index"][:])
|
| 118 |
+
var = text(h["raw/var/_index"][:])
|
| 119 |
+
names = set(by_name.index)
|
| 120 |
+
inobj = np.fromiter((x in names for x in idx), dtype=bool, count=len(idx))
|
| 121 |
+
m = cells.set_index("cell").reindex(idx[inobj])
|
| 122 |
+
cxg[h5.name] = {"cells": int(len(idx)), "genes": int(len(var)), "cells_in_author_object": int(inobj.sum()),
|
| 123 |
+
"of_which_sorted": int((m.Sorted == "Y").sum()), "of_which_hto_not_singlet": int((m["HTO_classification.global"] != "Singlet").sum()),
|
| 124 |
+
"obs_has_sorted_or_hto_columns": any(k in h["obs"] for k in ("Sorted", "BatchSort", "HTO_classification.global"))}
|
| 125 |
+
ip = h["raw/X/indptr"]
|
| 126 |
+
vpos = {g: k for k, g in enumerate(var)}
|
| 127 |
+
fg = h["raw/var/feature_name"]
|
| 128 |
+
fname = (np.asarray(text(fg["categories"][:]))[fg["codes"][:]] if isinstance(fg, h5py.Group) else text(fg[:]))
|
| 129 |
+
exp_sym = json.loads((RUN / "singlecell/feature_axis.json").read_text())["symbols"]
|
| 130 |
+
for k in rng.choice(np.flatnonzero(inobj), size=4, replace=False):
|
| 131 |
+
a, b = int(ip[k]), int(ip[k + 1])
|
| 132 |
+
cv = h["raw/X/data"][a:b]; ci = h["raw/X/indices"][a:b]
|
| 133 |
+
col = int(by_name[idx[k]])
|
| 134 |
+
oi = np.asarray(i_arr[p_arr[col]:p_arr[col + 1]]); ox = np.asarray(x_arr[p_arr[col]:p_arr[col + 1]])
|
| 135 |
+
ours = {exp_ids[g]: int(v) for g, v in zip(oi, ox)}
|
| 136 |
+
theirs = {var[g]: float(v) for g, v in zip(ci, cv)}
|
| 137 |
+
shared = [g for g in ours if g in vpos]
|
| 138 |
+
# genes CELLxGENE counts under an Ensembl ID that is not in the hg19-1.2.0 table: compare by symbol
|
| 139 |
+
ours_by_sym = {exp_sym[g]: int(v) for g, v in zip(oi, ox)}
|
| 140 |
+
relabel = [{"cxg_id": g, "cxg_feature_name": str(fname[vpos[g]]), "cxg_count": theirs[g],
|
| 141 |
+
"our_count_same_symbol": ours_by_sym.get(str(fname[vpos[g]]))}
|
| 142 |
+
for g in theirs if g not in ours]
|
| 143 |
+
spot.append({"file": h5.name, "cell": idx[k], "our_umis": int(ox.sum()), "our_genes_in_cxg_var": len(shared),
|
| 144 |
+
"equal_on_shared_ids": all(theirs.get(g, 0.0) == ours[g] for g in shared),
|
| 145 |
+
"cxg_ids_not_in_hg19_table": relabel,
|
| 146 |
+
"equal_after_symbol_match": all(theirs.get(g, 0.0) == ours[g] for g in shared) and
|
| 147 |
+
all(r["cxg_count"] == r["our_count_same_symbol"] for r in relabel),
|
| 148 |
+
"cxg_umis": float(cv.sum()), "our_umis_on_cxg_genes": int(sum(ours[g] for g in shared))})
|
| 149 |
+
corpus = {}
|
| 150 |
+
for pq in sorted((CORPUS / "metadata/obs_sc.parquet").glob("202_B_GSE161918*.parquet")):
|
| 151 |
+
o = pd.read_parquet(pq, columns=["cell_id", "donor_id", "timepoint", "qc_status"])
|
| 152 |
+
corpus[pq.name] = {"rows": int(len(o)), "has_barcode_column": False, "qc_status": o.qc_status.value_counts().to_dict(),
|
| 153 |
+
"donor_timepoints": int(o[["donor_id", "timepoint"]].drop_duplicates().shape[0])}
|
| 154 |
+
source = {"used": "author Seurat object GSE161918_AllBatches_SeuratObj.rds.gz (RNA counts slot), exported unchanged in R",
|
| 155 |
+
"cellxgene_h5ad": cxg, "corpus_obs": corpus, "spot_check_cellxgene_raw_vs_our_counts": spot,
|
| 156 |
+
"conclusion": ("Not the corpus copy: the CELLxGENE files it derives from hold 372,081 of the object's 411,902 cells "
|
| 157 |
+
"on a 30,000-gene Ensembl axis, include sorted-fraction cells and HTO doublets/negatives, but carry "
|
| 158 |
+
"no Sorted / HTO-classification columns, so the unsorted HTO-singlet subset needed to match an "
|
| 159 |
+
"unsorted PBMC bulk cannot be selected there; the corpus parquet has no barcodes and its own QC. "
|
| 160 |
+
"The spot-check (8 random cells) compares the exported counts with CELLxGENE raw/X: equal on every "
|
| 161 |
+
"shared Ensembl ID, and the only extra CELLxGENE entries are genes it labels with a newer "
|
| 162 |
+
"Ensembl ID (e.g. SOD2 ENSG00000291237 vs hg19 ENSG00000112096), equal when matched by symbol; "
|
| 163 |
+
"CELLxGENE drops the remaining hg19 genes (30,000 kept), which is why our cells have more UMIs.")}
|
| 164 |
+
# ---------------- gene coverage and bulk depth
|
| 165 |
+
cg = pd.read_csv(REF, sep="\t", dtype=str)
|
| 166 |
+
rep = json.loads((RUN / "bulk/GSE161918_htseq/REPORT.json").read_text())
|
| 167 |
+
bv, sv = f["bulk_valid"][0], f["sc_valid"][0]
|
| 168 |
+
src = np.load(RUN / "bulk/bulk_source_counts.npz")
|
| 169 |
+
tot = src["counts"].sum(1)
|
| 170 |
+
paired_cols = set(pairs.bulk_count_column)
|
| 171 |
+
ptot = np.asarray([t for c, t in zip(src["sample_ids"], tot) if c in paired_cols])
|
| 172 |
+
coverage = {"bulk_canonical_measured": int(bv.sum()), "sc_canonical_measured": int(sv.sum()),
|
| 173 |
+
"pair_valid": int((bv & sv).sum()), "panel6k_bulk": int(bv[pos].sum()), "panel6k_sc": int(sv[pos].sum()),
|
| 174 |
+
"panel6k_both": int((bv & sv)[pos].sum()),
|
| 175 |
+
"bulk_mapping_summary": rep["source_gene_mapping_summary"],
|
| 176 |
+
"bulk_duplicate_target_groups_summed": rep["duplicate_target_groups_summed_counts"],
|
| 177 |
+
"bulk_has_ribosomal_and_mito_genes": bool(np.all(bv[cg.gene_symbol.str.startswith(("RPL", "RPS")).to_numpy() & sv])),
|
| 178 |
+
"note": "Unlike Giroux, the author bulk table keeps ribosomal-protein and mitochondrial genes."}
|
| 179 |
+
depth = {"assigned_reads_paired_columns": {"min": float(ptot.min()), "median": float(np.median(ptot)), "max": float(ptot.max())},
|
| 180 |
+
"by_table": {t: float(np.median([v for c, v in zip(src["sample_ids"], tot) if c in set(g.bulk_column)]))
|
| 181 |
+
for t, g in pd.read_csv(RUN / "pairing/bulk_count_columns.csv").groupby("table_file")}}
|
| 182 |
+
usable = folds.fold >= 0
|
| 183 |
+
findings = {
|
| 184 |
+
"bulk_material_and_protocol": bulk_material, "sc_chemistry": sc_chem, "author_filtering": author,
|
| 185 |
+
"cell_selection": selection, "sc_source_choice": source, "gene_coverage": coverage, "bulk_depth": depth,
|
| 186 |
+
"pairing": json.loads((RUN / "pairing/PAIRING_SUMMARY.json").read_text()),
|
| 187 |
+
"identity": json.loads((OUT / "MANIFEST.json").read_text())["checks"],
|
| 188 |
+
"usable_rows": {"rows": int(len(folds)), "usable": int(usable.sum()),
|
| 189 |
+
"usable_by_group": folds[usable].group.value_counts().to_dict(),
|
| 190 |
+
"usable_donors_by_group": folds[usable].drop_duplicates("donor_id").group.value_counts().to_dict(),
|
| 191 |
+
"usable_by_timepoint": dict(Counter(f["timepoints"][usable.to_numpy()].astype(str))),
|
| 192 |
+
"excluded": folds[~usable].sample_id.tolist()},
|
| 193 |
+
"sanity": json.loads((RUN / "SANITY.json").read_text()) if (RUN / "SANITY.json").exists() else None,
|
| 194 |
+
"hto_negative_sensitivity": (json.loads((RUN / "identity/HTO_NEGATIVE_SENSITIVITY.json").read_text())
|
| 195 |
+
if (RUN / "identity/HTO_NEGATIVE_SENSITIVITY.json").exists() else None),
|
| 196 |
+
"cells_full": json.loads((OUT / "cells_full.BUILD.json").read_text()) if (OUT / "cells_full.BUILD.json").exists() else None,
|
| 197 |
+
}
|
| 198 |
+
(RUN / "FINDINGS.json").write_text(json.dumps(findings, indent=1, default=str) + "\n")
|
| 199 |
+
print(json.dumps({"spot": spot, "cxg": cxg, "selection_tv": tv, "coverage": {k: v for k, v in coverage.items() if k != "bulk_mapping_summary"},
|
| 200 |
+
"depth": depth, "author": author}, indent=1, default=str))
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
if __name__ == "__main__":
|
| 204 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/8a4485ba51f51c7e/liu2021_hto_sensitivity.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Sensitivity of the HTO-negative drop (CPU only; informational, changes no output file of the dataset).
|
| 3 |
+
|
| 4 |
+
For every paired row with HTO-negative unsorted cells: pseudobulks of the author's unsorted cells that pass the same
|
| 5 |
+
cell rule (>= 200 genes, >= 500 UMIs, <= 20 % mito, from the author nFeature/nCount/percent.mito, which equal the
|
| 6 |
+
bundle metrics) for (a) HTO singlets (= the dataset), (b) HTO negatives, (c) singlets + negatives. Each is compared
|
| 7 |
+
with (i) its own bulk and (ii) the subject's other paired bulks (other timepoints), by Pearson r of log1p CPM over
|
| 8 |
+
genes whose hg19 10x symbol is a row of the author bulk table (CPM over those genes in both assays).
|
| 9 |
+
Writes identity/hto_negative_sensitivity.csv and identity/HTO_NEGATIVE_SENSITIVITY.json.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import scipy.sparse as sp
|
| 20 |
+
|
| 21 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 22 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 23 |
+
RUN = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/liu2021_v1_20261002")
|
| 24 |
+
EXPORT = RUN / "rds_export"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def lcpm(v: np.ndarray) -> np.ndarray:
|
| 28 |
+
return np.log1p(v / v.sum() * 1e6)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main() -> None:
|
| 32 |
+
pairs = pd.read_csv(RUN / "pairing/pairs_primary.csv", dtype=str, keep_default_na=False)
|
| 33 |
+
cells = pd.read_parquet(RUN / "pairing/sc_cell_obs.parquet")
|
| 34 |
+
for c in ("nCount_RNA", "nFeature_RNA", "percent.mito"):
|
| 35 |
+
cells[c] = cells[c].astype(float)
|
| 36 |
+
cells["cellpass"] = (cells.nFeature_RNA >= 200) & (cells.nCount_RNA >= 500) & (100 * cells["percent.mito"] <= 20)
|
| 37 |
+
sym = json.loads((RUN / "singlecell/feature_axis.json").read_text())["symbols"]
|
| 38 |
+
src = np.load(RUN / "bulk/bulk_source_counts.npz")
|
| 39 |
+
bsym = list(src["gene_ids"])
|
| 40 |
+
bpos = {s: k for k, s in enumerate(bsym)}
|
| 41 |
+
# 10x symbols that occur once in the 10x table and are bulk rows
|
| 42 |
+
counts = pd.Series(sym).value_counts()
|
| 43 |
+
sc_idx = np.asarray([k for k, s in enumerate(sym) if counts[s] == 1 and s in bpos])
|
| 44 |
+
b_idx = np.asarray([bpos[sym[k]] for k in sc_idx])
|
| 45 |
+
bcols = {c: j for j, c in enumerate(src["sample_ids"])}
|
| 46 |
+
B = src["counts"][:, b_idx]
|
| 47 |
+
p = np.fromfile(EXPORT / "rna_counts_p.int32", dtype="<i4").astype(np.int64)
|
| 48 |
+
ind = np.memmap(EXPORT / "rna_counts_i.int32", dtype="<i4", mode="r")
|
| 49 |
+
val = np.memmap(EXPORT / "rna_counts_x.int32", dtype="<i4", mode="r")
|
| 50 |
+
|
| 51 |
+
def pseudobulk(col_index: np.ndarray) -> np.ndarray:
|
| 52 |
+
if len(col_index) == 0:
|
| 53 |
+
return np.zeros(len(sc_idx))
|
| 54 |
+
starts, stops = p[col_index], p[col_index + 1]
|
| 55 |
+
g = np.concatenate([np.arange(a, b) for a, b in zip(starts, stops)])
|
| 56 |
+
ip = np.concatenate([[0], np.cumsum(stops - starts)])
|
| 57 |
+
M = sp.csr_matrix((np.asarray(val[g], dtype=np.float64), np.asarray(ind[g]), ip), shape=(len(col_index), len(sym)))
|
| 58 |
+
return np.asarray(M[:, sc_idx].sum(0)).ravel()
|
| 59 |
+
|
| 60 |
+
rows = []
|
| 61 |
+
for _, r in pairs.iterrows():
|
| 62 |
+
c = cells[(cells.sample_id == r.sc_sample) & (cells.Sorted == "N") & cells.cellpass]
|
| 63 |
+
hto = c["HTO_classification.global"]
|
| 64 |
+
sets = {"singlet": c[hto == "Singlet"].col_index.to_numpy(np.int64),
|
| 65 |
+
"negative": c[hto == "Negative"].col_index.to_numpy(np.int64)}
|
| 66 |
+
sets["singlet_plus_negative"] = np.concatenate([sets["singlet"], sets["negative"]])
|
| 67 |
+
own = B[bcols[r.bulk_column]]
|
| 68 |
+
others = [x for x in pairs[(pairs.Subject == r.Subject) & (pairs.bulk_column != r.bulk_column)].bulk_column]
|
| 69 |
+
rec = {"sample_id": r.sample_id, "sc_sample": r.sc_sample, "batch": r.Batch, "hashtag": r.hashtags,
|
| 70 |
+
"n_singlet_pass": len(sets["singlet"]), "n_negative_pass": len(sets["negative"]),
|
| 71 |
+
"subject_other_timepoints": len(others)}
|
| 72 |
+
for name, cols in sets.items():
|
| 73 |
+
if len(cols) < 50:
|
| 74 |
+
continue
|
| 75 |
+
pb = pseudobulk(cols)
|
| 76 |
+
rec[f"r_own_{name}"] = float(np.corrcoef(lcpm(own), lcpm(pb))[0, 1])
|
| 77 |
+
if others:
|
| 78 |
+
rec[f"r_best_other_timepoint_{name}"] = max(float(np.corrcoef(lcpm(B[bcols[o]]), lcpm(pb))[0, 1]) for o in others)
|
| 79 |
+
rows.append(rec)
|
| 80 |
+
t = pd.DataFrame(rows)
|
| 81 |
+
t["negative_fraction"] = t.n_negative_pass / (t.n_singlet_pass + t.n_negative_pass)
|
| 82 |
+
t.to_csv(RUN / "identity/hto_negative_sensitivity.csv", index=False)
|
| 83 |
+
h = t[t.n_negative_pass >= 50]
|
| 84 |
+
multi = h[h.subject_other_timepoints > 0]
|
| 85 |
+
summ = {"genes": int(len(sc_idx)),
|
| 86 |
+
"rows_with_>=50_negative_cells": int(len(h)),
|
| 87 |
+
"median_negative_fraction_those_rows": float(h.negative_fraction.median()),
|
| 88 |
+
"r_own_singlet_median": float(h.r_own_singlet.median()),
|
| 89 |
+
"r_own_negative_median": float(h.r_own_negative.median()),
|
| 90 |
+
"r_own_singlet_plus_negative_median": float(h.r_own_singlet_plus_negative.median()),
|
| 91 |
+
"rows_where_adding_negatives_raises_r_own": int((h.r_own_singlet_plus_negative > h.r_own_singlet).sum()),
|
| 92 |
+
"negatives_own_timepoint_beats_best_other_timepoint": f"{int((multi.r_own_negative > multi.r_best_other_timepoint_negative).sum())}/{len(multi)}",
|
| 93 |
+
"singlets_own_timepoint_beats_best_other_timepoint": f"{int((multi.r_own_singlet > multi.r_best_other_timepoint_singlet).sum())}/{len(multi)}",
|
| 94 |
+
"note": ("r over hg19 symbols shared by the 10x table (unique) and the bulk table; informational only - the "
|
| 95 |
+
"dataset keeps the task rule (HTO singlets only)")}
|
| 96 |
+
(RUN / "identity/HTO_NEGATIVE_SENSITIVITY.json").write_text(json.dumps(summ, indent=1) + "\n")
|
| 97 |
+
print(json.dumps(summ, indent=1))
|
| 98 |
+
print(h.round(4).to_string())
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/981b08078aab70e8/liu2021_full_cells.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""cells_full.npz for liu2021: tools/build_full_cells.py semantics with bounded memory (CPU only).
|
| 3 |
+
|
| 4 |
+
Uses build_full_cells.read_library (the tool's own reader) for every library and applies the tool's fail-closed
|
| 5 |
+
checks: cells_obs rows == cells_panel6k rows; cells sorted by dataset row; on every row the panel columns equal
|
| 6 |
+
cells_panel6k exactly and the full-axis sums equal features.npz pseudo_raw_sum. Rows are streamed through disk
|
| 7 |
+
memmaps (one library = one row here), so peak memory is one library instead of three copies of the whole matrix.
|
| 8 |
+
Output keys, dtypes and cells_full.BUILD.json fields are those of build_full_cells.py.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import importlib.util
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
import scipy.sparse as sp
|
| 21 |
+
|
| 22 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 23 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 24 |
+
TOOL = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/tools/build_full_cells.py")
|
| 25 |
+
RUN = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/liu2021_v1_20261002")
|
| 26 |
+
DS = "liu2021"
|
| 27 |
+
spec = importlib.util.spec_from_file_location("build_full_cells", TOOL)
|
| 28 |
+
BF = importlib.util.module_from_spec(spec)
|
| 29 |
+
spec.loader.exec_module(BF)
|
| 30 |
+
BF.LIBRARY_ROOT[DS] = RUN / "singlecell"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def main() -> int:
|
| 34 |
+
d = BF.TASK / "data" / DS
|
| 35 |
+
obs = pd.read_parquet(d / "cells_obs.parquet")
|
| 36 |
+
panel = np.load(d / "cells_panel6k.npz", allow_pickle=False)
|
| 37 |
+
feat = np.load(d / "features.npz", allow_pickle=False)
|
| 38 |
+
positions = np.load(BF.POSITIONS).astype(np.int64)
|
| 39 |
+
if len(obs) != int(panel["shape"][0]):
|
| 40 |
+
raise SystemExit("cells_obs rows differ from cells_panel6k rows")
|
| 41 |
+
rs = panel["row_sample"].astype(np.int64)
|
| 42 |
+
if bool((np.diff(rs) < 0).any()):
|
| 43 |
+
raise SystemExit("cells are not sorted by dataset row")
|
| 44 |
+
if not np.array_equal(rs, obs.row_sample.to_numpy(np.int64)):
|
| 45 |
+
raise SystemExit("cells_obs row_sample differs from cells_panel6k row_sample")
|
| 46 |
+
P = sp.csr_matrix((panel["data"], panel["indices"], panel["indptr"]), shape=tuple(panel["shape"]))
|
| 47 |
+
want = np.nan_to_num(feat["pseudo_raw_sum"].astype(np.float64), nan=0.0)
|
| 48 |
+
n_rows = int(rs.max()) + 1
|
| 49 |
+
bounds = np.searchsorted(rs, np.arange(n_rows + 1))
|
| 50 |
+
root = BF.LIBRARY_ROOT[DS]
|
| 51 |
+
parts, total_nnz = [], 0
|
| 52 |
+
tmp = RUN / "full_cells_tmp"
|
| 53 |
+
tmp.mkdir(exist_ok=True)
|
| 54 |
+
bad_panel = bad_sum = 0
|
| 55 |
+
for r in range(n_rows):
|
| 56 |
+
a, b = int(bounds[r]), int(bounds[r + 1])
|
| 57 |
+
sub = obs.iloc[a:b]
|
| 58 |
+
libs = sub.library_id.unique()
|
| 59 |
+
if len(libs) != 1:
|
| 60 |
+
raise SystemExit(f"row {r}: expected one library, found {list(libs)}")
|
| 61 |
+
Xr = BF.read_library(root / str(libs[0]) / "canonical.h5ad", sub["barcode"].astype(str).to_numpy())
|
| 62 |
+
bad_panel += int((Xr[:, positions] != P[a:b]).nnz)
|
| 63 |
+
bad_sum += int(not np.array_equal(np.asarray(Xr.sum(axis=0, dtype=np.float64)).ravel(), want[r]))
|
| 64 |
+
np.save(tmp / f"{r:03d}_data.npy", Xr.data.astype(np.int32))
|
| 65 |
+
np.save(tmp / f"{r:03d}_indices.npy", Xr.indices.astype(np.int32))
|
| 66 |
+
np.save(tmp / f"{r:03d}_indptr.npy", Xr.indptr.astype(np.int64))
|
| 67 |
+
parts.append((Xr.shape[0], Xr.nnz))
|
| 68 |
+
total_nnz += Xr.nnz
|
| 69 |
+
print(f"{libs[0]}: {Xr.shape[0]} cells", flush=True)
|
| 70 |
+
del Xr
|
| 71 |
+
if bad_panel:
|
| 72 |
+
raise SystemExit(f"full-axis cells differ from cells_panel6k on the panel columns ({bad_panel} entries)")
|
| 73 |
+
if bad_sum:
|
| 74 |
+
raise SystemExit(f"per-row full-axis sums differ from pseudo_raw_sum for {bad_sum} rows")
|
| 75 |
+
n_cells = sum(c for c, _ in parts)
|
| 76 |
+
if n_cells != len(obs):
|
| 77 |
+
raise SystemExit("assembled cell count differs")
|
| 78 |
+
data = np.lib.format.open_memmap(tmp / "all_data.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
|
| 79 |
+
indices = np.lib.format.open_memmap(tmp / "all_indices.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
|
| 80 |
+
indptr = np.empty(n_cells + 1, dtype=np.int64)
|
| 81 |
+
indptr[0] = 0
|
| 82 |
+
at = cell_at = 0
|
| 83 |
+
for r in range(n_rows):
|
| 84 |
+
dd = np.load(tmp / f"{r:03d}_data.npy"); ix = np.load(tmp / f"{r:03d}_indices.npy")
|
| 85 |
+
ip = np.load(tmp / f"{r:03d}_indptr.npy")
|
| 86 |
+
data[at:at + len(dd)] = dd
|
| 87 |
+
indices[at:at + len(dd)] = ix
|
| 88 |
+
indptr[cell_at + 1:cell_at + len(ip)] = ip[1:] + at
|
| 89 |
+
at += len(dd); cell_at += len(ip) - 1
|
| 90 |
+
if at != total_nnz or cell_at != n_cells or indptr[-1] != total_nnz or bool((np.diff(indptr) < 0).any()):
|
| 91 |
+
raise SystemExit("assembly size / indptr")
|
| 92 |
+
data.flush(); indices.flush()
|
| 93 |
+
out = d / "cells_full.npz"
|
| 94 |
+
part = d / "cells_full.npz.partial"
|
| 95 |
+
with open(part, "wb") as h:
|
| 96 |
+
np.savez(h, data=data, indices=indices, indptr=indptr, shape=np.array([n_cells, 20097], dtype=np.int64),
|
| 97 |
+
row_sample=rs.astype(np.int32))
|
| 98 |
+
os.replace(part, out)
|
| 99 |
+
del data, indices
|
| 100 |
+
# re-open the written file and re-run the row checks on it (fail-closed on the artifact itself)
|
| 101 |
+
z = np.load(out, allow_pickle=False, mmap_mode=None)
|
| 102 |
+
for k, dt in (("data", np.int32), ("indices", np.int32), ("indptr", np.int64), ("shape", np.int64), ("row_sample", np.int32)):
|
| 103 |
+
if z[k].dtype != dt:
|
| 104 |
+
raise SystemExit(f"{k} dtype {z[k].dtype}")
|
| 105 |
+
X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=tuple(z["shape"]))
|
| 106 |
+
for r in range(n_rows):
|
| 107 |
+
a, b = int(bounds[r]), int(bounds[r + 1])
|
| 108 |
+
Xr = X[a:b]
|
| 109 |
+
if (Xr[:, positions] != P[a:b]).nnz or not np.array_equal(np.asarray(Xr.sum(axis=0, dtype=np.float64)).ravel(), want[r]):
|
| 110 |
+
raise SystemExit(f"row {r}: written cells_full.npz fails the checks")
|
| 111 |
+
del X, z
|
| 112 |
+
for q in tmp.iterdir():
|
| 113 |
+
q.unlink()
|
| 114 |
+
tmp.rmdir()
|
| 115 |
+
info = {"dataset": DS, "n_cells": int(n_cells), "nnz": int(total_nnz), "sha256": BF.sha(out),
|
| 116 |
+
"checks": {"panel_columns_equal_cells_panel6k": True, "row_sums_equal_pseudo_raw_sum": True},
|
| 117 |
+
"builder": "processing/liu2021_v1_20261002/code/liu2021_full_cells.py (build_full_cells.read_library, same checks, streamed; re-verified on the written file)"}
|
| 118 |
+
(d / "cells_full.BUILD.json").write_text(json.dumps(info, indent=1))
|
| 119 |
+
print(json.dumps(info))
|
| 120 |
+
return 0
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
if __name__ == "__main__":
|
| 124 |
+
sys.exit(main())
|