|
| 1 | +#!/usr/bin/env python |
| 2 | +"""Hörmann 2020: cell_type_annotations.json from the authors' per-stage clusters. |
| 3 | +
|
| 4 | +The authors clustered each stage separately and assigned each of its eight clusters to |
| 5 | +one T4/T5 subtype ("all eight single cell clusters to four T4 and four T5 subtypes in |
| 6 | +every examined developmental stage"). GEO (GSE147987) carries only the per-library |
| 7 | +matrices; the per-cell labels are the authors' as given to the Single Cell Expression |
| 8 | +Atlas (E-GEOD-147987 experiment design, "inferred cell type - authors labels"), e.g. |
| 9 | +"T4a neuron 0": the subtype, then a number 0-8 that appears to be the cross-stage |
| 10 | +integrated clustering (Fig 3D; not loaded). A cell's stage (its library) and subtype |
| 11 | +give its author cluster: one entry per stage x subtype. |
| 12 | +
|
| 13 | + label <stage>_<subtype> (e.g. 24h_T4a) |
| 14 | + type the subtype as the authors label it (e.g. "T4a neuron") |
| 15 | + clustering the stage (24h, 36h, 48h, 60h, 72h) |
| 16 | + source_cluster_id the subtype (the authors give the per-stage clusters no numbers) |
| 17 | + cells_by_library cells per GEO library (GSM title) |
| 18 | +
|
| 19 | +Also writes .cache/hormann/memberships.tsv.gz (cell<TAB>cluster, cells named |
| 20 | +<GSM title>_<10x barcode>, as in the combined matrix of combine_matrices.py) for the |
| 21 | +expression build. |
| 22 | +
|
| 23 | +Usage: |
| 24 | + uv run python projects/hormann_2020/build_clusters.py |
| 25 | +""" |
| 26 | + |
| 27 | +from __future__ import annotations |
| 28 | + |
| 29 | +import csv |
| 30 | +import gzip |
| 31 | +import json |
| 32 | +import re |
| 33 | +import urllib.request |
| 34 | +import zipfile |
| 35 | +from collections import Counter |
| 36 | +from pathlib import Path |
| 37 | + |
| 38 | +import yaml |
| 39 | + |
| 40 | +PROJ = Path(__file__).resolve().parent |
| 41 | +REPO_ROOT = PROJ.parents[1] |
| 42 | +CACHE = REPO_ROOT / ".cache" / "hormann" |
| 43 | +SCEA = CACHE / "scea" |
| 44 | +SCEA_URL = "https://www.ebi.ac.uk/gxa/sc/experiment/E-GEOD-147987/download" |
| 45 | +AUTHOR_COL = "Factor Value[inferred cell type - authors labels]" |
| 46 | + |
| 47 | + |
| 48 | +def fetch_scea() -> None: |
| 49 | + """The SCEA experiment design (per-cell labels) and MAGE-TAB (SDRF), cached.""" |
| 50 | + SCEA.mkdir(parents=True, exist_ok=True) |
| 51 | + if not (SCEA / "design.tsv").exists(): |
| 52 | + urllib.request.urlretrieve(SCEA_URL + "?fileType=experiment-design&accessKey=", SCEA / "design.tsv") |
| 53 | + if not (SCEA / "E-GEOD-147987.sdrf.txt").exists(): |
| 54 | + urllib.request.urlretrieve(SCEA_URL + "/zip?fileType=experiment-metadata&accessKey=", SCEA / "meta.zip") |
| 55 | + zipfile.ZipFile(SCEA / "meta.zip").extractall(SCEA) |
| 56 | + |
| 57 | + |
| 58 | +def main() -> None: |
| 59 | + cfg = yaml.safe_load((PROJ / "config.yaml").read_text()) |
| 60 | + names = {c["id"]: c["name"] for c in cfg["sample_build"]["clusterings"]} |
| 61 | + fetch_scea() |
| 62 | + with open(SCEA / "E-GEOD-147987.sdrf.txt", newline="") as fh: |
| 63 | + library = {r["Comment[BioSD_Sample]"]: r["Comment[Sample_title]"] |
| 64 | + for r in csv.DictReader(fh, delimiter="\t")} |
| 65 | + cells: dict[str, list[str]] = {} # cluster label -> cell names |
| 66 | + types: dict[str, str] = {} |
| 67 | + with open(SCEA / "design.tsv", newline="") as fh: |
| 68 | + for r in csv.DictReader(fh, delimiter="\t"): |
| 69 | + if not r[AUTHOR_COL]: |
| 70 | + continue # removed by the authors' filtering |
| 71 | + biosample, barcode = r["Assay"].split("-", 1) |
| 72 | + lib = library[biosample] # e.g. 24h_APF_1 |
| 73 | + stage = lib.split("_")[0] |
| 74 | + subtype = re.fullmatch(r"(T[45][a-d]) neuron \d+", r[AUTHOR_COL]).group(1) |
| 75 | + label = f"{stage}_{subtype}" |
| 76 | + types[label] = f"{subtype} neuron" |
| 77 | + cells.setdefault(label, []).append(f"{lib}_{barcode}-1") |
| 78 | + order = {c: i for i, c in enumerate(names)} |
| 79 | + anns = [] |
| 80 | + for label in sorted(cells, key=lambda x: (order[x.split("_")[0]], x)): |
| 81 | + stage, subtype = label.split("_") |
| 82 | + libs = Counter(c.rsplit("_", 1)[0] for c in cells[label]) |
| 83 | + anns.append({ |
| 84 | + "label": label, |
| 85 | + "type": types[label], |
| 86 | + "clustering": stage, |
| 87 | + "clustering_name": names[stage], |
| 88 | + "source_cluster_id": subtype, |
| 89 | + "cell_number": len(cells[label]), |
| 90 | + "cells_by_library": dict(sorted(libs.items())), |
| 91 | + }) |
| 92 | + with gzip.open(CACHE / "memberships.tsv.gz", "wt") as fh: |
| 93 | + fh.write("barcode\tcluster\n") |
| 94 | + for label, cs in cells.items(): |
| 95 | + for c in cs: |
| 96 | + fh.write(f"{c}\t{label}\n") |
| 97 | + out = { |
| 98 | + "source": {"doi": cfg["source"]["doi"], "title": cfg["source"]["title"]}, |
| 99 | + "dataset": { |
| 100 | + "accession": cfg["dataset"]["accession"], |
| 101 | + "label_source": "the authors' per-cell labels in SCEA E-GEOD-147987 ('inferred cell " |
| 102 | + "type - authors labels': the subtype of the cell's per-stage cluster), " |
| 103 | + "with the cell's stage from its GEO library", |
| 104 | + "label_level": "author cluster (one per stage x subtype)", |
| 105 | + "validate_against": "paper (per-stage clusters assigned to the eight subtypes)", |
| 106 | + }, |
| 107 | + "annotations": anns, |
| 108 | + } |
| 109 | + (PROJ / "cell_type_annotations.json").write_text(json.dumps(out, indent=2, ensure_ascii=False) + "\n") |
| 110 | + by = Counter(a["clustering"] for a in anns) |
| 111 | + print(f"wrote {len(anns)} clusters ({dict(by)}), {sum(a['cell_number'] for a in anns)} cells") |
| 112 | + |
| 113 | + |
| 114 | +if __name__ == "__main__": |
| 115 | + main() |
0 commit comments