|
| 1 | +import os |
| 2 | +import h5py |
| 3 | +import numpy as np |
| 4 | +import matplotlib.pyplot as plt |
| 5 | +from scipy.sparse import csr_matrix |
| 6 | + |
| 7 | +def diagnose_qc(h5ad_path, output_path, min_umis=500, min_genes=200, max_mt=0.15): |
| 8 | + print(f"Loading {h5ad_path}...") |
| 9 | + |
| 10 | + with h5py.File(h5ad_path, "r") as f: |
| 11 | + # Load barcodes and gene names |
| 12 | + barcodes = [b.decode("utf-8") if isinstance(b, bytes) else b for b in f["obs"]["_index"][:]] |
| 13 | + gene_names = [g.decode("utf-8") if isinstance(g, bytes) else g for g in f["var"]["_index"][:]] |
| 14 | + |
| 15 | + # Load expression matrix X |
| 16 | + X_group = f["X"] |
| 17 | + if isinstance(X_group, h5py.Group): |
| 18 | + data = X_group["data"][:] |
| 19 | + indices = X_group["indices"][:] |
| 20 | + indptr = X_group["indptr"][:] |
| 21 | + X = csr_matrix((data, indices, indptr), shape=(len(barcodes), len(gene_names))) |
| 22 | + else: |
| 23 | + X = f["X"][:] |
| 24 | + |
| 25 | + # Spatial coordinates (usually in obsm/spatial) |
| 26 | + if "obsm" in f and "spatial" in f["obsm"]: |
| 27 | + coords = f["obsm"]["spatial"][:] |
| 28 | + else: |
| 29 | + # Fallback if spatial not found |
| 30 | + coords = np.zeros((len(barcodes), 2)) |
| 31 | + print("Warning: Spatial coordinates not found in obsm/spatial") |
| 32 | + |
| 33 | + # Calculate QC metrics |
| 34 | + n_counts = np.array(X.sum(axis=1)).flatten() |
| 35 | + n_genes = np.array((X > 0).sum(axis=1)).flatten() |
| 36 | + |
| 37 | + # MT fraction |
| 38 | + # Robust MT detection: check for mt- or MT- anywhere, but prioritize common patterns |
| 39 | + mt_genes = [i for i, name in enumerate(gene_names) if "mt-" in name.lower() or "mt:" in name.lower()] |
| 40 | + if mt_genes: |
| 41 | + print(f"Found {len(mt_genes)} mitochondrial genes.") |
| 42 | + mt_counts = np.array(X[:, mt_genes].sum(axis=1)).flatten() |
| 43 | + pct_counts_mt = mt_counts / (n_counts + 1e-9) |
| 44 | + else: |
| 45 | + pct_counts_mt = np.zeros_like(n_counts) |
| 46 | + print("No mitochondrial genes found.") |
| 47 | + |
| 48 | + # Filter mask |
| 49 | + pass_umi = n_counts >= min_umis |
| 50 | + pass_gene = n_genes >= min_genes |
| 51 | + pass_mt = pct_counts_mt <= max_mt |
| 52 | + |
| 53 | + keep_mask = pass_umi & pass_gene & pass_mt |
| 54 | + |
| 55 | + total_spots = len(barcodes) |
| 56 | + kept_spots = np.sum(keep_mask) |
| 57 | + |
| 58 | + print(f"Total spots: {total_spots}") |
| 59 | + print(f"Kept spots: {kept_spots} ({kept_spots/total_spots:.1%})") |
| 60 | + print(f"Filtered: {total_spots - kept_spots}") |
| 61 | + print(f" - Low UMI (<{min_umis}): {np.sum(~pass_umi)}") |
| 62 | + print(f" - Low Genes (<{min_genes}): {np.sum(~pass_gene)}") |
| 63 | + print(f" - High MT (>{max_mt:.1%}): {np.sum(~pass_mt)}") |
| 64 | + |
| 65 | + # Plotting |
| 66 | + fig, axes = plt.subplots(2, 2, figsize=(15, 12)) |
| 67 | + |
| 68 | + # 1. UMI vs Genes |
| 69 | + axes[0, 0].scatter(n_counts, n_genes, c=keep_mask, cmap="RdYlGn", alpha=0.5, s=10) |
| 70 | + axes[0, 0].axvline(min_umis, color="red", linestyle="--", label=f"Min UMI={min_umis}") |
| 71 | + axes[0, 0].axhline(min_genes, color="blue", linestyle="--", label=f"Min Genes={min_genes}") |
| 72 | + axes[0, 0].set_xlabel("Total UMI counts") |
| 73 | + axes[0, 0].set_ylabel("Number of detected genes") |
| 74 | + axes[0, 0].set_title("QC: UMI vs Genes") |
| 75 | + axes[0, 0].legend() |
| 76 | + |
| 77 | + # 2. MT Fraction distribution |
| 78 | + axes[0, 1].hist(pct_counts_mt, bins=50, color="gray", alpha=0.7) |
| 79 | + axes[0, 1].axvline(max_mt, color="red", linestyle="--", label=f"Max MT={max_mt:.0%}") |
| 80 | + axes[0, 1].set_xlabel("Mitochondrial Fraction") |
| 81 | + axes[0, 1].set_ylabel("Count") |
| 82 | + axes[0, 1].set_title("QC: MT Fraction Distribution") |
| 83 | + axes[0, 1].legend() |
| 84 | + |
| 85 | + # 3. Spatial: Before (Total) |
| 86 | + axes[1, 0].scatter(coords[:, 0], coords[:, 1], c="lightgray", s=15, label="All Spots") |
| 87 | + axes[1, 0].scatter(coords[keep_mask, 0], coords[keep_mask, 1], c="green", s=15, label="Pass QC") |
| 88 | + axes[1, 0].set_title("Spatial Distribution: Kept vs Filtered") |
| 89 | + axes[1, 0].set_aspect("equal") |
| 90 | + axes[1, 0].legend() |
| 91 | + |
| 92 | + # 4. Summary Table (as text) |
| 93 | + stats_text = ( |
| 94 | + f"Sample: {os.path.basename(h5ad_path)}\n\n" |
| 95 | + f"Total Spots: {total_spots}\n" |
| 96 | + f"Kept Spots: {kept_spots} ({kept_spots/total_spots:.1%})\n" |
| 97 | + f"Filtered: {total_spots - kept_spots}\n\n" |
| 98 | + f"Thresholds:\n" |
| 99 | + f"Min UMI: {min_umis}\n" |
| 100 | + f"Min Genes: {min_genes}\n" |
| 101 | + f"Max MT: {max_mt:.0%}" |
| 102 | + ) |
| 103 | + axes[1, 1].text(0.1, 0.5, stats_text, fontsize=14, family="monospace") |
| 104 | + axes[1, 1].axis("off") |
| 105 | + |
| 106 | + plt.tight_layout() |
| 107 | + plt.savefig(output_path) |
| 108 | + print(f"Plot saved to {output_path}") |
| 109 | + |
| 110 | +if __name__ == "__main__": |
| 111 | + import argparse |
| 112 | + parser = argparse.ArgumentParser() |
| 113 | + parser.add_argument("--sample", type=str, default="MEND29") |
| 114 | + args = parser.parse_args() |
| 115 | + |
| 116 | + sample_id = args.sample |
| 117 | + h5ad_file = f"A:\\hest_data\\st\\{sample_id}.h5ad" |
| 118 | + output_file = f"qc_diagnosis_{sample_id}.png" |
| 119 | + |
| 120 | + if not os.path.exists(h5ad_file): |
| 121 | + print(f"Error: {h5ad_file} not found.") |
| 122 | + else: |
| 123 | + diagnose_qc(h5ad_file, output_file) |
0 commit comments