annotuneagent 0.1.2__tar.gz → 0.1.3__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.
Files changed (77) hide show
  1. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/CHANGELOG.md +51 -0
  2. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/CITATION.cff +2 -2
  3. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/PKG-INFO +6 -4
  4. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/README.md +4 -3
  5. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/api/index.md +1 -0
  6. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/installation.md +1 -1
  7. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/quickstart.md +6 -3
  8. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/tutorials/report.md +1 -1
  9. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/pyproject.toml +1 -0
  10. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/__init__.py +2 -1
  11. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/_version.py +1 -1
  12. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/annotate.py +15 -4
  13. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/arbitrate.py +69 -16
  14. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/cli.py +22 -13
  15. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/decide.py +43 -16
  16. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/evaluate.py +56 -2
  17. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/geo.py +6 -1
  18. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/hypotheses.py +9 -4
  19. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/local_lora.py +83 -19
  20. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/markers.tsv +23 -0
  21. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/ontology/ontology_map.jsonl +11 -0
  22. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/prepare.py +15 -0
  23. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/workflow.py +272 -22
  24. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent.egg-info/SOURCES.txt +1 -0
  25. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_annotate.py +57 -20
  26. annotuneagent-0.1.3/tests/test_bugfixes_1111.py +341 -0
  27. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_decide.py +33 -0
  28. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_evaluate.py +34 -0
  29. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_markers.py +13 -4
  30. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_version.py +2 -2
  31. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_workflow.py +263 -3
  32. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/.github/workflows/publish.yml +0 -0
  33. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/.github/workflows/tests.yml +0 -0
  34. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/.gitignore +0 -0
  35. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/.readthedocs.yaml +0 -0
  36. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/LICENSE +0 -0
  37. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/MANIFEST.in +0 -0
  38. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/SECURITY.md +0 -0
  39. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/_static/css/custom.css +0 -0
  40. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/_templates/README.md +0 -0
  41. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/conf.py +0 -0
  42. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/index.md +0 -0
  43. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/marker_sources.md +0 -0
  44. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/requirements.txt +0 -0
  45. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/tutorials/gse266598_annotation.ipynb +0 -0
  46. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/tutorials/index.md +0 -0
  47. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/tutorials/load_model.ipynb +0 -0
  48. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/docs/tutorials/pbmc8k_annotation.ipynb +0 -0
  49. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/setup.cfg +0 -0
  50. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/__main__.py +0 -0
  51. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/evidence.py +0 -0
  52. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/granularity/__init__.py +0 -0
  53. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/granularity/cl_dag.py +0 -0
  54. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/granularity/ontology_map.py +0 -0
  55. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/granularity/relations.py +0 -0
  56. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/marker_plot.py +0 -0
  57. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/markers.py +0 -0
  58. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/mltools.py +0 -0
  59. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/ontology/cl_isa.json +0 -0
  60. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/ontology/granularity_policy.yaml +0 -0
  61. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/py.typed +0 -0
  62. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/read.py +0 -0
  63. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/tokenizer/LICENSE +0 -0
  64. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/tokenizer/merges.txt +0 -0
  65. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/tokenizer/tokenizer.json +0 -0
  66. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/tokenizer/tokenizer_config.json +0 -0
  67. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/tokenizer/vocab.json +0 -0
  68. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/src/annotuneagent/votes.py +0 -0
  69. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_cli.py +0 -0
  70. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_evidence.py +0 -0
  71. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_geo.py +0 -0
  72. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_granularity.py +0 -0
  73. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_local_lora.py +0 -0
  74. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_mltools.py +0 -0
  75. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_prepare.py +0 -0
  76. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_read.py +0 -0
  77. {annotuneagent-0.1.2 → annotuneagent-0.1.3}/tests/test_votes.py +0 -0
@@ -2,6 +2,57 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [0.1.3] - 2026-11-11
6
+
7
+ ### Added
8
+
9
+ - Dictionary rows for macrophage, mature NK T cell, choroid plexus epithelium,
10
+ kidney connecting tubule epithelium, retinal horizontal and amacrine cells,
11
+ skeletal muscle myoblast, ovarian stroma, Merkel cell, small-intestine
12
+ transit amplifying cell, limb Schwann cell, and brain innate lymphoid cell.
13
+ - `evaluate(..., raw_label_key=...)`. A mapped name is the reference only when
14
+ it is the majority of every author-labeled cell. An unmapped raw majority
15
+ stays unmapped.
16
+ - `write_h5ad` saves a prepared AnnData with its QC report.
17
+ - `ANNOTUNE_API_KEY` is sent as a bearer token.
18
+
19
+ ### Changed
20
+
21
+ - A marker score caps each gene's log2 fold change at 3. A fired negative marker
22
+ subtracts half of one positive gene's share and still blocks a hard marker
23
+ label.
24
+ - When a call touches both CD4 and CD8, the written title is T cell. A cluster
25
+ whose NK and T panels are both specific is a cytotoxic mixture. A tissue
26
+ macrophage or alveolar fibroblast named by a model is kept when its own
27
+ panel is on. Effector-memory CD8 is not written when a MAIT marker is
28
+ enriched.
29
+
30
+ ### Fixed
31
+
32
+ - `dictionary_hits` order no longer depends on the input file name. The
33
+ command line and the Python API use the same fixed seed.
34
+ - A negative marker that is absent from the matrix stays on the ML panel.
35
+ `n_negative_unmeasured` counts it, and the marker score does not.
36
+ - `annotuneagent[models]` installs `jinja2`, which the chat template needs.
37
+ `run` with model endpoints checks `transformers` and `jinja2` before
38
+ scoring instead of failing at the first cluster.
39
+ - Model runs no longer stop on a one-cell cluster, an integer cluster
40
+ column, or unused categories. Wilcoxon skips clusters with fewer than two
41
+ cells; their model calls are recorded as failed.
42
+ - A label needs a positive gene that is enriched and detected in 25% of the
43
+ cluster, the same rule as the score.
44
+ - A model URL with a trailing slash no longer posts to `//completion` (404).
45
+ - A server not started by this process is called with the adapter ids its
46
+ `/lora-adapters` file names give, so `--lora ml.gguf,name.gguf` is not
47
+ swapped. A server started with repeated `--lora` flags is recognized.
48
+ - `TaskEndpoint(system=...)` is used on the URL path.
49
+ - The report shows `escalate` for an ML escalation instead of `null`.
50
+ - `--hypotheses` reads UTF-8 with or without a BOM, accepts `support` and
51
+ `requires_any`, and rejects non-list gene fields. `Hypothesis("x",
52
+ positive="CD3E")` is one gene, not four letters.
53
+ - `read_geo` keeps an uncompressed `features.tsv` or `genes.tsv`.
54
+ - `evaluate` treats a cluster with no record as uncertain.
55
+
5
56
  ## [0.1.2] - 2026-11-10
6
57
 
7
58
  ### Added
@@ -17,8 +17,8 @@ authors:
17
17
  orcid: "https://orcid.org/0000-0002-9276-9129"
18
18
  repository-code: "https://github.com/leelieber2025/AnnoTuneAgent"
19
19
  license: Apache-2.0
20
- version: 0.1.2
21
- date-released: "2026-11-10"
20
+ version: 0.1.3
21
+ date-released: "2026-11-11"
22
22
  keywords:
23
23
  - single-cell
24
24
  - RNA-seq
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: annotuneagent
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Cluster-level cell-type annotation from marker, name, and ML results
5
5
  Author-email: "Zhao Li (李钊)" <leelieber@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -37,6 +37,7 @@ Provides-Extra: scvi
37
37
  Requires-Dist: scvi-tools>=1.1.3; extra == "scvi"
38
38
  Provides-Extra: models
39
39
  Requires-Dist: transformers; extra == "models"
40
+ Requires-Dist: jinja2>=3.1; extra == "models"
40
41
  Provides-Extra: scfair
41
42
  Requires-Dist: scfair>=0.8; extra == "scfair"
42
43
  Provides-Extra: dev
@@ -125,7 +126,8 @@ Python 3.10–3.13.
125
126
  pip install annotuneagent
126
127
  ```
127
128
 
128
- Local GGUF models need `pip install 'annotuneagent[models]'`. Optional methods:
129
+ Local GGUF models need `pip install 'annotuneagent[models]'`, which installs
130
+ the tokenizer stack (`transformers` and `jinja2`). Optional methods:
129
131
  AmbiDose (`denoise=True`, [install](https://github.com/leelieber2025/AmbiDose)),
130
132
  scVI and SOLO (`annotuneagent[scvi]`), scFair (`annotuneagent[scfair]`),
131
133
  Harmony, and Scanorama. If you select one that is missing, `prepare` prints
@@ -212,12 +214,12 @@ The tokenizer is installed with the package. See
212
214
 
213
215
  ## Status
214
216
 
215
- **0.1.2 (Alpha).** Import as `import annotuneagent as ata`.
217
+ **0.1.3 (Alpha).** Import as `import annotuneagent as ata`.
216
218
 
217
219
  ## Citation
218
220
 
219
221
  For the software record, cite the [Zenodo DOI](https://doi.org/10.5281/zenodo.24092828).
220
- Pin the package version used in the analysis, for example `annotuneagent==0.1.2`.
222
+ Pin the package version used in the analysis, for example `annotuneagent==0.1.3`.
221
223
 
222
224
  ## License
223
225
 
@@ -72,7 +72,8 @@ Python 3.10–3.13.
72
72
  pip install annotuneagent
73
73
  ```
74
74
 
75
- Local GGUF models need `pip install 'annotuneagent[models]'`. Optional methods:
75
+ Local GGUF models need `pip install 'annotuneagent[models]'`, which installs
76
+ the tokenizer stack (`transformers` and `jinja2`). Optional methods:
76
77
  AmbiDose (`denoise=True`, [install](https://github.com/leelieber2025/AmbiDose)),
77
78
  scVI and SOLO (`annotuneagent[scvi]`), scFair (`annotuneagent[scfair]`),
78
79
  Harmony, and Scanorama. If you select one that is missing, `prepare` prints
@@ -159,12 +160,12 @@ The tokenizer is installed with the package. See
159
160
 
160
161
  ## Status
161
162
 
162
- **0.1.2 (Alpha).** Import as `import annotuneagent as ata`.
163
+ **0.1.3 (Alpha).** Import as `import annotuneagent as ata`.
163
164
 
164
165
  ## Citation
165
166
 
166
167
  For the software record, cite the [Zenodo DOI](https://doi.org/10.5281/zenodo.24092828).
167
- Pin the package version used in the analysis, for example `annotuneagent==0.1.2`.
168
+ Pin the package version used in the analysis, for example `annotuneagent==0.1.3`.
168
169
 
169
170
  ## License
170
171
 
@@ -19,6 +19,7 @@ The public API is the names below and `annotuneagent.__version__`.
19
19
  GeoSeries
20
20
  GeoSample
21
21
  prepare
22
+ write_h5ad
22
23
  run
23
24
  annotate
24
25
  evaluate
@@ -11,7 +11,7 @@ import annotuneagent as ata
11
11
  print(ata.__version__)
12
12
  ```
13
13
 
14
- The version is set in `src/annotuneagent/_version.py` (currently **0.1.2**).
14
+ The version is set in `src/annotuneagent/_version.py` (currently **0.1.3**).
15
15
 
16
16
  From a checkout:
17
17
 
@@ -157,7 +157,9 @@ annotuneagent --input counts.h5ad --output report.json --output-h5ad prepared.h5
157
157
 
158
158
  When the CLI writes a prepared `.h5ad`, it stores `uns["annotune_prep"]` as a
159
159
  JSON string so AnnData can write the nested QC report. After reloading, use
160
- `json.loads(adata.uns["annotune_prep"])`.
160
+ `json.loads(adata.uns["annotune_prep"])`. From Python, save with
161
+ `ata.write_h5ad(adata, "prepared.h5ad")`; `adata.write_h5ad` raises on that
162
+ report.
161
163
 
162
164
  ## Outputs
163
165
 
@@ -193,8 +195,9 @@ panel, not to each gene separately.
193
195
 
194
196
  ### Report fields
195
197
 
196
- - `dropped_hypotheses`: each dictionary type left out, and the positive markers
197
- missing from the matrix.
198
+ - `dropped_hypotheses`: each dictionary type left out because none of its
199
+ positive markers are in the matrix. One missing positive gene is omitted
200
+ and the type stays.
198
201
  - `review`: clusters that still need a look. The order is not an accuracy
199
202
  score.
200
203
  - `annotation_code`: an editable cluster mapping, `fine_order`, a `marker_dict`,
@@ -102,7 +102,7 @@ hint is in `review`, and on `annotune_hint`, and it is not in `queue`.
102
102
  | Field | What it is |
103
103
  |---|---|
104
104
  | `records` | The working record for each cluster, including model rounds and the marker ranking |
105
- | `dropped_hypotheses` | Dictionary types left out because a positive marker is missing from the matrix |
105
+ | `dropped_hypotheses` | Dictionary types left out because none of their positive markers are in the matrix |
106
106
  | `subclusters` | The second split of a cluster that was not settled. Empty when `subcluster=False` |
107
107
  | `arbitration` | Clusters that were not given the status `named` |
108
108
  | `merged` | Titles that were given one `annotune_cluster` id |
@@ -49,6 +49,7 @@ scvi = [
49
49
  ]
50
50
  models = [
51
51
  "transformers",
52
+ "jinja2>=3.1",
52
53
  ]
53
54
  scfair = [
54
55
  "scfair>=0.8",
@@ -47,7 +47,7 @@ from .hypotheses import Hypothesis
47
47
  from .local_lora import attach, local_server
48
48
  from .markers import hypotheses_from_names, marker_names, suggest_tissues, tissue_pages
49
49
  from .mltools import conformal_quantile, fit_ranker
50
- from .prepare import prepare
50
+ from .prepare import prepare, write_h5ad
51
51
  from .read import read_10x
52
52
  from .workflow import ModelChain, TaskEndpoint, dictionary_hypotheses, local_models, run
53
53
 
@@ -75,4 +75,5 @@ __all__ = [
75
75
  "run",
76
76
  "suggest_tissues",
77
77
  "tissue_pages",
78
+ "write_h5ad",
78
79
  ]
@@ -7,7 +7,7 @@ from __future__ import annotations
7
7
 
8
8
  __all__ = ["__version__", "version", "version_tuple"]
9
9
 
10
- __version__ = "0.1.2"
10
+ __version__ = "0.1.3"
11
11
  version = __version__
12
12
 
13
13
  _parts: list[int | str] = []
@@ -11,6 +11,7 @@ from anndata import AnnData
11
11
 
12
12
  from .arbitrate import DEFAULT_MIN_MARGIN, arbitrate, score_hypothesis
13
13
  from .evidence import (
14
+ GeneEvidence,
14
15
  cluster_ids,
15
16
  cluster_mask,
16
17
  evidence_from_stats,
@@ -21,6 +22,10 @@ from .evidence import (
21
22
  from .hypotheses import Hypothesis
22
23
 
23
24
 
25
+ def _absent_gene(name: str) -> GeneEvidence:
26
+ return GeneEvidence(name, "positive", 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, False)
27
+
28
+
24
29
  def annotate(
25
30
  adata: AnnData,
26
31
  cluster_key: str,
@@ -36,9 +41,11 @@ def annotate(
36
41
  ``clusters`` limits the records to those cluster ids. Each cluster is still
37
42
  compared with every other cell, so its record is the same either way.
38
43
 
39
- Expression is read from ``adata.X``. Genes named by a hypothesis must be in
40
- ``var_names``. Declared markers are scored together across clusters, using
41
- every CPU. Mann-Whitney p-values are reported and do not change the score.
44
+ Expression is read from ``adata.X``. A positive gene absent from
45
+ ``var_names`` scores 0 and stays in the panel mean. A negative gene
46
+ absent from ``var_names`` is not a penalty. Declared markers that are
47
+ present are scored together across clusters, using every CPU.
48
+ Mann-Whitney p-values are reported and do not change the score.
42
49
  """
43
50
  if adata.n_obs == 0:
44
51
  raise ValueError("AnnData has no cells")
@@ -59,8 +66,9 @@ def annotate(
59
66
  *hypothesis.positive,
60
67
  *hypothesis.negative,
61
68
  *hypothesis.support,
62
- *(gene for gene in hypothesis.requires_any if gene in present),
69
+ *hypothesis.requires_any,
63
70
  )
71
+ if gene in present
64
72
  )
65
73
  )
66
74
  measured = marker_statistics(adata, masks, genes)
@@ -72,11 +80,14 @@ def annotate(
72
80
  for hypothesis in hypotheses:
73
81
  positive = [
74
82
  evidence_from_stats(gene, "positive", cluster_stats[gene])
83
+ if gene in cluster_stats
84
+ else _absent_gene(gene)
75
85
  for gene in hypothesis.positive
76
86
  ]
77
87
  negative = [
78
88
  evidence_from_stats(gene, "negative", cluster_stats[gene])
79
89
  for gene in hypothesis.negative
90
+ if gene in cluster_stats
80
91
  ]
81
92
  support = [
82
93
  evidence_from_stats(gene, "positive", cluster_stats[gene])
@@ -12,8 +12,19 @@ from .hypotheses import Hypothesis
12
12
 
13
13
  # Score gap below this refuses a hard label.
14
14
  DEFAULT_MIN_MARGIN = 0.15
15
+ # One opposing gene weighs half of one positive gene. Negatives are a reference.
16
+ # A fired negative still refuses a hard marker label; this weight only changes rank.
17
+ NEGATIVE_REFERENCE_WEIGHT = 0.5
18
+ # One very large fold change does not outrank a broader panel. The cap was the
19
+ # best marker ranking on the high-error train files.
20
+ LOGFC_CAP = 3.0
15
21
  # A positive panel is on when at least half of its genes are detected in the cluster.
16
22
  _PROGRAM_PCT = 0.5
23
+ # A program is specific when those genes are also scarce outside the cluster.
24
+ # Detection alone is not enough: CD3 is common in blood, so a blood NK cluster
25
+ # can carry CD3 without being a T-cell cluster.
26
+ _SPECIFIC_PCT_OUT = 0.25
27
+ _SPECIFIC_LOGFC = 1.0
17
28
 
18
29
 
19
30
  @dataclass(frozen=True)
@@ -38,20 +49,24 @@ def score_hypothesis(
38
49
  negative: list[GeneEvidence],
39
50
  support: list[GeneEvidence] | None = None,
40
51
  required: list[GeneEvidence] | None = None,
52
+ *,
53
+ negative_weight: float | None = None,
41
54
  ) -> ScoredHypothesis:
42
- # Every positive gene stays in the mean. A gene detected in fewer than 25%
43
- # of the cells contributes 0, so a missing identity gene dilutes genes that
44
- # are shared with other types. One detected gene cannot stand for the panel.
45
- parts = [
46
- positive_contribution(gene) if gene.pct_in >= NEGATIVE_PRESENT_PCT else 0.0
47
- for gene in positive
48
- ]
55
+ # Every positive gene stays in the mean, including one absent from the
56
+ # matrix. A gene detected in fewer than 25% of the cells contributes 0.
57
+ # Fold change is capped so one gene cannot stand for the panel.
58
+ parts = [_capped_positive(gene) for gene in positive]
49
59
  score = float(sum(parts) / len(parts)) if parts else 0.0
50
- score += float(sum(positive_contribution(gene) for gene in support or []))
51
- fired = [value for value in (negative_penalty(gene) for gene in negative) if value > 0]
52
- # One opposing gene weighs like one positive gene. Subtracting the whole
53
- # logfc let a single shared gene erase a specific panel.
54
- penalty = float(sum(fired) / len(parts)) if fired and parts else float(sum(fired))
60
+ score += float(sum(_capped_positive(gene) for gene in support or []))
61
+ fired = [
62
+ min(value, LOGFC_CAP)
63
+ for value in (negative_penalty(gene) for gene in negative)
64
+ if value > 0
65
+ ]
66
+ # Positives are the score. A fired negative subtracts ``negative_weight``
67
+ # of one positive gene's share. The default weight is one half.
68
+ weight = NEGATIVE_REFERENCE_WEIGHT if negative_weight is None else negative_weight
69
+ penalty = weight * float(sum(fired) / len(parts)) if fired and parts else float(sum(fired))
55
70
  # None means this name has no required gene. An empty list means the
56
71
  # required genes were absent from the matrix, so the name cannot win.
57
72
  eligible = (
@@ -67,16 +82,47 @@ def score_hypothesis(
67
82
  )
68
83
 
69
84
 
85
+ def _capped_positive(gene: GeneEvidence) -> float:
86
+ if gene.pct_in < NEGATIVE_PRESENT_PCT or gene.logfc <= 0:
87
+ return 0.0
88
+ return min(gene.logfc, LOGFC_CAP)
89
+
90
+
91
+ def counted_positive(gene: GeneEvidence) -> bool:
92
+ """A positive gene that adds to the score: enriched and detected in 25% of the cluster."""
93
+ return gene.pct_in >= NEGATIVE_PRESENT_PCT and positive_contribution(gene) > 0
94
+
95
+
70
96
  def program_detected(genes: tuple[GeneEvidence, ...] | list[GeneEvidence]) -> bool:
71
97
  """True when two positive genes, and at least half the panel, are detected.
72
98
 
73
99
  One detected gene is not a second program. A two-gene panel therefore needs
74
100
  both genes, including when the other gene is ambient.
75
101
  """
102
+ return _panel_count(genes, specific=False)
103
+
104
+
105
+ def program_specific(genes: tuple[GeneEvidence, ...] | list[GeneEvidence]) -> bool:
106
+ """True when the same panel is enriched against the other cells.
107
+
108
+ Each counted gene is detected in at least half the cluster, in under 25%
109
+ of other cells, and at least twofold higher. A gene that is common outside
110
+ the cluster does not count.
111
+ """
112
+ return _panel_count(genes, specific=True)
113
+
114
+
115
+ def _panel_count(genes: tuple[GeneEvidence, ...] | list[GeneEvidence], *, specific: bool) -> bool:
76
116
  if len(genes) < 2:
77
117
  return False
78
- detected = sum(gene.pct_in >= _PROGRAM_PCT for gene in genes)
79
- return detected >= 2 and detected * 2 >= len(genes)
118
+ counted = 0
119
+ for gene in genes:
120
+ if gene.pct_in < _PROGRAM_PCT:
121
+ continue
122
+ if specific and (gene.pct_out >= _SPECIFIC_PCT_OUT or gene.logfc < _SPECIFIC_LOGFC):
123
+ continue
124
+ counted += 1
125
+ return counted >= 2 and counted * 2 >= len(genes)
80
126
 
81
127
 
82
128
  def arbitrate(
@@ -103,7 +149,10 @@ def arbitrate(
103
149
  accepted = prediction_set(eligible, conformal_q)
104
150
  status = "label"
105
151
  blocked = top is None or top.penalty > 0
106
- blocked = blocked or not any(positive_contribution(gene) > 0 for gene in top.positive)
152
+ # The same rule as the score: a positive gene below 25% detection contributes 0,
153
+ # so it cannot be the positive enrichment a label needs.
154
+ if top is not None:
155
+ blocked = blocked or not any(counted_positive(gene) for gene in top.positive)
107
156
  if blocked:
108
157
  status = "uncertain"
109
158
  elif accepted is not None:
@@ -129,7 +178,11 @@ def arbitrate(
129
178
  "name": item.hypothesis.name,
130
179
  "score": item.score,
131
180
  "program_on": program_detected(item.positive),
181
+ "program_specific": program_specific(item.positive),
132
182
  "eligible": item.eligible,
183
+ "lead_genes": [
184
+ gene.gene for gene in item.positive if gene.pct_in >= 0.25 and gene.logfc >= 1.0
185
+ ],
133
186
  }
134
187
  for item in ordered
135
188
  ],
@@ -140,7 +193,7 @@ def arbitrate(
140
193
 
141
194
 
142
195
  def _reasoning(top: ScoredHypothesis, status: str) -> str:
143
- up = [gene.gene for gene in top.positive if positive_contribution(gene) > 0]
196
+ up = [gene.gene for gene in top.positive if counted_positive(gene)]
144
197
  against = [gene.gene for gene in top.negative if negative_penalty(gene) > 0]
145
198
  parts: list[str] = []
146
199
  if up:
@@ -11,14 +11,13 @@ import os
11
11
  import sys
12
12
  from pathlib import Path
13
13
 
14
- import anndata as ad
15
14
  import scanpy as sc
16
15
 
17
16
  from .evaluate import evaluate
18
17
  from .hypotheses import Hypothesis
19
18
  from .local_lora import packaged_tokenizer
20
19
  from .markers import hypotheses_from_names, parents_for, suggest_tissues, tissue_pages
21
- from .prepare import install_hint, prepare
20
+ from .prepare import install_hint, prepare, write_h5ad
22
21
  from .workflow import ModelChain, TaskEndpoint, dictionary_hypotheses, run
23
22
 
24
23
 
@@ -98,17 +97,31 @@ def _reject_same_path(parser: argparse.ArgumentParser, args) -> None:
98
97
  seen.append(dest)
99
98
 
100
99
 
100
+ def _gene_field(item: dict, key: str, index: int) -> tuple[str, ...]:
101
+ value = item.get(key) or []
102
+ if isinstance(value, str):
103
+ value = [value]
104
+ if not isinstance(value, list) or not all(isinstance(gene, str) for gene in value):
105
+ raise ValueError(f"hypothesis {index}: {key!r} must be a list of gene symbols")
106
+ return tuple(value)
107
+
108
+
101
109
  def _hypotheses_from_file(path: Path) -> list[Hypothesis]:
102
- payload = json.loads(path.read_text())
110
+ # utf-8-sig: UTF-8 with or without the byte-order mark Windows editors add.
111
+ payload = json.loads(path.read_text(encoding="utf-8-sig"))
103
112
  if not isinstance(payload, list):
104
113
  raise ValueError("hypotheses file must be a JSON list")
105
114
  hypotheses: list[Hypothesis] = []
106
- for item in payload:
115
+ for index, item in enumerate(payload):
116
+ if not isinstance(item, dict) or not item.get("name"):
117
+ raise ValueError(f"hypothesis {index}: needs a name")
107
118
  hypotheses.append(
108
119
  Hypothesis(
109
120
  str(item["name"]),
110
- positive=tuple(item["positive"]),
111
- negative=tuple(item.get("negative", ())),
121
+ positive=_gene_field(item, "positive", index),
122
+ negative=_gene_field(item, "negative", index),
123
+ support=_gene_field(item, "support", index),
124
+ requires_any=_gene_field(item, "requires_any", index),
112
125
  )
113
126
  )
114
127
  return hypotheses
@@ -333,7 +346,7 @@ def main(argv: list[str] | None = None) -> int:
333
346
  return 0
334
347
  rates = None
335
348
  if args.solo_expected_rates is not None:
336
- rates = json.loads(args.solo_expected_rates.read_text())
349
+ rates = json.loads(args.solo_expected_rates.read_text(encoding="utf-8-sig"))
337
350
  if not isinstance(rates, dict):
338
351
  parser.error("--solo-expected-rates must contain a JSON object")
339
352
  adata = prepare(
@@ -385,11 +398,7 @@ def main(argv: list[str] | None = None) -> int:
385
398
  prediction_key="annotune_label",
386
399
  )
387
400
  # The report goes first so a failed h5ad write does not lose the run.
388
- args.output.write_text(json.dumps(payload, indent=2) + "\n")
401
+ args.output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
389
402
  if args.output_h5ad is not None:
390
- saved = adata.copy()
391
- if "annotune_prep" in saved.uns:
392
- saved.uns["annotune_prep"] = json.dumps(saved.uns["annotune_prep"])
393
- with ad.settings.override(allow_write_nullable_strings=True):
394
- saved.write_h5ad(args.output_h5ad)
403
+ write_h5ad(adata, args.output_h5ad)
395
404
  return 0
@@ -67,6 +67,10 @@ _ACTIONS = frozenset({"adopt_subcluster", "retest", "refuse", "escalate"})
67
67
  # A marker counts as support only above this log2 fold change.
68
68
  SUPPORT_LOGFC = 0.5
69
69
 
70
+ # dictionary_hits is shuffled so position is not rank. The seed does not
71
+ # include the input path: a renamed file and the Python API share one order.
72
+ _HIT_ORDER_SEED = "annotune-dictionary-hits"
73
+
70
74
 
71
75
  @dataclass(frozen=True)
72
76
  class Decision:
@@ -255,18 +259,33 @@ def wilcoxon_order(adata, cluster_key: str) -> dict[str, list[tuple[str, float]]
255
259
 
256
260
  import pandas as pd
257
261
 
258
- # Scanpy inserts one column per cluster into a single frame.
259
- with warnings.catch_warnings():
260
- warnings.simplefilter("ignore", pd.errors.PerformanceWarning)
261
- sc.tl.rank_genes_groups(
262
- adata,
263
- groupby=cluster_key,
264
- reference="rest",
265
- method="wilcoxon",
266
- use_raw=False,
267
- pts=True,
268
- )
262
+ # Scanpy needs a categorical column and at least two cells in every tested
263
+ # group. Integer cluster ids, unused categories, and one-cell clusters made
264
+ # it raise. A one-cell cluster has no table; it is still part of "rest".
265
+ tested = [str(cluster) for cluster, size in counts.items() if int(size) >= 2]
266
+ if not tested:
267
+ raise ValueError("wilcoxon needs a cluster with at least two cells")
268
+ groupby = "_annotune_wilcoxon_groups"
269
+ while groupby in adata.obs.columns:
270
+ groupby += "_"
271
+ adata.obs[groupby] = pd.Categorical(labels.to_numpy(), categories=list(counts.index))
272
+ try:
273
+ # Scanpy inserts one column per cluster into a single frame.
274
+ with warnings.catch_warnings():
275
+ warnings.simplefilter("ignore", pd.errors.PerformanceWarning)
276
+ sc.tl.rank_genes_groups(
277
+ adata,
278
+ groupby=groupby,
279
+ groups=tested,
280
+ reference="rest",
281
+ method="wilcoxon",
282
+ use_raw=False,
283
+ pts=True,
284
+ )
285
+ finally:
286
+ del adata.obs[groupby]
269
287
  result = adata.uns["rank_genes_groups"]
288
+ result["params"]["groupby"] = cluster_key
270
289
  tables: dict[str, list[tuple[str, float]]] = {}
271
290
  for cluster in counts.index:
272
291
  key = str(cluster)
@@ -357,8 +376,12 @@ def ranked_payload(
357
376
  continue
358
377
  genes.append({"gene": gene, "logfc": round(by_gene[gene], 1)})
359
378
  have.add(gene)
360
- if source is not None and cluster is not None:
361
- random.Random(f"{source}|{donor}|{cluster}").shuffle(hits)
379
+ # ``source`` is accepted so older callers keep working. It is not part of
380
+ # the seed: training shuffled with the dataset file name, and a copy of
381
+ # that file would otherwise change the prompt.
382
+ del source
383
+ if cluster is not None:
384
+ random.Random(f"{_HIT_ORDER_SEED}|{donor}|{cluster}").shuffle(hits)
362
385
  payload: dict[str, object] = {
363
386
  "species": species,
364
387
  "tissue": tissue,
@@ -614,10 +637,12 @@ def post_chat(
614
637
  {"role": "user", "content": user_text(task, payload)},
615
638
  ],
616
639
  }
640
+ from .local_lora import _auth_headers
641
+
617
642
  request = urllib.request.Request(
618
643
  endpoint,
619
644
  data=json.dumps(body).encode(),
620
- headers={"Content-Type": "application/json"},
645
+ headers={"Content-Type": "application/json", **_auth_headers()},
621
646
  method="POST",
622
647
  )
623
648
  with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -639,6 +664,7 @@ def fetch_name(
639
664
  *,
640
665
  maxlen: int = 2048,
641
666
  tokenizer: str | None = None,
667
+ system: str | None = None,
642
668
  ) -> Decision:
643
669
  """Name task on ``/completion``. One adapter is enabled for this request."""
644
670
  from .local_lora import complete_url
@@ -646,7 +672,7 @@ def fetch_name(
646
672
  text = complete_url(
647
673
  url,
648
674
  "name",
649
- SYSTEM_NAME,
675
+ system or SYSTEM_NAME,
650
676
  payload,
651
677
  maxlen=maxlen,
652
678
  timeout=timeout,
@@ -672,6 +698,7 @@ def fetch_ml(
672
698
  *,
673
699
  maxlen: int = 8192,
674
700
  tokenizer: str | None = None,
701
+ system: str | None = None,
675
702
  ) -> MlResult:
676
703
  """ML task on ``/completion``. One adapter is enabled for this request."""
677
704
  from .local_lora import complete_url
@@ -679,7 +706,7 @@ def fetch_ml(
679
706
  text = complete_url(
680
707
  url,
681
708
  "ml",
682
- SYSTEM_ML,
709
+ system or SYSTEM_ML,
683
710
  payload,
684
711
  maxlen=maxlen,
685
712
  timeout=timeout,