peeters 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- peeters/__init__.py +14 -0
- peeters/analysis.py +327 -0
- peeters/differential.py +180 -0
- peeters/gating.py +624 -0
- peeters/heatmap.py +298 -0
- peeters/plots.py +246 -0
- peeters/style.py +77 -0
- peeters-0.1.0.dist-info/METADATA +80 -0
- peeters-0.1.0.dist-info/RECORD +12 -0
- peeters-0.1.0.dist-info/WHEEL +5 -0
- peeters-0.1.0.dist-info/licenses/LICENSE +21 -0
- peeters-0.1.0.dist-info/top_level.txt +1 -0
peeters/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""peeters: FlowSOM on flow cytometry populations gated in ALN, and differential abundance
|
|
2
|
+
between conditions, drawn on the tree and as a node heatmap.
|
|
3
|
+
|
|
4
|
+
Named after Clara Peeters (1594 to after 1657), the Antwerp painter of still lifes.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .analysis import Result, inputs, load, load_model, run, save_model
|
|
8
|
+
from .differential import differential, plot_differential
|
|
9
|
+
from .gating import Prepared, load_gating, masks, read_fcs
|
|
10
|
+
from .heatmap import node_heatmap
|
|
11
|
+
|
|
12
|
+
__all__ = ["Prepared", "Result", "differential", "inputs", "load", "load_gating",
|
|
13
|
+
"load_model", "masks", "node_heatmap", "plot_differential", "read_fcs", "run",
|
|
14
|
+
"save_model"]
|
peeters/analysis.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""FlowSOM on one gated population of many FCS files, and what each file has of every
|
|
2
|
+
(meta)cluster: the numbers a comparison of conditions starts from.
|
|
3
|
+
|
|
4
|
+
The recipe follows FlowSOM's own protocol (Quintelier et al., Nat Protoc 2021; the R
|
|
5
|
+
vignette and the Python package's example): compensate, transform, train on an aggregate
|
|
6
|
+
with the same number of cells from every file, metacluster the nodes, then map every
|
|
7
|
+
file's gated events onto the trained tree and count.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import pickle
|
|
14
|
+
from collections import Counter
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
from . import gating as ag
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class Input:
|
|
27
|
+
path: str
|
|
28
|
+
data: str | None = None # the FCS file's data id in ALN
|
|
29
|
+
name: str | None = None
|
|
30
|
+
sample: str | None = None
|
|
31
|
+
entry: Any = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class Result:
|
|
36
|
+
fsom: Any
|
|
37
|
+
markers: list[str]
|
|
38
|
+
extra: list[str]
|
|
39
|
+
files: pd.DataFrame # one row per file: gate counts, sample columns
|
|
40
|
+
metaclusters: pd.DataFrame # long: file x metacluster: count, percent
|
|
41
|
+
nodes: pd.DataFrame # long: file x node: count, percent
|
|
42
|
+
medians: pd.DataFrame # metacluster x marker, display units 0-1 (the trained aggregate)
|
|
43
|
+
file_medians: pd.DataFrame # long: file x metacluster x marker, data units
|
|
44
|
+
out: Path
|
|
45
|
+
params: dict = field(default_factory=dict)
|
|
46
|
+
|
|
47
|
+
def wide(self, level: str = "metaclusters", value: str = "percent") -> pd.DataFrame:
|
|
48
|
+
"""Files as rows, (meta)clusters as columns: what a per-experiment test reads."""
|
|
49
|
+
long = self.metaclusters if level == "metaclusters" else self.nodes
|
|
50
|
+
col = "metacluster" if level == "metaclusters" else "node"
|
|
51
|
+
return long.pivot(index="file", columns=col, values=value)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def inputs(g: ag.Gating, in_dir: str = "/in", only: list[str] | None = None,
|
|
55
|
+
files: dict[str, str] | None = None) -> list[Input]:
|
|
56
|
+
"""The gating's FCS files as the run has them. ``files``: {data id: path} when the
|
|
57
|
+
gating does not name its files or the inputs were renamed. Otherwise each file is
|
|
58
|
+
``/in/<name>``; a name that comes twice is ``<stem>-2<suffix>``, ``-3``..., in the order
|
|
59
|
+
the inputs were given (as ALN names them): so give the inputs in the gating's order.
|
|
60
|
+
``only``: data ids, names or samples of the files to use (default: all)."""
|
|
61
|
+
picked = [e for e in g.files
|
|
62
|
+
if not only or e.data in only or e.name in only or e.sample in only]
|
|
63
|
+
if not picked:
|
|
64
|
+
raise ValueError(f"none of the gating's files matches {only}")
|
|
65
|
+
out, seen = [], Counter()
|
|
66
|
+
for e in picked:
|
|
67
|
+
if files is not None:
|
|
68
|
+
if e.data not in files:
|
|
69
|
+
continue
|
|
70
|
+
path = files[e.data]
|
|
71
|
+
else:
|
|
72
|
+
if not e.name:
|
|
73
|
+
raise ValueError(f"the gating names no file name for {e.data}: give "
|
|
74
|
+
"files={data id: '/in/...'}")
|
|
75
|
+
seen[e.name] += 1
|
|
76
|
+
n = seen[e.name]
|
|
77
|
+
p = Path(e.name)
|
|
78
|
+
path = str(Path(in_dir) / (e.name if n == 1 else f"{p.stem}-{n}{p.suffix}"))
|
|
79
|
+
if not Path(path).exists():
|
|
80
|
+
raise FileNotFoundError(f"{path} ({e.data}) is not in the run: give it as an input")
|
|
81
|
+
out.append(Input(path, e.data, e.name, e.sample, e))
|
|
82
|
+
return out
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _samples_table(g: ag.Gating | None, samples: Any) -> tuple[pd.DataFrame | None, str | None]:
|
|
86
|
+
match = None
|
|
87
|
+
if samples is None and g is not None and g.samples:
|
|
88
|
+
root = Path(g.path).parent
|
|
89
|
+
while root.parent.name != "exp" and root.parent != root:
|
|
90
|
+
root = root.parent
|
|
91
|
+
samples, match = root / g.samples["table"], g.samples.get("match")
|
|
92
|
+
if samples is None:
|
|
93
|
+
return None, None
|
|
94
|
+
if isinstance(samples, pd.DataFrame):
|
|
95
|
+
return samples, match
|
|
96
|
+
path = Path(samples)
|
|
97
|
+
sep = "\t" if path.suffix.lower() in (".tsv", ".tab") else ","
|
|
98
|
+
return pd.read_csv(path, sep=sep, dtype=str), match
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _attach_samples(files: pd.DataFrame, table: pd.DataFrame | None, match: str | None):
|
|
102
|
+
if table is None:
|
|
103
|
+
return files
|
|
104
|
+
keys = ["data", "name", "sample", "file"]
|
|
105
|
+
cols = [match] if match else list(table.columns)
|
|
106
|
+
for col in cols:
|
|
107
|
+
values = set(table[col].dropna().astype(str))
|
|
108
|
+
for key in keys:
|
|
109
|
+
if key in files and files[key].dropna().astype(str).isin(values).all():
|
|
110
|
+
merged = files.merge(table.drop_duplicates(col), left_on=key, right_on=col,
|
|
111
|
+
how="left", suffixes=("", "_sample"))
|
|
112
|
+
return merged
|
|
113
|
+
print("samples: no column of the table matches the files' data ids, names or samples; "
|
|
114
|
+
"not joined")
|
|
115
|
+
return files
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def run(gating: str | Path | None, population: str | None, markers: list[str], *,
|
|
119
|
+
extra: list[str] = (), files: dict[str, str] | list[str] | None = None,
|
|
120
|
+
only: list[str] | None = None, samples: Any = None, out: str | Path = "/out/flowsom",
|
|
121
|
+
per_file: int = 20000, xdim: int = 10, ydim: int = 10, metaclusters: int = 12,
|
|
122
|
+
seed: int = 42, by: str | None = None, in_dir: str = "/in",
|
|
123
|
+
plots: bool = True) -> Result:
|
|
124
|
+
"""Cluster ``population`` of the gating's files on ``markers`` (detectors or marker
|
|
125
|
+
names) and count every file's events per node and metacluster.
|
|
126
|
+
|
|
127
|
+
``gating``: the experiment's gating file (``/exp/<id>/gating/x.gating.yaml``), whose
|
|
128
|
+
compensation, scales and gates are used; ``None`` with ``files`` a list of paths takes
|
|
129
|
+
every event of those files (already gated exports), compensated by their spillover,
|
|
130
|
+
on ALN's default scales. ``extra``: markers not clustered on, of which medians per
|
|
131
|
+
file and metacluster are reported (activation, reporters). ``per_file``: cells from
|
|
132
|
+
each file in the training aggregate (fewer when a file has fewer). ``samples``: a
|
|
133
|
+
table (path or DataFrame) joined to the files; default the gating's own ``samples``.
|
|
134
|
+
``by``: a column of it (genotype, treatment) the files are ordered and drawn by.
|
|
135
|
+
"""
|
|
136
|
+
rng = np.random.default_rng(seed)
|
|
137
|
+
g = ag.load_gating(gating) if gating is not None else None
|
|
138
|
+
if g is not None:
|
|
139
|
+
ins = inputs(g, in_dir, only, files if isinstance(files, dict) else None)
|
|
140
|
+
else:
|
|
141
|
+
if not isinstance(files, list):
|
|
142
|
+
raise ValueError("without a gating give files=[paths]")
|
|
143
|
+
ins = [Input(str(p), name=Path(p).name) for p in files]
|
|
144
|
+
if population is not None:
|
|
145
|
+
raise ValueError("a population needs a gating")
|
|
146
|
+
out = Path(out)
|
|
147
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
148
|
+
|
|
149
|
+
names = list(markers) + [m for m in extra if m not in markers]
|
|
150
|
+
labels: list[str] | None = None
|
|
151
|
+
gated: list[np.ndarray] = [] # display units, events x names
|
|
152
|
+
scales: list[list[ag.Scale]] = []
|
|
153
|
+
rows = []
|
|
154
|
+
for k, inp in enumerate(ins, 1):
|
|
155
|
+
ev = ag.read_fcs(inp.path)
|
|
156
|
+
p = ag.Prepared(g, inp.entry, ev)
|
|
157
|
+
if g is not None and population is not None:
|
|
158
|
+
ms = ag.masks(p, {population})
|
|
159
|
+
mask = ms[population]
|
|
160
|
+
counts = {f"count {n}": int(m.sum()) for n, m in ms.items()}
|
|
161
|
+
else:
|
|
162
|
+
mask = np.ones(ev.n, dtype=bool)
|
|
163
|
+
counts = {}
|
|
164
|
+
idx = [ev.index(m) for m in names]
|
|
165
|
+
these = [ev.label(i) for i in idx]
|
|
166
|
+
if labels is None:
|
|
167
|
+
labels = these
|
|
168
|
+
elif these != labels:
|
|
169
|
+
print(f"note: {Path(inp.path).name} names the channels {these}, the first file "
|
|
170
|
+
f"{labels}; columns follow the order asked")
|
|
171
|
+
x = np.column_stack([p.display(i)[mask] for i in idx]).astype(np.float32)
|
|
172
|
+
gated.append(x)
|
|
173
|
+
scales.append([p.scale(i) for i in idx])
|
|
174
|
+
rows.append({"file": inp.name or Path(inp.path).name, "path": inp.path,
|
|
175
|
+
"data": inp.data, "sample": inp.sample, "events": ev.n,
|
|
176
|
+
"population": population, "population_events": int(mask.sum()),
|
|
177
|
+
**counts, "fcs_date": ev.keywords.get("$DATE"),
|
|
178
|
+
"cytometer": ev.keywords.get("$CYT")})
|
|
179
|
+
print(f"read {k} of {len(ins)}: {rows[-1]['file']}: {int(mask.sum()):,} of "
|
|
180
|
+
f"{ev.n:,} events in {population or 'the file'}", flush=True)
|
|
181
|
+
p.drop()
|
|
182
|
+
del ev, p
|
|
183
|
+
files_df = pd.DataFrame(rows)
|
|
184
|
+
dup = files_df["file"].duplicated(keep=False) # the same file name in two runs
|
|
185
|
+
files_df.loc[dup, "file"] = [f"{f} [{d or i}]" for i, (f, d) in
|
|
186
|
+
enumerate(zip(files_df.loc[dup, "file"],
|
|
187
|
+
files_df.loc[dup, "data"]))]
|
|
188
|
+
table, match = _samples_table(g, samples)
|
|
189
|
+
files_df = _attach_samples(files_df, table, match)
|
|
190
|
+
|
|
191
|
+
# the aggregate: the same number of cells from every file
|
|
192
|
+
take = []
|
|
193
|
+
for x in gated:
|
|
194
|
+
n = min(per_file, x.shape[0])
|
|
195
|
+
take.append(x[rng.choice(x.shape[0], n, replace=False)] if n < x.shape[0] else x)
|
|
196
|
+
agg = np.concatenate(take)
|
|
197
|
+
agg_file = np.repeat(np.arange(len(gated)), [t.shape[0] for t in take])
|
|
198
|
+
if agg.shape[0] < xdim * ydim:
|
|
199
|
+
raise ValueError(f"only {agg.shape[0]} cells to train {xdim}x{ydim} nodes")
|
|
200
|
+
print(f"training FlowSOM {xdim}x{ydim}, {metaclusters} metaclusters, on {agg.shape[0]:,} "
|
|
201
|
+
f"cells ({per_file:,} per file at most), {len(markers)} markers", flush=True)
|
|
202
|
+
|
|
203
|
+
import anndata as ad
|
|
204
|
+
import flowsom as fs
|
|
205
|
+
|
|
206
|
+
adata = ad.AnnData(agg)
|
|
207
|
+
adata.var_names = labels
|
|
208
|
+
adata.var["marker"] = labels
|
|
209
|
+
adata.obs["file"] = pd.Categorical(files_df["file"].to_numpy()[agg_file])
|
|
210
|
+
cols = labels[:len(markers)]
|
|
211
|
+
fsom = fs.FlowSOM(adata, cols_to_use=cols, n_clusters=metaclusters, xdim=xdim, ydim=ydim,
|
|
212
|
+
seed=seed)
|
|
213
|
+
node_mc = np.asarray(fsom.get_cluster_data().obs["metaclustering"]).astype(int)
|
|
214
|
+
n_nodes = xdim * ydim
|
|
215
|
+
|
|
216
|
+
# every file's gated events mapped onto the tree
|
|
217
|
+
mc_rows, node_rows, med_rows = [], [], []
|
|
218
|
+
col_idx = [labels.index(c) for c in cols]
|
|
219
|
+
for k, (x, row, sc) in enumerate(zip(gated, files_df.to_dict("records"), scales)):
|
|
220
|
+
nodes = (np.asarray(fsom.model.cluster_model.predict(x[:, col_idx])).astype(int)
|
|
221
|
+
if x.shape[0] else np.zeros(0, dtype=int))
|
|
222
|
+
mcs = node_mc[nodes] if len(nodes) else nodes
|
|
223
|
+
total = max(len(nodes), 1)
|
|
224
|
+
nc = np.bincount(nodes, minlength=n_nodes)
|
|
225
|
+
mc = np.bincount(mcs, minlength=metaclusters)
|
|
226
|
+
for i in range(n_nodes):
|
|
227
|
+
node_rows.append({"file": row["file"], "node": i + 1,
|
|
228
|
+
"metacluster": int(node_mc[i]) + 1, "count": int(nc[i]),
|
|
229
|
+
"percent": 100.0 * nc[i] / total})
|
|
230
|
+
for j in range(metaclusters):
|
|
231
|
+
mc_rows.append({"file": row["file"], "metacluster": j + 1, "count": int(mc[j]),
|
|
232
|
+
"percent": 100.0 * mc[j] / total})
|
|
233
|
+
sel = mcs == j
|
|
234
|
+
for c, lab in enumerate(labels):
|
|
235
|
+
med = float(np.median(x[sel, c])) if sel.any() else np.nan
|
|
236
|
+
data = float(ag.transform(sc[c]).inverse(np.array([med]))[0]) \
|
|
237
|
+
if sel.any() else np.nan
|
|
238
|
+
med_rows.append({"file": row["file"], "metacluster": j + 1, "marker": lab,
|
|
239
|
+
"clustered": lab in cols, "median": data,
|
|
240
|
+
"median_display": med})
|
|
241
|
+
metaclusters_df = pd.DataFrame(mc_rows)
|
|
242
|
+
nodes_df = pd.DataFrame(node_rows)
|
|
243
|
+
file_medians = pd.DataFrame(med_rows)
|
|
244
|
+
|
|
245
|
+
cell_mc = np.asarray(fsom.get_cell_data().obs["metaclustering"]).astype(int)
|
|
246
|
+
med = pd.DataFrame(agg, columns=labels).groupby(cell_mc + 1).median()
|
|
247
|
+
med.index.name = "metacluster"
|
|
248
|
+
med.insert(0, "cells_in_aggregate", pd.Series(cell_mc + 1).value_counts().sort_index())
|
|
249
|
+
group_cols = [c for c in files_df.columns if c not in rows[0]]
|
|
250
|
+
|
|
251
|
+
params = {"gating": str(gating) if gating else None, "population": population,
|
|
252
|
+
"markers": cols, "extra": labels[len(markers):], "per_file": per_file,
|
|
253
|
+
"xdim": xdim, "ydim": ydim, "metaclusters": metaclusters, "seed": seed,
|
|
254
|
+
"by": by, "files": len(ins), "aggregate_cells": int(agg.shape[0]),
|
|
255
|
+
"scales": {lab: {"kind": s.kind, **s.p} for lab, s in zip(labels, scales[0])},
|
|
256
|
+
"flowsom": getattr(fs, "__version__", None)}
|
|
257
|
+
res = Result(fsom, cols, labels[len(markers):], files_df, metaclusters_df, nodes_df, med,
|
|
258
|
+
file_medians, out, params)
|
|
259
|
+
files_df.to_csv(out / "files.csv", index=False)
|
|
260
|
+
metaclusters_df.merge(files_df[["file", *group_cols]], on="file") \
|
|
261
|
+
.to_csv(out / "metaclusters.csv", index=False)
|
|
262
|
+
nodes_df.to_csv(out / "nodes.csv", index=False)
|
|
263
|
+
med.to_csv(out / "metacluster_medians.csv")
|
|
264
|
+
file_medians.to_csv(out / "file_medians.csv", index=False)
|
|
265
|
+
(out / "params.json").write_text(json.dumps(params, indent=1, default=str))
|
|
266
|
+
save_model(fsom, out / "model.pkl")
|
|
267
|
+
if plots:
|
|
268
|
+
from . import plots as pl
|
|
269
|
+
|
|
270
|
+
pl.stars(res, out / "stars.png")
|
|
271
|
+
pl.heatmap(res, out / "metacluster_heatmap.png")
|
|
272
|
+
pl.composition(res, out / "composition.png", by=by or g and g.groups)
|
|
273
|
+
if by or (g is not None and g.groups):
|
|
274
|
+
pl.groups(res, by or g.groups, out / "groups.png")
|
|
275
|
+
print(f"done: {out}", flush=True)
|
|
276
|
+
return res
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def save_model(fsom, path: str | Path) -> None:
|
|
280
|
+
"""The trained tree, as a pickle that loads again: a FlowSOM object pickled whole does
|
|
281
|
+
not (anndata's file manager fails to unpickle), so its AnnData are kept as parts."""
|
|
282
|
+
state = {k: v for k, v in vars(fsom).items() if k != "mudata"}
|
|
283
|
+
state["_mods"] = {k: {"X": m.X, "obs": m.obs, "var": m.var, "uns": dict(m.uns),
|
|
284
|
+
"obsm": dict(m.obsm)} for k, m in fsom.mudata.mod.items()}
|
|
285
|
+
with open(path, "wb") as fh:
|
|
286
|
+
pickle.dump(state, fh)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def load_model(path: str | Path):
|
|
290
|
+
"""A tree ``save_model`` wrote (``model.pkl`` of a run): ``.model.cluster_model.predict``
|
|
291
|
+
maps new cells, ``new_data`` and the plots work as on the original."""
|
|
292
|
+
import warnings
|
|
293
|
+
|
|
294
|
+
import anndata as ad
|
|
295
|
+
import flowsom as fs
|
|
296
|
+
import mudata as md
|
|
297
|
+
|
|
298
|
+
with open(path, "rb") as fh:
|
|
299
|
+
state = pickle.load(fh)
|
|
300
|
+
mods = state.pop("_mods")
|
|
301
|
+
fsom = object.__new__(fs.FlowSOM)
|
|
302
|
+
fsom.__dict__.update(state)
|
|
303
|
+
with warnings.catch_warnings():
|
|
304
|
+
warnings.simplefilter("ignore", UserWarning) # the two modalities share var names
|
|
305
|
+
fsom.mudata = md.MuData({k: ad.AnnData(**v) for k, v in mods.items()})
|
|
306
|
+
return fsom
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def load(folder: str | Path, out: str | Path | None = None) -> Result:
|
|
310
|
+
"""A run's results again from its folder (``files.csv``, ``nodes.csv``,
|
|
311
|
+
``metaclusters.csv``, ``metacluster_medians.csv``, ``file_medians.csv``, ``params.json``,
|
|
312
|
+
``model.pkl``: an earlier run's outputs given as inputs, then ``load("/in")``), to compare
|
|
313
|
+
groups or draw without training again. What is written next goes to ``out`` (default the
|
|
314
|
+
folder, or ``/out/flowsom`` for ``/in``)."""
|
|
315
|
+
folder = Path(folder)
|
|
316
|
+
out = Path(out) if out is not None else (
|
|
317
|
+
Path("/out/flowsom") if folder.parts[:2] == ("/", "in") else folder)
|
|
318
|
+
params = json.loads((folder / "params.json").read_text())
|
|
319
|
+
fsom = load_model(folder / "model.pkl")
|
|
320
|
+
files = pd.read_csv(folder / "files.csv", dtype=str)
|
|
321
|
+
for col in ("events", "population_events"):
|
|
322
|
+
files[col] = pd.to_numeric(files[col])
|
|
323
|
+
mcs = pd.read_csv(folder / "metaclusters.csv")[["file", "metacluster", "count", "percent"]]
|
|
324
|
+
medians = pd.read_csv(folder / "metacluster_medians.csv", index_col="metacluster")
|
|
325
|
+
return Result(fsom, params["markers"], params["extra"], files, mcs,
|
|
326
|
+
pd.read_csv(folder / "nodes.csv"), medians,
|
|
327
|
+
pd.read_csv(folder / "file_medians.csv"), out, params)
|
peeters/differential.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Differential abundance between two groups of files on a FlowSOM tree: which nodes (or
|
|
2
|
+
metaclusters) hold more or fewer of the population's cells in one group than in the other,
|
|
3
|
+
and the tree with a coloured band around every node that differs.
|
|
4
|
+
|
|
5
|
+
As FlowSOM's own ``GroupStats`` (R): the unit is the file (a mouse), the value its % of the
|
|
6
|
+
population in each node; per node the two groups' medians, their fold change, a
|
|
7
|
+
Wilcoxon rank-sum test (Mann-Whitney U) and Benjamini-Hochberg over the nodes tested.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import pandas as pd
|
|
17
|
+
|
|
18
|
+
#: added to both medians (percentage points) so a node empty in one group has a fold change
|
|
19
|
+
PSEUDO = 0.01
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _bh(p: np.ndarray) -> np.ndarray:
|
|
23
|
+
p = np.asarray(p, dtype=float)
|
|
24
|
+
n = len(p)
|
|
25
|
+
order = np.argsort(p)
|
|
26
|
+
ranked = p[order] * n / np.arange(1, n + 1)
|
|
27
|
+
q = np.minimum.accumulate(ranked[::-1])[::-1]
|
|
28
|
+
out = np.empty(n)
|
|
29
|
+
out[order] = np.minimum(q, 1.0)
|
|
30
|
+
return out
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _files(res, by: str, where: Any) -> pd.DataFrame:
|
|
34
|
+
files = res.files.set_index("file")
|
|
35
|
+
if by not in files:
|
|
36
|
+
raise KeyError(f"no column {by!r}; the files have {', '.join(files.columns)}")
|
|
37
|
+
if where is None:
|
|
38
|
+
return files
|
|
39
|
+
if callable(where):
|
|
40
|
+
return files[where(files)]
|
|
41
|
+
keep = np.ones(len(files), dtype=bool)
|
|
42
|
+
for col, value in where.items():
|
|
43
|
+
values = value if isinstance(value, (list, tuple, set)) else [value]
|
|
44
|
+
keep &= files[col].isin(values).to_numpy()
|
|
45
|
+
return files[keep]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _where_label(where: Any) -> str | None:
|
|
49
|
+
if where is None:
|
|
50
|
+
return None
|
|
51
|
+
if callable(where):
|
|
52
|
+
return "a subset"
|
|
53
|
+
return " · ".join("+".join(map(str, v)) if isinstance(v, (list, tuple, set)) else str(v)
|
|
54
|
+
for v in where.values())
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def differential(res, by: str, groups: tuple[str, str] | None = None, *,
|
|
58
|
+
level: str = "nodes", where: Any = None, alpha: float = 0.05,
|
|
59
|
+
min_fold: float = 1.5, out: str | Path | None = None) -> pd.DataFrame:
|
|
60
|
+
"""Compare two groups of files (``by``: a column of the files' samples, e.g. genotype;
|
|
61
|
+
``groups``: (reference, other), default the two values sorted) per node or metacluster.
|
|
62
|
+
``where``: only some files, e.g. ``{"cohort": "Exp2"}`` (or a function of the files
|
|
63
|
+
table). A unit ``differs`` when q < ``alpha`` and the medians differ at least
|
|
64
|
+
``min_fold``-fold: ``up`` = more in ``other``. Written to ``<out>/differential_<level>.csv``
|
|
65
|
+
(``out`` default: the run's folder)."""
|
|
66
|
+
from scipy.stats import mannwhitneyu
|
|
67
|
+
|
|
68
|
+
if level not in ("nodes", "metaclusters"):
|
|
69
|
+
raise ValueError("level is nodes or metaclusters")
|
|
70
|
+
files = _files(res, by, where)
|
|
71
|
+
values = [v for v in files[by].dropna().unique()]
|
|
72
|
+
if groups is None:
|
|
73
|
+
if len(values) != 2:
|
|
74
|
+
raise ValueError(f"{by} has {len(values)} values ({values}): name the two groups")
|
|
75
|
+
groups = tuple(sorted(map(str, values)))
|
|
76
|
+
ref, other = (str(g) for g in groups)
|
|
77
|
+
labels = files[by].astype(str)
|
|
78
|
+
a, b = labels[labels == ref].index, labels[labels == other].index
|
|
79
|
+
if len(a) < 2 or len(b) < 2:
|
|
80
|
+
raise ValueError(f"{ref}: {len(a)} files, {other}: {len(b)}; a test needs at least 2 each")
|
|
81
|
+
wide = res.wide(level, "percent").fillna(0.0)
|
|
82
|
+
col = "node" if level == "nodes" else "metacluster"
|
|
83
|
+
rows = []
|
|
84
|
+
for unit in wide.columns:
|
|
85
|
+
x, y = wide.loc[a, unit].to_numpy(), wide.loc[b, unit].to_numpy()
|
|
86
|
+
tested = not (np.all(x == 0) and np.all(y == 0))
|
|
87
|
+
p = float(mannwhitneyu(x, y, alternative="two-sided").pvalue) if tested else 1.0
|
|
88
|
+
mx, my = float(np.median(x)), float(np.median(y))
|
|
89
|
+
rows.append({col: int(unit), f"median {ref}": mx, f"median {other}": my,
|
|
90
|
+
f"mean {ref}": float(x.mean()), f"mean {other}": float(y.mean()),
|
|
91
|
+
"log2_fold": float(np.log2((my + PSEUDO) / (mx + PSEUDO))), "p": p,
|
|
92
|
+
"tested": tested})
|
|
93
|
+
df = pd.DataFrame(rows)
|
|
94
|
+
df["q"] = 1.0
|
|
95
|
+
t = df["tested"].to_numpy()
|
|
96
|
+
if t.any():
|
|
97
|
+
df.loc[t, "q"] = _bh(df.loc[t, "p"].to_numpy())
|
|
98
|
+
big = df["log2_fold"].abs() >= np.log2(min_fold)
|
|
99
|
+
df["direction"] = np.where((df["q"] < alpha) & big,
|
|
100
|
+
np.where(df["log2_fold"] > 0, "up", "down"), "")
|
|
101
|
+
if level == "nodes":
|
|
102
|
+
node_mc = res.nodes.drop_duplicates("node").set_index("node")["metacluster"]
|
|
103
|
+
df.insert(1, "metacluster", df["node"].map(node_mc))
|
|
104
|
+
df.attrs.update({"by": by, "reference": ref, "other": other, "level": level,
|
|
105
|
+
"alpha": alpha, "min_fold": min_fold, "n_reference": len(a),
|
|
106
|
+
"n_other": len(b), "files_reference": list(a), "files_other": list(b),
|
|
107
|
+
"where": repr(where) if where is not None else None,
|
|
108
|
+
"where_label": _where_label(where)})
|
|
109
|
+
target = Path(out) if out is not None else res.out
|
|
110
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
df.to_csv(target / f"differential_{level}.csv", index=False)
|
|
112
|
+
n_up, n_down = int((df["direction"] == "up").sum()), int((df["direction"] == "down").sum())
|
|
113
|
+
print(f"{level}: {other} ({len(b)} files) vs {ref} ({len(a)}): {n_up} up, {n_down} down "
|
|
114
|
+
f"(q < {alpha}, at least {min_fold}-fold)")
|
|
115
|
+
return df
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def plot_differential(res, diff: pd.DataFrame, path: str | Path | None = None, *,
|
|
119
|
+
view: str = "MST", stars: bool = True) -> Path:
|
|
120
|
+
"""The tree once per group, side by side: node area = the group's median %, the stars
|
|
121
|
+
the nodes' markers, and a ring around every node that differs: red = more in the other
|
|
122
|
+
group, blue = fewer, deeper = a larger fold change; the numbers name the nodes (or
|
|
123
|
+
metaclusters) that differ. From a metacluster-level ``diff`` every node of a
|
|
124
|
+
metacluster that differs takes its ring."""
|
|
125
|
+
from matplotlib.cm import ScalarMappable
|
|
126
|
+
from matplotlib.colors import Normalize
|
|
127
|
+
|
|
128
|
+
from . import plots, style
|
|
129
|
+
|
|
130
|
+
plt = plots._plt()
|
|
131
|
+
at = diff.attrs
|
|
132
|
+
ref, other, level, by = at["reference"], at["other"], at["level"], at["by"]
|
|
133
|
+
layout, _, _ = plots.tree_layout(res.fsom, view)
|
|
134
|
+
n_nodes = len(layout)
|
|
135
|
+
mcs = plots._mc_of_nodes(res)
|
|
136
|
+
if level == "nodes":
|
|
137
|
+
per = diff.set_index("node").reindex(range(1, n_nodes + 1))
|
|
138
|
+
names = {i: str(i + 1) for i in range(n_nodes)}
|
|
139
|
+
else:
|
|
140
|
+
per = diff.set_index("metacluster").reindex(mcs)
|
|
141
|
+
per.index = range(1, n_nodes + 1)
|
|
142
|
+
names = {i: f"MC{m}" for i, m in plots._mc_labels(res, layout).items()
|
|
143
|
+
for m in [mcs[i]]}
|
|
144
|
+
wide = res.wide("nodes", "percent").fillna(0.0)
|
|
145
|
+
sizes = {g: wide.loc[at[key]].median().reindex(range(1, n_nodes + 1)).fillna(0).to_numpy()
|
|
146
|
+
for g, key in ((ref, "files_reference"), (other, "files_other"))}
|
|
147
|
+
top = max(float(v.max()) for v in sizes.values()) or 1.0
|
|
148
|
+
|
|
149
|
+
lf = per["log2_fold"].to_numpy()
|
|
150
|
+
marked = (per["direction"].fillna("") != "").to_numpy()
|
|
151
|
+
lim = max(1.0, float(np.nanmax(np.abs(lf[marked]))) if marked.any() else 1.0)
|
|
152
|
+
cmap, norm = style.cmap("diverging"), Normalize(-lim, lim)
|
|
153
|
+
band = [cmap(norm(lf[i])) if marked[i] else None for i in range(n_nodes)]
|
|
154
|
+
if level == "nodes":
|
|
155
|
+
text = {i: names[i] for i in np.flatnonzero(marked)}
|
|
156
|
+
else:
|
|
157
|
+
text = {i: t for i, t in names.items() if marked[i]}
|
|
158
|
+
|
|
159
|
+
fig, axes, lax = plots._with_legend(plt, 2, res=res)
|
|
160
|
+
for ax, g in zip(axes, (ref, other)):
|
|
161
|
+
plots.draw_tree(ax, res, sizes[g], view=view, ref=top, band=band, labels=text,
|
|
162
|
+
stars=stars, labels_outside=True)
|
|
163
|
+
n = at["n_reference"] if g == ref else at["n_other"]
|
|
164
|
+
ax.set_title(f"{by} = {g} · median of {n} files", loc="left")
|
|
165
|
+
if stars:
|
|
166
|
+
plots.star_legend(lax, list(res.markers))
|
|
167
|
+
else:
|
|
168
|
+
lax.axis("off")
|
|
169
|
+
cax = fig.add_axes([0.38, 0.03, 0.24, 0.025])
|
|
170
|
+
cb = fig.colorbar(ScalarMappable(norm=norm, cmap=cmap), cax=cax, orientation="horizontal")
|
|
171
|
+
cb.outline.set_visible(False)
|
|
172
|
+
cb.ax.tick_params(labelsize=7, length=0)
|
|
173
|
+
cb.set_label(f"ring: log2 fold change, {other} vs {ref} (q < {at['alpha']}, at least "
|
|
174
|
+
f"{at['min_fold']}-fold)", fontsize=8, color=style.INK_2)
|
|
175
|
+
unit = "node" if level == "nodes" else "metacluster"
|
|
176
|
+
n_up, n_down = int(diff["direction"].eq("up").sum()), int(diff["direction"].eq("down").sum())
|
|
177
|
+
fig.suptitle(f"{other} vs {ref}: {n_up} {unit}{'' if n_up == 1 else 's'} more, "
|
|
178
|
+
f"{n_down} fewer", x=0.02, ha="left", fontsize=13)
|
|
179
|
+
path = Path(path) if path is not None else res.out / f"differential_{level}.png"
|
|
180
|
+
return plots._save(fig, path)
|