cell-type-annotation 0.4.2__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.
@@ -0,0 +1,239 @@
1
+ """The labels table of a level, its completeness check, and its Markdown report.
2
+
3
+ ``results/labels_<level>.csv`` is the single source of truth for a level: the call and the
4
+ reasoning behind it, one row per cluster. The report renders from it and from the evidence
5
+ tables, so re-rendering never loses reasoning, and a level is not finished while
6
+ :func:`check_level` reports problems.
7
+ """
8
+
9
+ from collections.abc import Iterable, Mapping, Sequence
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ from cell_type_annotation.checks import validate_cl_ids
15
+
16
+ #: Columns of ``results/labels_<level>.csv``. ``state`` is the orthogonal cell-state axis (normal,
17
+ #: low-quality, cycling, doublet, ...), exempt from CL ids and from nesting.
18
+ LABEL_COLUMNS = ("cluster", "label", "state", "cl_id", "confidence", "status", "rationale", "rejected")
19
+ STATUSES = ("assigned", "unknown", "needs_subcluster", "refuted")
20
+ #: Calls below this confidence are flagged for review.
21
+ LOW_CONFIDENCE = 0.6
22
+ #: What a cell without a cross-check prediction counts as.
23
+ NO_PREDICTION = "(no prediction)"
24
+
25
+
26
+ def _blank(value) -> bool:
27
+ return pd.isna(value) or not str(value).strip()
28
+
29
+
30
+ def check_level(labels: pd.DataFrame, clusters: Iterable) -> list[str]:
31
+ """What still stops a level from being complete.
32
+
33
+ A level is complete when each of its clusters has exactly one row, with a label, a status, a
34
+ rationale, a confidence in [0, 1] and a well-formed (or blank) ``cl_id``. Descend only on an
35
+ empty list, and only after the level's assumptions are signed off.
36
+
37
+ Parameters
38
+ ----------
39
+ labels
40
+ The level's labels table.
41
+ clusters
42
+ The clusters the level must cover, e.g. the categories of its cluster key.
43
+
44
+ Returns
45
+ -------
46
+ One message per problem.
47
+ """
48
+ missing = [c for c in LABEL_COLUMNS if c not in labels.columns]
49
+ if missing:
50
+ return [f"labels table is missing columns {missing}"]
51
+ problems = []
52
+ listed = labels["cluster"].astype(str).str.strip()
53
+ expected = [str(c).strip() for c in clusters]
54
+ for what, ids in (
55
+ ("without a row", [c for c in expected if c not in set(listed)]),
56
+ ("not in this level", sorted(set(listed) - set(expected))),
57
+ ("listed more than once", sorted(set(listed[listed.duplicated()]))),
58
+ ):
59
+ if ids:
60
+ problems.append(f"cluster(s) {what}: {', '.join(ids)}")
61
+ for column in ("label", "status", "rationale"):
62
+ blank = labels.loc[labels[column].map(_blank), "cluster"].astype(str).tolist()
63
+ if blank:
64
+ problems.append(f"{len(blank)} cluster(s) without a {column}: {', '.join(blank)}")
65
+ bad_status = labels.loc[~labels["status"].map(_blank) & ~labels["status"].isin(STATUSES), "cluster"]
66
+ if len(bad_status):
67
+ problems.append(f"status must be one of {list(STATUSES)}: cluster(s) {', '.join(map(str, bad_status))}")
68
+ for status, todo in (("refuted", "revise or mark Unknown"), ("needs_subcluster", "split once, then resolve")):
69
+ pending = labels.loc[labels["status"] == status, "cluster"].astype(str).tolist()
70
+ if pending:
71
+ problems.append(f"{status} call(s) still open, {todo}: cluster(s) {', '.join(pending)}")
72
+ confidence = pd.to_numeric(labels["confidence"], errors="coerce")
73
+ bad_conf = labels.loc[confidence.isna() | ~confidence.between(0, 1), "cluster"].astype(str).tolist()
74
+ if bad_conf:
75
+ problems.append(f"confidence must be a number in [0, 1]: cluster(s) {', '.join(bad_conf)}")
76
+ problems += validate_cl_ids(dict(zip(labels["cluster"].astype(str), labels["cl_id"], strict=True)))
77
+ return problems
78
+
79
+
80
+ def prediction_summary(clusters, labels, confidence=None) -> pd.DataFrame:
81
+ """Summarize a cross-check's per-cell predictions per cluster, the same way for every method.
82
+
83
+ Parameters
84
+ ----------
85
+ clusters
86
+ Cluster per cell.
87
+ labels
88
+ Predicted label per cell.
89
+ confidence
90
+ Optional per-cell confidence. Methods differ in what it means: compare it within a method,
91
+ never across methods.
92
+
93
+ Returns
94
+ -------
95
+ One row per cluster: ``top1``, ``frac1``, ``top2``, ``frac2``, ``mean_conf``. Cells without a
96
+ prediction count as ``(no prediction)``, so the fractions stay over all of a cluster's cells.
97
+ """
98
+ if isinstance(clusters, pd.Series): # align indexed inputs on cells, never by position
99
+ labels = labels.reindex(clusters.index) if isinstance(labels, pd.Series) else labels
100
+ confidence = confidence.reindex(clusters.index) if isinstance(confidence, pd.Series) else confidence
101
+ labels = pd.Series(np.asarray(labels, dtype=object))
102
+ cells = pd.DataFrame(
103
+ {
104
+ "cluster": np.asarray(clusters).astype(str),
105
+ "label": labels.where(labels.notna(), NO_PREDICTION).astype(str).to_numpy(),
106
+ "conf": np.nan if confidence is None else np.asarray(confidence, dtype=float),
107
+ }
108
+ )
109
+ rows = []
110
+ for cluster, group in cells.groupby("cluster", sort=False):
111
+ share = group["label"].value_counts(normalize=True)
112
+ rows.append(
113
+ {
114
+ "cluster": cluster,
115
+ "top1": share.index[0],
116
+ "frac1": round(float(share.iloc[0]), 3),
117
+ "top2": share.index[1] if len(share) > 1 else "",
118
+ "frac2": round(float(share.iloc[1]), 3) if len(share) > 1 else 0.0,
119
+ "mean_conf": round(float(group["conf"].mean()), 3),
120
+ }
121
+ )
122
+ return pd.DataFrame(rows, columns=["cluster", "top1", "frac1", "top2", "frac2", "mean_conf"])
123
+
124
+
125
+ def _flagged(row) -> bool:
126
+ if str(row["status"]).strip() in ("unknown", "refuted", "needs_subcluster"):
127
+ return True
128
+ if str(row["label"]).strip().lower().startswith(("unknown", "unassigned")):
129
+ return True
130
+ confidence = pd.to_numeric(row["confidence"], errors="coerce")
131
+ return bool(pd.isna(confidence) or confidence < LOW_CONFIDENCE)
132
+
133
+
134
+ def _cell(value) -> str:
135
+ if pd.isna(value):
136
+ return ""
137
+ if isinstance(value, float):
138
+ value = f"{value:.3g}"
139
+ return str(value).replace("|", "\\|").replace("\n", " ")
140
+
141
+
142
+ def _table(df: pd.DataFrame) -> str:
143
+ head = "| " + " | ".join(map(_cell, df.columns)) + " |"
144
+ rule = "| " + " | ".join("---" for _ in df.columns) + " |"
145
+ body = ["| " + " | ".join(_cell(v) for v in row) + " |" for row in df.itertuples(index=False)]
146
+ return "\n".join([head, rule, *body])
147
+
148
+
149
+ def render_level(
150
+ level: str,
151
+ labels: pd.DataFrame,
152
+ *,
153
+ sizes: Mapping[str, int],
154
+ evidence: Mapping[str, pd.DataFrame] | None = None,
155
+ figures: Sequence[str] = (),
156
+ max_rows: int = 8,
157
+ ) -> str:
158
+ """Render a level's report: an overview, the open problems, then one evidence card per cluster.
159
+
160
+ Parameters
161
+ ----------
162
+ level
163
+ Level name, e.g. ``"L2 within Neuron"``.
164
+ labels
165
+ The level's labels table.
166
+ sizes
167
+ Cells per cluster, for every cluster of the level (e.g. ``obs[cluster_key].value_counts()``);
168
+ also the clusters the completeness check expects.
169
+ evidence
170
+ Evidence tables by title, each tidy with a ``cluster`` column, already sorted and filtered
171
+ to what a reader should see (e.g. top filtered markers, the curated panel's detection,
172
+ negative-marker violations, the cross-check's top labels, QC deviation, the confidence proxy).
173
+ figures
174
+ Paths of the level's figures, relative to the report.
175
+ max_rows
176
+ Rows shown per evidence table per cluster.
177
+
178
+ Returns
179
+ -------
180
+ The report as Markdown, flagged clusters first.
181
+ """
182
+ evidence = dict(evidence or {})
183
+ sizes = {str(k): int(v) for k, v in dict(sizes).items()}
184
+ labels = labels.assign(cluster=labels["cluster"].astype(str))
185
+ flagged = labels.apply(_flagged, axis=1)
186
+ problems = check_level(labels, sizes)
187
+
188
+ lines = [f"# Level {level}", ""]
189
+ n_cells = sum(sizes.get(c, 0) for c in labels["cluster"])
190
+ lines.append(
191
+ f"{len(labels)} clusters, {labels['label'].nunique()} labels"
192
+ + (f", {n_cells:,} cells" if n_cells else "")
193
+ + f", {int(flagged.sum())} flagged for review."
194
+ )
195
+ lines += ["", "## Completeness", ""]
196
+ lines += (
197
+ [f"- {p}" for p in problems] if problems else ["Complete: every cluster has a label, status and rationale."]
198
+ )
199
+
200
+ overview = (
201
+ labels.assign(
202
+ cells=labels["cluster"].map(sizes).fillna(0).astype(int),
203
+ confidence=pd.to_numeric(labels["confidence"], errors="coerce"),
204
+ flagged=flagged,
205
+ )
206
+ .groupby("label", sort=False)
207
+ .agg(
208
+ clusters=("cluster", ", ".join),
209
+ cells=("cells", "sum"),
210
+ confidence=("confidence", "mean"),
211
+ flagged=("flagged", "sum"),
212
+ )
213
+ .sort_values(["cells", "label"], ascending=[False, True])
214
+ .reset_index()
215
+ )
216
+ if not n_cells:
217
+ overview = overview.drop(columns="cells")
218
+ lines += ["", "## Labels", "", _table(overview.round({"confidence": 2}))]
219
+
220
+ if figures:
221
+ lines += ["", "## Figures", "", *(f"- [{f}]({f})" for f in figures)]
222
+
223
+ lines += ["", "## Evidence cards"]
224
+ for _, row in labels.assign(_flag=flagged).sort_values("_flag", ascending=False, kind="stable").iterrows():
225
+ cluster = row["cluster"]
226
+ call = [f"**{row['label']}**"]
227
+ call += [f"`{row['cl_id']}`"] if not _blank(row["cl_id"]) else []
228
+ call += [f"state {row['state']}"] if not _blank(row["state"]) else []
229
+ call += [f"confidence {_cell(pd.to_numeric(row['confidence'], errors='coerce'))}", f"status {row['status']}"]
230
+ call += [f"{sizes[cluster]:,} cells"] if cluster in sizes else []
231
+ lines += ["", f"### Cluster {cluster}{' (flagged)' if row['_flag'] else ''}", "", " · ".join(call)]
232
+ lines += ["", f"**Rationale.** {_cell(row['rationale']) or '_missing_'}"]
233
+ if not _blank(row["rejected"]):
234
+ lines += ["", f"**Rejected.** {_cell(row['rejected'])}"]
235
+ for title, table in evidence.items():
236
+ rows = table[table["cluster"].astype(str) == cluster].drop(columns="cluster").head(max_rows)
237
+ if not rows.empty:
238
+ lines += ["", f"**{title}**", "", _table(rows)]
239
+ return "\n".join(lines) + "\n"
@@ -0,0 +1,371 @@
1
+ """Which one automated cross-check to run, given the query and the machine.
2
+
3
+ The ranking and every gate live here as data. ``references/method_selection.md`` renders its tables
4
+ from :func:`to_markdown`, and a test fails when the committed page drifts from it, so the page a
5
+ human reads and the answer :func:`evaluate` gives cannot disagree.
6
+
7
+ Whatever is routed here is one hypothesis to reconcile against the marker evidence, never a verdict.
8
+ Run exactly one primary cross-check, and a second only to break a tie.
9
+ """
10
+
11
+ import re
12
+ from collections.abc import Callable
13
+ from dataclasses import dataclass, field
14
+ from os import PathLike
15
+ from pathlib import Path
16
+
17
+ #: The axes a query is described on, with their allowed values.
18
+ AXES: dict[str, tuple[tuple[str, str], ...]] = {
19
+ "species": (
20
+ ("human", "Homo sapiens"),
21
+ ("mouse", "Mus musculus"),
22
+ ("other", "any other organism"),
23
+ ("unknown", "not established yet: ask before routing"),
24
+ ),
25
+ "stage": (
26
+ ("adult", "adult / postnatal primary tissue"),
27
+ ("developmental", "fetal, embryonic, or otherwise developing primary tissue"),
28
+ ("organoid", "organoid / iPSC-derived / in-vitro differentiated"),
29
+ ("unknown", "not established yet: ask before routing"),
30
+ ),
31
+ "state": (
32
+ ("normal", "healthy / untreated"),
33
+ ("disease", "non-cancer disease or perturbation"),
34
+ ("tumor", "malignant cells expected"),
35
+ ("unknown", "not established yet"),
36
+ ),
37
+ "technology": (
38
+ ("dissociated", "scRNA-seq / snRNA-seq, whole transcriptome"),
39
+ ("spatial_wt", "whole-transcriptome spatial (Visium / VisiumHD), segmented"),
40
+ ("spatial_panel", "targeted imaging panel (MERSCOPE / Xenium / CosMx), 100s of genes"),
41
+ ),
42
+ "profile": (
43
+ ("cpu", "no CUDA GPU reachable from where the step runs"),
44
+ ("gpu", "an NVIDIA CUDA GPU is reachable, here or through the scheduler"),
45
+ ),
46
+ }
47
+
48
+ #: Reference assets, as independent yes/no flags.
49
+ REFERENCES: tuple[tuple[str, str], ...] = (
50
+ ("obs_pred", "`obs` already carries a label-transfer or classifier prediction"),
51
+ ("atlas", "a labelled reference AnnData for this tissue and context"),
52
+ ("scanvi_model", "a tissue-matched scANVI model (trained, or from the scvi-tools hub)"),
53
+ ("celltypist_model", "a tissue- and stage-matched pretrained CellTypist model"),
54
+ )
55
+
56
+ #: How each axis is established.
57
+ HOW_TO_DETERMINE: dict[str, str] = {
58
+ "species": "Stage 1 intake; corroborated by the gene-ID convention.",
59
+ "stage": "Stage 1 intake. There is no data probe for this: ask, do not infer from tissue.",
60
+ "state": "Stage 1 intake for the design; QC deviation per cluster for quality and cycling.",
61
+ "technology": "A few hundred genes in `var` means a targeted panel; confirm the platform with the user.",
62
+ "profile": "Where the cross-check will run, including a GPU job submitted through the scheduler.",
63
+ "references": "`obs` listing; `celltypist.models.get_models_index(force_update=True)` filtered to the tissue.",
64
+ }
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class Route:
69
+ """One candidate cross-check: what it is, when it applies, and when it must not."""
70
+
71
+ method: str
72
+ #: How to run it, in a few words; the recipe is in ``references/method_selection.md``.
73
+ name: str
74
+ #: The situation this route is for.
75
+ when: str
76
+ #: Predicate over a context; true when the preconditions hold.
77
+ applies: Callable[[dict], bool] = field(repr=False)
78
+ #: ``(label, predicate)``; a true predicate refuses the route whatever its rank.
79
+ disqualifiers: tuple[tuple[str, Callable[[dict], bool]], ...] = field(default=(), repr=False)
80
+ why: str = ""
81
+ #: Travels with the result into the evidence cards.
82
+ caveat: str = ""
83
+
84
+
85
+ def _human_adult_normal(c: dict) -> bool:
86
+ return c["species"] == "human" and c["stage"] == "adult" and c["state"] in ("normal", "disease")
87
+
88
+
89
+ #: Shared by Azimuth and SCimilarity, so the two pan-body human models cannot drift apart.
90
+ _PAN_BODY_DISQUALIFIERS: tuple[tuple[str, Callable[[dict], bool]], ...] = (
91
+ (
92
+ "species not human, or not established (the model has a fixed human gene space)",
93
+ lambda c: c["species"] != "human",
94
+ ),
95
+ (
96
+ "developmental / organoid query (trained on adult tissue; not designed for developmental stages)",
97
+ lambda c: c["stage"] in ("developmental", "organoid"),
98
+ ),
99
+ ("tumour expected (malignant cells were excluded from training)", lambda c: c["state"] == "tumor"),
100
+ (
101
+ "stage or state not established (no data probe for either: ask before routing)",
102
+ lambda c: "unknown" in (c["stage"], c["state"]),
103
+ ),
104
+ (
105
+ "targeted imaging panel (missing panel genes are zero-filled, producing confident garbage)",
106
+ lambda c: c["technology"] == "spatial_panel",
107
+ ),
108
+ )
109
+
110
+ #: The ranking. The first route whose preconditions hold and whose disqualifiers are all false is
111
+ #: the primary cross-check; everything below it is fallback.
112
+ ROUTES: tuple[Route, ...] = (
113
+ Route(
114
+ method="obs_pred",
115
+ name="existing `obs` prediction",
116
+ when="`obs` already carries a prediction that fits this level",
117
+ applies=lambda c: c["refs"].get("obs_pred", False),
118
+ disqualifiers=(
119
+ (
120
+ "the column's provenance is unknown, or the method that produced it is itself "
121
+ "disqualified here (species / stage / tissue / panel)",
122
+ lambda c: False, # not checkable from the context; see the caveat
123
+ ),
124
+ ),
125
+ why="Free and already reconciled with the object: no recompute, no new assumptions.",
126
+ caveat=(
127
+ "It summarises someone else's prediction and inherits that method's disqualifiers. "
128
+ "Establish what produced the column before trusting it; if you cannot, treat this route "
129
+ "as unavailable."
130
+ ),
131
+ ),
132
+ Route(
133
+ method="scarches",
134
+ name="scANVI / scArches mapping",
135
+ when="a GPU AND a well-matched scANVI reference model (trained or from the hub)",
136
+ applies=lambda c: c["profile"] == "gpu" and c["refs"].get("scanvi_model", False),
137
+ disqualifiers=(
138
+ ("no CUDA GPU reachable", lambda c: c["profile"] == "cpu"),
139
+ (
140
+ "targeted imaging panel (query preparation zero-pads the reference genes the panel lacks)",
141
+ lambda c: c["technology"] == "spatial_panel",
142
+ ),
143
+ ),
144
+ why=(
145
+ "The strongest option when it fits: labels with calibrated per-cell uncertainty, in a "
146
+ "reference latent space built for this tissue. A well-matched, curated reference beats "
147
+ "any generic model."
148
+ ),
149
+ caveat="Stochastic: seed it, and still report predictions as a hypothesis.",
150
+ ),
151
+ Route(
152
+ method="reference_map",
153
+ name="CellMapper on your reference",
154
+ when="a labelled reference AnnData of your own (the user's atlas)",
155
+ applies=lambda c: c["refs"].get("atlas", False),
156
+ disqualifiers=(
157
+ (
158
+ "fewer than 30 genes shared with the query after symbol alignment",
159
+ lambda c: False, # checked when the mapping runs
160
+ ),
161
+ ),
162
+ why=(
163
+ "The user's own curated atlas for their tissue and context is usually the strongest "
164
+ "reference available, and CellMapper builds the joint embedding itself, including "
165
+ "cross-modality CCA for a targeted panel."
166
+ ),
167
+ caveat="On a targeted spatial panel this is the preferred route (cross-modality CCA).",
168
+ ),
169
+ Route(
170
+ method="celltypist",
171
+ name="CellTypist",
172
+ when="a tissue- AND stage-matched pretrained model exists",
173
+ applies=lambda c: c["refs"].get("celltypist_model", False),
174
+ disqualifiers=(
175
+ (
176
+ "no tissue- and stage-matched model: omit CellTypist rather than force an "
177
+ "ill-fitting one (a mismatched model collapses, it does not degrade gracefully)",
178
+ lambda c: not c["refs"].get("celltypist_model", False),
179
+ ),
180
+ ("targeted imaging panel (most model genes missing)", lambda c: c["technology"] == "spatial_panel"),
181
+ ),
182
+ why=(
183
+ "A genuinely matched model is a strong, nearly free cross-check trained on exactly this "
184
+ "tissue and stage, so it outranks a pan-body model. The gate is the whole point: stage "
185
+ "matters as much as tissue."
186
+ ),
187
+ caveat="Scale-sensitive: feed it log1p of counts normalized to 10,000 per cell.",
188
+ ),
189
+ Route(
190
+ method="azimuth",
191
+ name="pan-human Azimuth",
192
+ when="human, adult/postnatal, non-tumour, whole-transcriptome, and no matched reference or model above",
193
+ applies=_human_adult_normal,
194
+ disqualifiers=_PAN_BODY_DISQUALIFIERS,
195
+ why=(
196
+ "One supervised model spanning 23 human tissues, so a single reference covers a broad "
197
+ "or multi-tissue query that no tissue-specific model does. It is also the only "
198
+ "cross-check here that returns a Cell Ontology id per cluster, a calibrated confidence, "
199
+ "and trained `Unassigned` / `Doublet like cell` classes that feed the `state` axis. "
200
+ "CPU-only and cheap (~50-60k cells/min, 84 MB model)."
201
+ ),
202
+ caveat=(
203
+ "Two structural limits. (1) It cannot be constrained to a tissue: it predicts over the "
204
+ "full pan-body space, so on a single-organ query it can return a type from another "
205
+ "organ; check the winning label against the tissue. (2) For lymph node and spleen its "
206
+ "training labels came from the CellTypist organ atlases, so on immune tissue it is not "
207
+ "independent of CellTypist. Its CL ids, calibrated confidence and state signals are useful "
208
+ "however you weigh its labels, which also makes it a good tie-break below a matched model."
209
+ ),
210
+ ),
211
+ Route(
212
+ method="scimilarity",
213
+ name="SCimilarity",
214
+ when="broad / multi-tissue human adult query with no matched reference or model",
215
+ applies=_human_adult_normal,
216
+ disqualifiers=_PAN_BODY_DISQUALIFIERS
217
+ + (("under ~27 GB of usable RAM", lambda c: c["ram_gb"] is not None and c["ram_gb"] < 27),),
218
+ why=(
219
+ "An option for broad / multi-tissue human queries where no tissue-matched model exists. "
220
+ "Ranked below Azimuth because it costs far more (9 GB bundle, 16-27 GB RAM) and returns "
221
+ "a flat label space with no ontology ids, no calibrated confidence and no state signals."
222
+ ),
223
+ caveat="Zero-shot foundation model: an additional opinion, never a primary annotator.",
224
+ ),
225
+ Route(
226
+ method="census",
227
+ name="Census slice, then CellMapper",
228
+ when="nothing above fits: build a reference instead of going without one",
229
+ applies=lambda c: True,
230
+ disqualifiers=(
231
+ (
232
+ "species not human or mouse, or not established (Census holds those two)",
233
+ lambda c: c["species"] not in ("human", "mouse"),
234
+ ),
235
+ ("offline (Census is a remote TileDB store)", lambda c: False),
236
+ ),
237
+ why="Keeps a reference cross-check alive for any human or mouse tissue, so no level goes unchecked.",
238
+ caveat=(
239
+ "Census `cell_type` is author-supplied and heterogeneous across datasets, so a "
240
+ "transferred label is a coarser, noisier hypothesis than one from a curated atlas."
241
+ ),
242
+ ),
243
+ )
244
+
245
+ STATUSES = ("primary", "fallback", "skipped", "disqualified")
246
+
247
+
248
+ def default_context() -> dict:
249
+ """A context with everything unknown, so every axis has to be supplied deliberately."""
250
+ return {
251
+ "species": "unknown",
252
+ "stage": "unknown",
253
+ "state": "unknown",
254
+ "technology": "dissociated",
255
+ "profile": "cpu",
256
+ "ram_gb": None,
257
+ "refs": dict.fromkeys((k for k, _ in REFERENCES), False),
258
+ }
259
+
260
+
261
+ def evaluate(ctx: dict | None = None, /, **axes) -> list[dict]:
262
+ """Score every route against a query, in ranking order.
263
+
264
+ Parameters
265
+ ----------
266
+ ctx
267
+ A context as returned by :func:`default_context`. Keyword arguments update it, and any
268
+ reference flag (``atlas=True``) goes into ``refs``.
269
+ **axes
270
+ Axis values (``species="human"``), ``ram_gb``, or reference flags.
271
+
272
+ Returns
273
+ -------
274
+ One dict per route, ``{method, name, rank, status, reason, why, caveat}``. ``status`` is
275
+ ``primary`` (the first route that passes), ``fallback`` (passes but outranked), ``skipped``
276
+ (preconditions not met) or ``disqualified`` (a hard gate refused it). Disqualifiers are
277
+ checked first, so a refusal is always reported as such.
278
+
279
+ Raises
280
+ ------
281
+ ValueError
282
+ If an axis value or a keyword is not recognized.
283
+
284
+ Examples
285
+ --------
286
+ >>> results = evaluate(species="human", stage="adult", state="normal", technology="dissociated", profile="cpu")
287
+ >>> primary = next((r for r in results if r["status"] == "primary"), None)
288
+ """
289
+ c = default_context() if ctx is None else {**ctx, "refs": dict(ctx["refs"])}
290
+ refs = {k for k, _ in REFERENCES}
291
+ for key, value in axes.items():
292
+ if key in refs:
293
+ c["refs"][key] = bool(value)
294
+ elif key in AXES or key == "ram_gb":
295
+ c[key] = value
296
+ else:
297
+ raise ValueError(f"Unknown routing input {key!r}; expected one of {[*AXES, 'ram_gb', *refs]}")
298
+ for axis, values in AXES.items():
299
+ allowed = [v for v, _ in values]
300
+ if c[axis] not in allowed:
301
+ raise ValueError(f"{axis}={c[axis]!r} is not one of {allowed}")
302
+
303
+ out, chosen = [], False
304
+ for rank, route in enumerate(ROUTES, start=1):
305
+ blocked = [label for label, refuses in route.disqualifiers if refuses(c)]
306
+ if blocked:
307
+ status, reason = "disqualified", "; ".join(blocked)
308
+ elif not route.applies(c):
309
+ status, reason = "skipped", f"preconditions not met ({route.when})"
310
+ elif not chosen:
311
+ status, reason, chosen = "primary", route.when, True
312
+ else:
313
+ status, reason = "fallback", "outranked by a higher route that also applies"
314
+ out.append(
315
+ {
316
+ "method": route.method,
317
+ "name": route.name,
318
+ "rank": rank,
319
+ "status": status,
320
+ "reason": reason,
321
+ "why": route.why,
322
+ "caveat": route.caveat,
323
+ }
324
+ )
325
+ return out
326
+
327
+
328
+ def to_markdown() -> str:
329
+ """The generated block of ``references/method_selection.md``: axes, ranking, disqualifiers, caveats."""
330
+ lines = ["### Axes\n", "| Axis | Values | How you determine it |", "| --- | --- | --- |"]
331
+ for axis, values in AXES.items():
332
+ lines.append(f"| **{axis}** | {' · '.join(f'`{v}`' for v, _ in values)} | {HOW_TO_DETERMINE[axis]} |")
333
+ refs = " · ".join(f"`{k}`" for k, _ in REFERENCES)
334
+ lines.append(f"| **references** (flags) | {refs} | {HOW_TO_DETERMINE['references']} |")
335
+
336
+ lines += [
337
+ "\n### Ranking\n",
338
+ "Evaluated top-down. The first route whose preconditions hold and whose disqualifiers are all",
339
+ "false is the primary cross-check. A disqualifier beats rank.\n",
340
+ "| # | Method | Use when | Why here |",
341
+ "| --- | --- | --- | --- |",
342
+ ]
343
+ lines += [f"| {i} | `{r.method}`: {r.name} | {r.when} | {r.why} |" for i, r in enumerate(ROUTES, start=1)]
344
+
345
+ lines += ["\n### Disqualifiers\n", "| Method | Refused when |", "| --- | --- |"]
346
+ lines += [
347
+ f"| `{r.method}` | {'; '.join(label for label, _ in r.disqualifiers)} |" for r in ROUTES if r.disqualifiers
348
+ ]
349
+
350
+ lines.append("\n### Caveats that travel with the result\n")
351
+ lines += [f"- **`{r.method}`**: {r.caveat}" for r in ROUTES if r.caveat]
352
+ return "\n".join(lines)
353
+
354
+
355
+ _GENERATED = re.compile(r"(<!-- BEGIN GENERATED -->\n).*?(\n<!-- END GENERATED -->)", re.S)
356
+
357
+
358
+ def update_page(path: str | PathLike) -> bool:
359
+ """Regenerate the block between the ``GENERATED`` markers of the page at ``path``.
360
+
361
+ Returns
362
+ -------
363
+ Whether the page changed.
364
+ """
365
+ path = Path(path)
366
+ text = path.read_text()
367
+ if not _GENERATED.search(text):
368
+ raise ValueError(f"{path} has no <!-- BEGIN GENERATED --> ... <!-- END GENERATED --> block")
369
+ new = _GENERATED.sub(lambda m: m[1] + to_markdown() + m[2], text)
370
+ path.write_text(new)
371
+ return new != text