peeters 0.1.0__tar.gz

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.
@@ -0,0 +1,9 @@
1
+ __pycache__
2
+ *.pyc
3
+ *.egg-info
4
+ .pytest_cache
5
+ .ruff_cache
6
+ .venv
7
+ dist/
8
+ build/
9
+ .secrets
peeters-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wouter Saelens
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
peeters-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: peeters
3
+ Version: 0.1.0
4
+ Summary: FlowSOM on gated flow cytometry populations, differential abundance between conditions, and its figures
5
+ Author-email: Wouter Saelens <wouter.saelens@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/instantomics/peeters
8
+ Project-URL: Bug Tracker, https://github.com/instantomics/peeters/issues
9
+ Keywords: bioinformatics,flow cytometry,FlowSOM,differential abundance
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
12
+ Requires-Python: >=3.11
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: anndata>=0.10
16
+ Requires-Dist: flowsom>=0.2.2
17
+ Requires-Dist: matplotlib>=3.8
18
+ Requires-Dist: mudata>=0.3
19
+ Requires-Dist: numpy>=1.26
20
+ Requires-Dist: pandas<3,>=2.1
21
+ Requires-Dist: pyyaml>=6
22
+ Requires-Dist: scipy>=1.12
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest; extra == "test"
25
+ Requires-Dist: ruff; extra == "test"
26
+ Dynamic: license-file
27
+
28
+ # Peeters
29
+
30
+ FlowSOM on a gated flow cytometry population over many FCS files, and differential
31
+ abundance between conditions, drawn on the FlowSOM tree and as a node heatmap.
32
+
33
+ Named after Clara Peeters (1594 to after 1657), the Antwerp painter of still lifes.
34
+
35
+ ```bash
36
+ pip install peeters
37
+ ```
38
+
39
+ ## What it does
40
+
41
+ 1. **Gate** each file as an [ALN](https://github.com/guilliottslab) gating file
42
+ (`*.gating.yaml`, format `aln-gating/1`) says: the same compensation, scales and gates
43
+ as ALN's own engine, so the counts are ALN's counts. Files that are already gated can be
44
+ given without a gating.
45
+ 2. **Cluster** the population with [FlowSOM](https://github.com/saeyslab/FlowSOM_Python):
46
+ trained on the same number of cells from every file, then every cell of every file mapped
47
+ onto the tree.
48
+ 3. **Count** each file's share of every node and metacluster, and the medians of every marker.
49
+ 4. **Compare** two groups of files per node or metacluster, as FlowSOM's `GroupStats` does:
50
+ per-file shares, Mann-Whitney test, Benjamini-Hochberg.
51
+ 5. **Draw** it: the tree with a coloured band around every node that differs, and a node
52
+ heatmap with each node as high as its share and a strip per comparison.
53
+
54
+ ## Use
55
+
56
+ ```python
57
+ from peeters import run, differential, plot_differential, node_heatmap
58
+
59
+ res = run("gating/liver.gating.yaml", "CD45+",
60
+ markers=["CD11b", "F4/80", "CD64", "Tim4", "Clec4f", "Vsig4", "Clec2", "Ly6C"],
61
+ extra=["CD45.1", "CD45.2"], # reported per metacluster, not clustered on
62
+ samples="samples.csv", by="genotype", metaclusters=12, seed=42, out="flowsom")
63
+
64
+ nodes = differential(res, "genotype", ("WT", "KO")) # reference first
65
+ mcs = differential(res, "genotype", ("WT", "KO"), level="metaclusters")
66
+ plot_differential(res, nodes) # the tree with bands
67
+
68
+ exp1 = differential(res, "genotype", ("WT", "KO"), where={"cohort": "Exp1"})
69
+ exp2 = differential(res, "genotype", ("WT", "KO"), where={"cohort": "Exp2"})
70
+ node_heatmap(res, [exp1, exp2], names={6: "KC-like"}) # a strip per cohort
71
+ ```
72
+
73
+ `run` writes `files.csv`, `metaclusters.csv`, `nodes.csv`, `metacluster_medians.csv`,
74
+ `file_medians.csv`, `params.json`, `model.pkl` and the tree, heatmap and composition
75
+ figures; `load(folder)` reads a run back without training again.
76
+
77
+ ## Release
78
+
79
+ `./dist.sh <version>` from a clean, pushed `main`: tags, builds, makes the GitHub release
80
+ and publishes to PyPI (the token in `~/.secrets/pypi.env`).
@@ -0,0 +1,53 @@
1
+ # Peeters
2
+
3
+ FlowSOM on a gated flow cytometry population over many FCS files, and differential
4
+ abundance between conditions, drawn on the FlowSOM tree and as a node heatmap.
5
+
6
+ Named after Clara Peeters (1594 to after 1657), the Antwerp painter of still lifes.
7
+
8
+ ```bash
9
+ pip install peeters
10
+ ```
11
+
12
+ ## What it does
13
+
14
+ 1. **Gate** each file as an [ALN](https://github.com/guilliottslab) gating file
15
+ (`*.gating.yaml`, format `aln-gating/1`) says: the same compensation, scales and gates
16
+ as ALN's own engine, so the counts are ALN's counts. Files that are already gated can be
17
+ given without a gating.
18
+ 2. **Cluster** the population with [FlowSOM](https://github.com/saeyslab/FlowSOM_Python):
19
+ trained on the same number of cells from every file, then every cell of every file mapped
20
+ onto the tree.
21
+ 3. **Count** each file's share of every node and metacluster, and the medians of every marker.
22
+ 4. **Compare** two groups of files per node or metacluster, as FlowSOM's `GroupStats` does:
23
+ per-file shares, Mann-Whitney test, Benjamini-Hochberg.
24
+ 5. **Draw** it: the tree with a coloured band around every node that differs, and a node
25
+ heatmap with each node as high as its share and a strip per comparison.
26
+
27
+ ## Use
28
+
29
+ ```python
30
+ from peeters import run, differential, plot_differential, node_heatmap
31
+
32
+ res = run("gating/liver.gating.yaml", "CD45+",
33
+ markers=["CD11b", "F4/80", "CD64", "Tim4", "Clec4f", "Vsig4", "Clec2", "Ly6C"],
34
+ extra=["CD45.1", "CD45.2"], # reported per metacluster, not clustered on
35
+ samples="samples.csv", by="genotype", metaclusters=12, seed=42, out="flowsom")
36
+
37
+ nodes = differential(res, "genotype", ("WT", "KO")) # reference first
38
+ mcs = differential(res, "genotype", ("WT", "KO"), level="metaclusters")
39
+ plot_differential(res, nodes) # the tree with bands
40
+
41
+ exp1 = differential(res, "genotype", ("WT", "KO"), where={"cohort": "Exp1"})
42
+ exp2 = differential(res, "genotype", ("WT", "KO"), where={"cohort": "Exp2"})
43
+ node_heatmap(res, [exp1, exp2], names={6: "KC-like"}) # a strip per cohort
44
+ ```
45
+
46
+ `run` writes `files.csv`, `metaclusters.csv`, `nodes.csv`, `metacluster_medians.csv`,
47
+ `file_medians.csv`, `params.json`, `model.pkl` and the tree, heatmap and composition
48
+ figures; `load(folder)` reads a run back without training again.
49
+
50
+ ## Release
51
+
52
+ `./dist.sh <version>` from a clean, pushed `main`: tags, builds, makes the GitHub release
53
+ and publishes to PyPI (the token in `~/.secrets/pypi.env`).
peeters-0.1.0/dist.sh ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env bash
2
+ # Release peeters: ./dist.sh <version>, from a clean main that is already pushed.
3
+ # The version comes from the git tag (setuptools_scm).
4
+ set -euo pipefail
5
+ version="${1:?usage: ./dist.sh <version>}"
6
+ test -z "$(git status --porcelain --untracked-files=no)" || { echo "commit your changes first" >&2; exit 1; }
7
+
8
+ git tag -a "v${version}" -m "v${version}"
9
+ rm -rf dist
10
+ uv build --out-dir dist
11
+ git push origin main "v${version}"
12
+ gh release create "v${version}" -t "v${version}" -n "v${version}" dist/peeters-"${version}"*
13
+
14
+ set -a; . ~/.secrets/pypi.env; set +a
15
+ uv publish dist/peeters-"${version}"*
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69", "wheel", "setuptools_scm[toml]>=8"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "peeters"
7
+ authors = [
8
+ {name = "Wouter Saelens", email = "wouter.saelens@gmail.com"},
9
+ ]
10
+ description = "FlowSOM on gated flow cytometry populations, differential abundance between conditions, and its figures"
11
+ requires-python = ">=3.11"
12
+ keywords = ["bioinformatics", "flow cytometry", "FlowSOM", "differential abundance"]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
16
+ ]
17
+ dependencies = [
18
+ "anndata>=0.10",
19
+ "flowsom>=0.2.2",
20
+ "matplotlib>=3.8",
21
+ "mudata>=0.3",
22
+ "numpy>=1.26",
23
+ # flowsom 0.2.2 writes into arrays that pandas 3 hands out read-only (clean_anndata)
24
+ "pandas>=2.1,<3",
25
+ "pyyaml>=6",
26
+ "scipy>=1.12",
27
+ ]
28
+ dynamic = ["version"]
29
+ readme = "README.md"
30
+ license = "MIT"
31
+
32
+ [project.urls]
33
+ "Homepage" = "https://github.com/instantomics/peeters"
34
+ "Bug Tracker" = "https://github.com/instantomics/peeters/issues"
35
+
36
+ [project.optional-dependencies]
37
+ test = ["pytest", "ruff"]
38
+
39
+ [tool.setuptools_scm]
40
+
41
+ [tool.ruff]
42
+ line-length = 100
43
+
44
+ [tool.ruff.lint]
45
+ select = ["E", "F", "W", "I"]
46
+
47
+ [tool.pytest.ini_options]
48
+ filterwarnings = ["ignore"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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"]
@@ -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)