|
| 1 | +#!/usr/bin/env python |
| 2 | +"""Xie et al. 2021: cell_type_annotations.json from the authors' annotated h5ads (GEO). |
| 3 | +
|
| 4 | +The authors typed each cell (`PN_type`) at each stage, matching types across stages |
| 5 | +(Figures 5-6): the main pan-PN analysis (GSE161228_adata_all_panPN_annotated_final.h5ad) |
| 6 | +and the knot analysis (GSE161228_knot_24h_48h_adult.h5ad). One entry per analysis x |
| 7 | +stage x PN type, the authors' per-stage typed clusters. |
| 8 | +
|
| 9 | + label <clustering>_<PN type> (clustering: main_0h, ..., knot_adult) |
| 10 | + type the authors' PN type (e.g. "DA1_fru+", "VM7 or VM5v #1", "vPN") |
| 11 | + source_cluster_id the PN type |
| 12 | + unannotated cells the authors gave no type ("nan" / "NaN": held, unassigned) and |
| 13 | + types left numbered ("MARS_<n>": held, untyped) |
| 14 | + cells_by_sample cells per Sample (a main-analysis 24 h cell is in a Li 2017 sort) |
| 15 | +
|
| 16 | +Also writes .cache/xie/memberships.tsv.gz (cell<TAB>cluster) for the expression build. |
| 17 | +
|
| 18 | +Usage: |
| 19 | + uv run python projects/xie_2021/build_clusters.py |
| 20 | +""" |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import csv |
| 25 | +import gzip |
| 26 | +import json |
| 27 | +import re |
| 28 | +from collections import Counter |
| 29 | +from pathlib import Path |
| 30 | + |
| 31 | +import h5py |
| 32 | +import yaml |
| 33 | + |
| 34 | +PROJ = Path(__file__).resolve().parent |
| 35 | +REPO_ROOT = PROJ.parents[1] |
| 36 | +CACHE = REPO_ROOT / ".cache" / "xie" |
| 37 | +H5ADS = {"main": "all.h5ad", "knot": "knot_24h_48h_adult.h5ad"} # GEO GSE161228_adata_all_panPN_annotated_final / _knot_24h_48h_adult |
| 38 | +UNTYPED = re.compile(r"MARS_\d+") |
| 39 | + |
| 40 | + |
| 41 | +def obs(path: Path) -> tuple[list[str], dict[str, list[str]]]: |
| 42 | + f = h5py.File(path, "r") |
| 43 | + o = f["obs"] |
| 44 | + |
| 45 | + def col(name): |
| 46 | + v = o[name] |
| 47 | + if isinstance(v, h5py.Group): # anndata >= 0.8 categoricals |
| 48 | + cats = [c.decode() if isinstance(c, bytes) else c for c in v["categories"][:]] |
| 49 | + return [cats[c] if c >= 0 else "nan" for c in v["codes"][:]] |
| 50 | + vals = v[:] |
| 51 | + if "categories" in v.attrs: # anndata 0.7 categoricals |
| 52 | + cats = [c.decode() if isinstance(c, bytes) else c for c in o["__categories"][name][:]] |
| 53 | + return [cats[c] if c >= 0 else "nan" for c in vals] |
| 54 | + return [x.decode() if isinstance(x, bytes) else str(x) for x in vals] |
| 55 | + return [x.decode() for x in o["_index"][:]], {c: col(c) for c in ("stage", "PN_type")} |
| 56 | + |
| 57 | + |
| 58 | +def main() -> None: |
| 59 | + cfg = yaml.safe_load((PROJ / "config.yaml").read_text()) |
| 60 | + cname = {c["id"]: c["name"] for c in cfg["sample_build"]["clusterings"]} |
| 61 | + sort_of = {p: s["id"] for p, s in cfg["sample_build"]["sorts"].items()} |
| 62 | + with gzip.open(REPO_ROOT / ".cache" / "li2017" / "df_libs.csv.gz", "rt") as fh: |
| 63 | + li = {r["library"]: f"exp{r['experiment']}_GH146_24hAPF" for r in csv.DictReader(fh) |
| 64 | + if r["label"] == "GH146-GFP"} |
| 65 | + |
| 66 | + def sample_of(cell: str) -> str: |
| 67 | + if cell in li: |
| 68 | + return f"li_2017:{li[cell]}" |
| 69 | + prefix = re.sub(r"(_P\d+)?_[A-P]\d+$", "", cell) |
| 70 | + prefix = {"PN_24h_KnotGAL4": "PN_24h_KnotGAL4_GH146"}.get(prefix, prefix) |
| 71 | + return sort_of[prefix] |
| 72 | + |
| 73 | + groups: dict[tuple[str, str], list[str]] = {} |
| 74 | + for analysis, f in H5ADS.items(): |
| 75 | + cells, cols = obs(CACHE / f) |
| 76 | + for cell, stage, typ in zip(cells, cols["stage"], cols["PN_type"]): |
| 77 | + stage = stage.replace(" APF", "") |
| 78 | + groups.setdefault((f"{analysis}_{stage}", "unassigned" if typ in ("nan", "NaN") else typ), []).append(cell) |
| 79 | + |
| 80 | + order = [c["id"] for c in cfg["sample_build"]["clusterings"]] |
| 81 | + anns, membership = [], [] |
| 82 | + for cid, typ in sorted(groups, key=lambda k: (order.index(k[0]), k[1].lower())): |
| 83 | + cells = groups[(cid, typ)] |
| 84 | + label = f"{cid}_{typ}" |
| 85 | + rec = {"label": label, "type": typ, "clustering": cid, "clustering_name": cname[cid], |
| 86 | + "source_cluster_id": typ, "cell_number": len(cells), |
| 87 | + "cells_by_sample": dict(sorted(Counter(sample_of(c) for c in cells).items()))} |
| 88 | + if typ == "unassigned" or UNTYPED.fullmatch(typ): |
| 89 | + rec["unannotated"] = True |
| 90 | + anns.append(rec) |
| 91 | + membership += [(c, label) for c in cells] |
| 92 | + with gzip.open(CACHE / "memberships.tsv.gz", "wt") as fh: |
| 93 | + fh.write("barcode\tcluster\n") |
| 94 | + fh.writelines(f"{c}\t{label}\n" for c, label in membership) |
| 95 | + out = { |
| 96 | + "source": {"doi": cfg["source"]["doi"], "title": cfg["source"]["title"]}, |
| 97 | + "dataset": { |
| 98 | + "accession": cfg["dataset"]["accession"], |
| 99 | + "label_source": "authors' annotated h5ads on GEO (GSE161228): obs `PN_type` per cell and " |
| 100 | + "`stage`, main pan-PN and knot analyses", |
| 101 | + "label_level": "author type per analysis and stage", |
| 102 | + "validate_against": "paper, Figures 2, 5-6", |
| 103 | + }, |
| 104 | + "annotations": anns, |
| 105 | + } |
| 106 | + (PROJ / "cell_type_annotations.json").write_text(json.dumps(out, indent=2, ensure_ascii=False) + "\n") |
| 107 | + by = Counter(a["clustering"] for a in anns) |
| 108 | + held = sum(1 for a in anns if a.get("unannotated")) |
| 109 | + print(f"wrote {len(anns)} entries ({dict(by)}), {len(membership)} cells; {held} held") |
| 110 | + |
| 111 | + |
| 112 | +if __name__ == "__main__": |
| 113 | + main() |
0 commit comments