stangene 0.5.1__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 (62) hide show
  1. stangene-0.5.1/LICENSE +21 -0
  2. stangene-0.5.1/PKG-INFO +569 -0
  3. stangene-0.5.1/README.md +544 -0
  4. stangene-0.5.1/pyproject.toml +40 -0
  5. stangene-0.5.1/setup.cfg +4 -0
  6. stangene-0.5.1/src/stangene/__init__.py +92 -0
  7. stangene-0.5.1/src/stangene/__main__.py +60 -0
  8. stangene-0.5.1/src/stangene/_logging.py +16 -0
  9. stangene-0.5.1/src/stangene/biotype.py +204 -0
  10. stangene-0.5.1/src/stangene/classify.py +65 -0
  11. stangene-0.5.1/src/stangene/data/refs/c_elegans/build_metadata.json +18 -0
  12. stangene-0.5.1/src/stangene/data/refs/c_elegans/gene_table.parquet +0 -0
  13. stangene-0.5.1/src/stangene/data/refs/cynomolgus/build_metadata.json +20 -0
  14. stangene-0.5.1/src/stangene/data/refs/cynomolgus/gene_table.parquet +0 -0
  15. stangene-0.5.1/src/stangene/data/refs/fruit_fly/build_metadata.json +18 -0
  16. stangene-0.5.1/src/stangene/data/refs/fruit_fly/gene_table.parquet +0 -0
  17. stangene-0.5.1/src/stangene/data/refs/human/build_metadata.json +13 -0
  18. stangene-0.5.1/src/stangene/data/refs/human/gene_table.parquet +0 -0
  19. stangene-0.5.1/src/stangene/data/refs/marmoset/build_metadata.json +20 -0
  20. stangene-0.5.1/src/stangene/data/refs/marmoset/gene_table.parquet +0 -0
  21. stangene-0.5.1/src/stangene/data/refs/mouse/build_metadata.json +22 -0
  22. stangene-0.5.1/src/stangene/data/refs/mouse/gene_table.parquet +0 -0
  23. stangene-0.5.1/src/stangene/data/refs/mouse_lemur/build_metadata.json +20 -0
  24. stangene-0.5.1/src/stangene/data/refs/mouse_lemur/gene_table.parquet +0 -0
  25. stangene-0.5.1/src/stangene/data/refs/rat/build_metadata.json +13 -0
  26. stangene-0.5.1/src/stangene/data/refs/rat/gene_table.parquet +0 -0
  27. stangene-0.5.1/src/stangene/data/refs/rhesus/build_metadata.json +20 -0
  28. stangene-0.5.1/src/stangene/data/refs/rhesus/gene_table.parquet +0 -0
  29. stangene-0.5.1/src/stangene/data/refs/zebrafish/build_metadata.json +23 -0
  30. stangene-0.5.1/src/stangene/data/refs/zebrafish/gene_table.parquet +0 -0
  31. stangene-0.5.1/src/stangene/harmonize.py +252 -0
  32. stangene-0.5.1/src/stangene/hb.py +83 -0
  33. stangene-0.5.1/src/stangene/infer.py +200 -0
  34. stangene-0.5.1/src/stangene/io.py +204 -0
  35. stangene-0.5.1/src/stangene/merge.py +80 -0
  36. stangene-0.5.1/src/stangene/mito.py +64 -0
  37. stangene-0.5.1/src/stangene/references.py +893 -0
  38. stangene-0.5.1/src/stangene/report.py +381 -0
  39. stangene-0.5.1/src/stangene/species.py +267 -0
  40. stangene-0.5.1/src/stangene.egg-info/PKG-INFO +569 -0
  41. stangene-0.5.1/src/stangene.egg-info/SOURCES.txt +60 -0
  42. stangene-0.5.1/src/stangene.egg-info/dependency_links.txt +1 -0
  43. stangene-0.5.1/src/stangene.egg-info/entry_points.txt +2 -0
  44. stangene-0.5.1/src/stangene.egg-info/requires.txt +14 -0
  45. stangene-0.5.1/src/stangene.egg-info/top_level.txt +1 -0
  46. stangene-0.5.1/tests/test_biotype.py +301 -0
  47. stangene-0.5.1/tests/test_classify.py +88 -0
  48. stangene-0.5.1/tests/test_edge_cases.py +183 -0
  49. stangene-0.5.1/tests/test_harmonize.py +339 -0
  50. stangene-0.5.1/tests/test_harmonize_anndata.py +45 -0
  51. stangene-0.5.1/tests/test_hb_mask.py +51 -0
  52. stangene-0.5.1/tests/test_infer_species.py +69 -0
  53. stangene-0.5.1/tests/test_io.py +161 -0
  54. stangene-0.5.1/tests/test_markdown_report.py +169 -0
  55. stangene-0.5.1/tests/test_merge.py +70 -0
  56. stangene-0.5.1/tests/test_mito_mask.py +48 -0
  57. stangene-0.5.1/tests/test_pbmc3k.py +228 -0
  58. stangene-0.5.1/tests/test_references.py +740 -0
  59. stangene-0.5.1/tests/test_report.py +86 -0
  60. stangene-0.5.1/tests/test_resolve_species.py +39 -0
  61. stangene-0.5.1/tests/test_run.py +67 -0
  62. stangene-0.5.1/tests/test_species.py +174 -0
stangene-0.5.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sijie Chen
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.
@@ -0,0 +1,569 @@
1
+ Metadata-Version: 2.4
2
+ Name: stangene
3
+ Version: 0.5.1
4
+ Summary: Gene identifier harmonization for single-cell transcriptomics
5
+ Author: Sijie Chen
6
+ License: MIT
7
+ Project-URL: Repository, https://github.com/chansigit/stangene
8
+ Project-URL: Documentation, https://chansigit.github.io/stangene/
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: pandas>=1.5
13
+ Requires-Dist: anndata>=0.8
14
+ Requires-Dist: pyarrow>=10.0
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest>=7.0; extra == "dev"
17
+ Requires-Dist: scanpy>=1.9; extra == "dev"
18
+ Provides-Extra: docs
19
+ Requires-Dist: sphinx>=7.0; extra == "docs"
20
+ Requires-Dist: furo; extra == "docs"
21
+ Requires-Dist: myst-parser>=3.0; extra == "docs"
22
+ Requires-Dist: sphinx-copybutton; extra == "docs"
23
+ Requires-Dist: sphinx-autodoc-typehints; extra == "docs"
24
+ Dynamic: license-file
25
+
26
+ # StanGene: Gene identifier harmonization for single-cell transcriptomics datasets
27
+
28
+ <p align="center">
29
+ <img src="docs/_static/logo.png" alt="StanGene logo" width="200">
30
+ </p>
31
+
32
+ <p align="center">
33
+ <a href="https://github.com/chansigit/stangene/actions/workflows/tests.yml"><img src="https://github.com/chansigit/stangene/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
34
+ <a href="https://chansigit.github.io/stangene/"><img src="https://img.shields.io/badge/docs-GitHub%20Pages-blue" alt="Documentation"></a>
35
+ <a href="https://github.com/chansigit/stangene/blob/master/LICENSE"><img src="https://img.shields.io/github/license/chansigit/stangene" alt="License"></a>
36
+ <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.9%2B-blue?logo=python&logoColor=white" alt="Python 3.9+"></a>
37
+ <a href="https://github.com/chansigit/stangene/stargazers"><img src="https://img.shields.io/github/stars/chansigit/stangene?style=social" alt="GitHub stars"></a>
38
+ </p>
39
+
40
+ Gene identifier harmonization for single-cell transcriptomics datasets.
41
+
42
+ StanGene maps gene features from individual datasets into a shared canonical gene identity system using a tiered matching cascade. It preserves all original information, tracks mapping provenance, and never silently forces ambiguous mappings.
43
+
44
+ Designed to be invoked as a Claude Code / Codex skill or used as a standalone Python library and CLI tool.
45
+
46
+ **Documentation:** https://chansigit.github.io/stangene/
47
+
48
+ ---
49
+
50
+ ## Before & After
51
+
52
+ A typical 10x Genomics feature table arrives with inconsistent, version-tagged, or Excel-corrupted identifiers. StanGene cleans and standardises everything in one pass:
53
+
54
+ | Original input | Problem | After harmonization |
55
+ |---|---|---|
56
+ | `ENSG00000141510.18` | Versioned Ensembl ID | → `ENSG00000141510` · `TP53` · `exact_id` · high |
57
+ | `p53` | Alias, not approved symbol | → `ENSG00000141510` · `TP53` · `alias_symbol` · medium |
58
+ | `1-Mar` | Excel auto-date corruption | → unmapped · flagged in report |
59
+ | `MARCH1` | HGNC-renamed in 2020 | → `ENSG00000145416` · `MARCHF1` · flagged |
60
+ | `CD8a` | Wrong capitalisation | → `ENSG00000153563` · `CD8A` · `exact_symbol` · high |
61
+ | `ENSMFAG00000000001` | Non-human Ensembl ID | → matched in cynomolgus reference |
62
+ | `CD3_TotalSeqB` | Antibody capture, not a gene | → labeled `non_gene_feature`, passed through |
63
+
64
+ Every original identifier is preserved. Harmonized identifiers live in new columns — nothing is overwritten.
65
+
66
+ ---
67
+
68
+ ## Workflow
69
+
70
+ ```mermaid
71
+ flowchart TD
72
+ Input["Input Dataset\n(.h5ad / .tsv / .csv)"]
73
+ Load["load_features()\nExtract feature metadata"]
74
+ Classify["classify_features()\nTriage: gene vs non-gene"]
75
+ Gene["Gene features"]
76
+ NonGene["Non-gene features\n(antibody, CRISPR, spike-in,\npeaks, transcripts)"]
77
+ NonGeneLabel["Labeled non_gene_feature\nand passed through"]
78
+ LoadRef["load_reference()\nHGNC / MGI / RGD"]
79
+ Harmonize["harmonize()\n5-tier matching cascade"]
80
+
81
+ T1["Tier 1\nExact ID\n(high)"]
82
+ T2["Tier 2\nID no version\n(high)"]
83
+ T3["Tier 3\nExact symbol\n(high)"]
84
+ T4["Tier 4\nAlias / prev sym\n(medium)"]
85
+ T5["Tier 5\nUnmapped"]
86
+ Excel["Excel date\ndetection"]
87
+
88
+ Result["HarmonizationResult"]
89
+ WriteResults["write_results()\nharmonization_table.tsv\n*_harmonized.h5ad"]
90
+ WriteReports["write_reports()\nsummary.json\nconflicts.tsv\nunmapped.tsv\nreport.md"]
91
+ Merge["merge_features()\nstrict / symbol policy"]
92
+ MergeOut["MergeResult\n(merged_table + provenance)"]
93
+
94
+ Input --> Load --> Classify
95
+ Classify --> Gene
96
+ Classify --> NonGene --> NonGeneLabel
97
+
98
+ Gene --> LoadRef --> Harmonize
99
+ Harmonize --> T1
100
+ Harmonize --> T2
101
+ Harmonize --> T3
102
+ Harmonize --> T4
103
+ Harmonize --> T5
104
+ Harmonize --> Excel
105
+
106
+ T1 --> Result
107
+ T2 --> Result
108
+ T3 --> Result
109
+ T4 --> Result
110
+ T5 --> Result
111
+ Excel --> Result
112
+
113
+ Result --> WriteResults
114
+ Result --> WriteReports
115
+ Result -.->|"optional\nexplicit opt-in"| Merge --> MergeOut
116
+
117
+ style Input fill:#e8f4f8,stroke:#2196F3
118
+ style Result fill:#e8f5e9,stroke:#4CAF50
119
+ style MergeOut fill:#e8f5e9,stroke:#4CAF50
120
+ style NonGeneLabel fill:#fff3e0,stroke:#FF9800
121
+ style T1 fill:#c8e6c9,stroke:#388E3C
122
+ style T2 fill:#c8e6c9,stroke:#388E3C
123
+ style T3 fill:#c8e6c9,stroke:#388E3C
124
+ style T4 fill:#fff9c4,stroke:#FBC02D
125
+ style T5 fill:#ffcdd2,stroke:#D32F2F
126
+ style Excel fill:#ffcdd2,stroke:#D32F2F
127
+ ```
128
+
129
+ ---
130
+
131
+ ## Install
132
+
133
+ ### Python package
134
+
135
+ ```bash
136
+ pip install git+https://github.com/chansigit/stangene.git
137
+
138
+ # Or from source with dev dependencies:
139
+ git clone https://github.com/chansigit/stangene.git
140
+ cd stangene
141
+ pip install -e ".[dev]"
142
+ ```
143
+
144
+ **Dependencies:** pandas, anndata, pyarrow. Downloads use stdlib `urllib` (no `requests`).
145
+
146
+ ### Claude Code plugin
147
+
148
+ ```
149
+ /plugins add chansigit/stangene
150
+ ```
151
+
152
+ Once installed, ask Claude to "harmonize genes" or "standardize gene names" and the skill activates automatically.
153
+
154
+ ---
155
+
156
+ ## Quick start
157
+
158
+ ### 1. Build reference data (one-time per species)
159
+
160
+ ```bash
161
+ stangene build-refs --species human # downloads HGNC (~15 MB)
162
+ stangene build-refs --species mouse # downloads MGI + BioMart (~10 MB)
163
+ stangene build-refs --species rat # downloads RGD (~5 MB)
164
+ stangene build-refs --species zebrafish # downloads ZFIN
165
+ stangene build-refs --species fruit_fly # downloads FlyBase
166
+ stangene build-refs --species c_elegans # downloads WormBase
167
+ # Ensembl-only (BioMart) species:
168
+ stangene build-refs --species cynomolgus
169
+ stangene build-refs --species rhesus
170
+ stangene build-refs --species marmoset
171
+ stangene build-refs --species mouse_lemur
172
+ ```
173
+
174
+ Or from Python:
175
+
176
+ ```python
177
+ from stangene import build_reference
178
+
179
+ # Dedicated nomenclature authorities
180
+ for sp in ["human", "mouse", "rat", "zebrafish", "fruit_fly", "c_elegans"]:
181
+ build_reference(sp)
182
+
183
+ # Ensembl BioMart (no dedicated authority)
184
+ for sp in ["cynomolgus", "rhesus", "marmoset", "mouse_lemur"]:
185
+ build_reference(sp)
186
+ ```
187
+
188
+ References are stored locally (in `references/` during development, or `~/.cache/stangene/references` when pip-installed). Re-run with `--force` to update.
189
+
190
+ ### 2. Harmonize a dataset
191
+
192
+ ```python
193
+ import stangene
194
+
195
+ result = stangene.run(
196
+ path="my_data.h5ad", # or .tsv / .csv / .txt
197
+ species="human", # or any of: mouse, rat, zebrafish, fruit_fly, c_elegans, cynomolgus, rhesus, marmoset, mouse_lemur
198
+ output_dir="results/", # where to write reports
199
+ dataset_name="pbmc_10k", # optional label
200
+ )
201
+ ```
202
+
203
+ Or via CLI:
204
+
205
+ ```bash
206
+ stangene harmonize --input my_data.h5ad --species human --output-dir results/
207
+ ```
208
+
209
+ ### 3. Review outputs
210
+
211
+ | File | Contents |
212
+ |---|---|
213
+ | `harmonization_table.tsv` | Full mapping table, one row per original feature |
214
+ | `report.md` | Human-readable markdown report with summary, conflicts, and warnings |
215
+ | `summary.json` | Dataset-level statistics as JSON |
216
+ | `conflicts.tsv` | Many-to-one collisions, ambiguities, outdated names |
217
+ | `unmapped.tsv` | Unmapped features for manual review |
218
+ | `*_harmonized.h5ad` | Enriched h5ad with harmonization columns in `adata.var` (if input was h5ad) |
219
+
220
+ ### 4. Single-cell QC preparation
221
+
222
+ After harmonization, StanGene can generate the boolean masks that feed directly into scanpy/AnnData QC metrics — **no manual gene-list curation needed**.
223
+
224
+ ```python
225
+ import stangene
226
+ import scanpy as sc
227
+
228
+ adata = sc.read_h5ad("my_data.h5ad")
229
+ result = stangene.run(path="my_data.h5ad", species="human")
230
+
231
+ # Canonical symbols from the harmonization result
232
+ symbols = result.mapping_table["gene_symbol_harmonized"].fillna(
233
+ result.mapping_table["original_feature_name"]
234
+ )
235
+
236
+ # One line per QC metric
237
+ adata.var["is_mito"] = stangene.mito_mask(symbols, "human") # MT- prefix genes
238
+ adata.var["is_hb"] = stangene.hb_mask(symbols, "human") # HBA1, HBB, …
239
+ adata.var["biotype"] = result.mapping_table["canonical_biotype"].values
240
+
241
+ # Feed into scanpy QC
242
+ sc.pp.calculate_qc_metrics(
243
+ adata,
244
+ qc_vars=["is_mito", "is_hb"],
245
+ inplace=True,
246
+ )
247
+ ```
248
+
249
+ `canonical_biotype` uses a unified 13-category vocabulary (`protein_coding`, `lncRNA`, `pseudogene`, `miRNA`, `rRNA`, …) normalised from HGNC / MGI / RGD / Ensembl / WormBase / ZFIN / FlyBase — the same vocabulary across all 10 supported species.
250
+
251
+ ---
252
+
253
+ ## How it works
254
+
255
+ ### Feature classification
256
+
257
+ Before harmonization, every feature is classified:
258
+
259
+ | Pattern | Type |
260
+ |---|---|
261
+ | `ENSG*` / `ENSMUSG*` / `ENSRNOG*` | `gene` |
262
+ | `ENST*` / `ENSMUST*` / `ENSRNOT*` | `transcript` |
263
+ | `*_ADT`, `*_HTO`, `*TotalSeq*` | `antibody_capture` |
264
+ | `sg-*`, `gRNA-*` | `crispr_guide` |
265
+ | `ERCC-*` | `spike_in` |
266
+ | `chrN:start-end` | `peak` |
267
+ | 10x Cell Ranger labels | Mapped directly (`Gene Expression` -> `gene`, etc.) |
268
+ | Anything else | `gene` (default, flagged) |
269
+
270
+ Non-gene features are labeled `non_gene_feature` and excluded from the matching cascade. They are preserved in the output.
271
+
272
+ ### Matching cascade
273
+
274
+ Gene features are matched in strict priority order. Once a feature is resolved at a tier, lower tiers are skipped.
275
+
276
+ | Tier | Strategy | Confidence | Example |
277
+ |---|---|---|---|
278
+ | 1 | Exact Ensembl gene ID | high | `ENSG00000141510` matches directly |
279
+ | 2 | Version-stripped Ensembl ID | high | `ENSG00000141510.18` -> `ENSG00000141510` |
280
+ | 3 | Exact approved symbol | high | `TP53` matches HGNC approved symbol |
281
+ | 4 | Alias or previous symbol | medium | `p53` matches via HGNC alias for TP53 |
282
+ | 5 | Unmapped | -- | No confident match; preserved as-is |
283
+
284
+ **Symbol matching is case-insensitive**: exact case is tried first, then uppercase fallback. This ensures `tp53`, `Tp53`, and `TP53` all resolve correctly.
285
+
286
+ **Additional checks at each tier:**
287
+ - Withdrawn genes matched at Tier 3 are downgraded to `medium` confidence
288
+ - Non-protein-coding gene types are noted in `mapping_notes`
289
+ - Excel-corrupted date formats (`1-Mar`, `2-Sep`) are detected and marked unmapped
290
+ - Known HGNC-renamed genes (MARCH1->MARCHF1, SEPT2->SEPTIN2, etc.) are flagged
291
+
292
+ ### Output schema
293
+
294
+ Every feature receives these harmonization columns:
295
+
296
+ | Column | Description |
297
+ |---|---|
298
+ | `gene_id_harmonized` | Canonical Ensembl gene ID (or source_id fallback, e.g. `RGD:2003`) |
299
+ | `gene_symbol_harmonized` | Official approved symbol |
300
+ | `mapping_status` | `exact_id`, `id_no_version`, `exact_symbol`, `alias_symbol`, `previous_symbol`, `ambiguous`, `unmapped`, or `non_gene_feature` |
301
+ | `mapping_confidence` | `high`, `medium`, `low`, or null |
302
+ | `mapping_source` | Which lookup resolved this feature (e.g., `HGNC:approved_symbol`) |
303
+ | `mapping_notes` | Warnings, candidate lists, version mismatches |
304
+ | `stangene_version` | Version of StanGene that produced the mapping |
305
+ | `reference_release` | Timestamp of the reference data used |
306
+
307
+ Original columns (`original_feature_name`, `original_feature_id`, `original_feature_type`, `feature_id_no_version`) are always preserved.
308
+
309
+ ---
310
+
311
+ ## Detailed API
312
+
313
+ ### Top-level
314
+
315
+ ```python
316
+ import stangene
317
+
318
+ # Full pipeline
319
+ result = stangene.run(path, species, output_dir=None, dataset_name=None, reference_dir=None)
320
+ # Returns: HarmonizationResult
321
+
322
+ # Individual stages
323
+ stangene.build_reference(species, reference_dir=None, force=False)
324
+ ref = stangene.load_reference(species, reference_dir=None)
325
+ ft = stangene.load_features(path, species, dataset_name=None, column_map=None)
326
+ ft = stangene.classify_features(ft)
327
+ result = stangene.harmonize(ft, ref)
328
+
329
+ # Reporting
330
+ stats = stangene.summary(result)
331
+ conflicts = stangene.conflict_report(result)
332
+ md_report = stangene.generate_markdown_report(result)
333
+ stangene.write_reports(result, output_dir)
334
+
335
+ # Optional merge
336
+ merge_result = stangene.merge_features(result, policy="strict")
337
+
338
+ # Special gene masks (QC)
339
+ mito = stangene.mito_mask(symbols, species) # mitochondrial genes
340
+ hb = stangene.hb_mask(symbols, species) # hemoglobin genes
341
+
342
+ # Biotype normalization
343
+ stangene.CANONICAL_BIOTYPES # frozenset of 13 canonical categories
344
+ label = stangene.normalize_biotype(raw, source) # raw gene_type string → canonical label
345
+ ```
346
+
347
+ ### `stangene.run()`
348
+
349
+ Convenience function that chains the full pipeline:
350
+
351
+ 1. `load_features()` -- extract feature metadata from h5ad or TSV
352
+ 2. `classify_features()` -- triage gene vs. non-gene features
353
+ 3. `load_reference()` -- load pre-built annotation tables (raises `ReferenceNotFoundError` if not built)
354
+ 4. `harmonize()` -- run the 5-tier matching cascade
355
+ 5. `write_results()` + `write_reports()` -- write outputs (if `output_dir` provided)
356
+
357
+ ### `HarmonizationResult`
358
+
359
+ ```python
360
+ @dataclass
361
+ class HarmonizationResult:
362
+ mapping_table: pd.DataFrame # full FeatureTable with harmonization columns
363
+ conflicts: pd.DataFrame # many-to-one collision rows
364
+ stats: dict # counts per mapping_status
365
+ ```
366
+
367
+ ### `MergeResult`
368
+
369
+ ```python
370
+ @dataclass
371
+ class MergeResult:
372
+ merged_table: pd.DataFrame # collapsed rows
373
+ provenance: pd.DataFrame # which originals contributed to each merge
374
+ merge_log: list[str] # human-readable merge decisions
375
+ ```
376
+
377
+ ---
378
+
379
+ ## Conservative merge
380
+
381
+ Merge is **never automatic**. It must be explicitly requested.
382
+
383
+ ```python
384
+ from stangene import merge_features
385
+
386
+ # Strict: only merge rows sharing gene_id_harmonized via Tier 1 or 2 (ID-based)
387
+ merge_result = merge_features(result, policy="strict")
388
+
389
+ # Symbol: also merge Tier 3 (exact approved symbol) matches
390
+ merge_result = merge_features(result, policy="symbol")
391
+ ```
392
+
393
+ **Never merges:** Tier 4 (alias/previous symbol), ambiguous, unmapped, or non-gene features.
394
+
395
+ Every merge is recorded in `merge_result.provenance` with the original rows and merge reason, making it fully reversible.
396
+
397
+ ---
398
+
399
+ ## Supported species
400
+
401
+ | Species | Common name | Authority | Primary ID prefix | Source |
402
+ |---|---|---|---|---|
403
+ | `human` | Human (*Homo sapiens*) | [HGNC](https://www.genenames.org/) | `ENSG` | ~15 MB |
404
+ | `mouse` | Mouse (*Mus musculus*) | [MGI](https://www.informatics.jax.org/) + Ensembl BioMart | `ENSMUSG` | ~10 MB |
405
+ | `rat` | Rat (*Rattus norvegicus*) | [RGD](https://rgd.mcw.edu/) | `ENSRNOG` | ~5 MB |
406
+ | `zebrafish` | Zebrafish (*Danio rerio*) | [ZFIN](https://zfin.org/) | `ENSDARG` | ZFIN genes + aliases |
407
+ | `fruit_fly` | Fruit fly (*D. melanogaster*) | [FlyBase](https://flybase.org/) | `FBgn` | FlyBase annotation + synonyms |
408
+ | `c_elegans` | Roundworm (*C. elegans*) | [WormBase](https://wormbase.org/) | `WBGene` | WormBase geneIDs + geneOtherIDs |
409
+ | `cynomolgus` | Cynomolgus macaque (*M. fascicularis*) | Ensembl BioMart | `ENSMFAG` | Ensembl |
410
+ | `rhesus` | Rhesus macaque (*M. mulatta*) | Ensembl BioMart | `ENSMMUG` | Ensembl |
411
+ | `marmoset` | Common marmoset (*C. jacchus*) | Ensembl BioMart | `ENSCJAG` | Ensembl |
412
+ | `mouse_lemur` | Mouse lemur (*M. murinus*) | Ensembl BioMart | `ENSMICG` | Ensembl |
413
+
414
+ ### Reference internals
415
+
416
+ Built references are stored as:
417
+
418
+ ```
419
+ references/<species>/
420
+ gene_table.parquet # one row per gene
421
+ symbol_lookup.parquet # flattened symbol->gene index
422
+ build_metadata.json # source URLs, timestamps, checksums
423
+ ```
424
+
425
+ `gene_table` columns: `ensembl_id`, `symbol`, `alias_symbols`, `prev_symbols`, `gene_type`, `canonical_biotype`, `status`, `source`, `source_id`
426
+
427
+ `symbol_lookup` columns: `lookup_string`, `lookup_string_upper`, `ensembl_id`, `source_id`, `lookup_type`, `source`
428
+
429
+ ---
430
+
431
+ ## Conflict detection
432
+
433
+ The conflict report (`conflicts.tsv`) and markdown report (`report.md`) flag:
434
+
435
+ | Conflict type | Description |
436
+ |---|---|
437
+ | `many_to_one` | Multiple original features map to the same canonical gene ID |
438
+ | `unmapped` | Feature could not be matched to any reference gene |
439
+ | `ambiguous` | Feature matched multiple candidate genes |
440
+ | `outdated_name` | Feature resolved via a previous symbol (likely renamed) |
441
+
442
+ Additionally, the report detects:
443
+ - **Excel date artifacts:** Gene names corrupted by spreadsheet auto-formatting (`1-Mar`, `2-Sep`)
444
+ - **Known Excel-renamed genes:** Symbols renamed by HGNC in 2020 (e.g., MARCH1->MARCHF1, SEPT2->SEPTIN2)
445
+
446
+ ---
447
+
448
+ ## Input formats
449
+
450
+ ### h5ad (primary)
451
+
452
+ Reads `adata.var` metadata. Extracts `gene_ids`, `feature_types`, and `genome` columns if present. Does **not** load the expression matrix.
453
+
454
+ When writing results, harmonization columns are added to `adata.var` in a new `*_harmonized.h5ad` file. Original `var_names` are never overwritten.
455
+
456
+ ### TSV / CSV / TXT
457
+
458
+ Reads the table and auto-detects common column names:
459
+
460
+ | Detected column name | Maps to |
461
+ |---|---|
462
+ | `gene`, `gene_name`, `feature_name`, `gene_symbol`, `symbol` | `original_feature_name` |
463
+ | `gene_id`, `gene_ids`, `ensembl_id`, `ensembl_gene_id`, `feature_id` | `original_feature_id` |
464
+ | `feature_types`, `feature_type` | `original_feature_type` |
465
+
466
+ If no column names are recognized, the first column is used as `original_feature_name`.
467
+
468
+ Or pass an explicit `column_map`:
469
+
470
+ ```python
471
+ ft = stangene.load_features(
472
+ "features.tsv",
473
+ species="human",
474
+ column_map={"my_gene_col": "original_feature_name", "my_id_col": "original_feature_id"},
475
+ )
476
+ ```
477
+
478
+ File extension determines the delimiter: `.tsv`/`.txt` = tab, `.csv` = comma.
479
+
480
+ ---
481
+
482
+ ## Design principles
483
+
484
+ 1. **Never destroy original information.** All original identifiers are preserved. Harmonized identifiers live in separate columns.
485
+ 2. **Stable IDs over symbols.** Ensembl gene IDs are the canonical key. Gene symbols are a display layer.
486
+ 3. **Separate identity from display.** `gene_id_harmonized` (identity) and `gene_symbol_harmonized` (display) are distinct.
487
+ 4. **Within-species only.** Cross-species linkage via orthology is a separate concern, not conflated with name harmonization.
488
+ 5. **Conservative by default.** An explicit `ambiguous` or `unmapped` is always better than an incorrect forced mapping.
489
+ 6. **Full traceability.** Every mapping records its tier, confidence, source, and notes.
490
+
491
+ ---
492
+
493
+ ## Adding a new species
494
+
495
+ 1. Add a `SpeciesConfig` entry in `src/stangene/species.py` with the species' Ensembl prefix, naming convention, and reference source URLs.
496
+ 2. Add classification patterns if needed (e.g., new Ensembl prefix patterns for both gene and transcript IDs).
497
+ 3. Implement a `_build_<species>_reference()` function in `references.py` that downloads source files, builds `gene_table` and `symbol_lookup` DataFrames, and calls `_save_reference()`.
498
+ 4. Add the dispatch to `build_reference()`.
499
+
500
+ See the [rat (RGD) implementation](src/stangene/references.py) for a complete example.
501
+
502
+ ---
503
+
504
+ ## Testing
505
+
506
+ ```bash
507
+ # Run unit tests (fast, no network)
508
+ python -m pytest tests/ --ignore=tests/test_pbmc3k.py -v
509
+
510
+ # Run integration tests with real data (requires network + scanpy)
511
+ python -m pytest tests/test_pbmc3k.py -v
512
+
513
+ # Run all tests
514
+ python -m pytest tests/ -v
515
+ ```
516
+
517
+ 334 unit tests + integration tests covering: species config (human/mouse/rat/zebrafish/fruit_fly/c_elegans/cynomolgus/rhesus/marmoset/mouse_lemur), feature classification, I/O adapters (h5ad/TSV/CSV/TXT), reference building (HGNC/MGI/RGD/ZFIN/FlyBase/WormBase/Ensembl BioMart), all 5 harmonization tiers (including non-Ensembl FBgn/WBGene IDs), case-insensitive matching, Excel corruption detection, withdrawn gene handling, conservative merge, markdown reporting, empty input handling, canonical biotype normalization (all sources + integration across all 10 species), and end-to-end integration on the 10x pbmc3k dataset.
518
+
519
+ ---
520
+
521
+ ## Project structure
522
+
523
+ ```
524
+ stangene/
525
+ ├── pyproject.toml
526
+ ├── README.md
527
+ ├── LICENSE # MIT
528
+ ├── skill.md # Claude Code skill definition
529
+ ├── .readthedocs.yaml # Read the Docs config
530
+ ├── src/stangene/
531
+ │ ├── __init__.py # public API: run(), re-exports
532
+ │ ├── __main__.py # CLI: harmonize, build-refs
533
+ │ ├── species.py # SpeciesConfig, classification patterns, Excel lists
534
+ │ ├── classify.py # classify_features()
535
+ │ ├── io.py # load_features(), write_results()
536
+ │ ├── references.py # build_reference(), load_reference()
537
+ │ ├── harmonize.py # harmonize(), HarmonizationResult
538
+ │ ├── merge.py # merge_features(), MergeResult
539
+ │ ├── report.py # summary(), conflict_report(), generate_markdown_report(), write_reports()
540
+ │ ├── mito.py # mito_mask() — species-aware mitochondrial gene detection
541
+ │ ├── hb.py # hb_mask() — species-aware hemoglobin gene detection
542
+ │ ├── biotype.py # CANONICAL_BIOTYPES, normalize_biotype()
543
+ │ └── _logging.py # structured logging
544
+ ├── references/ # built by build_reference(), gitignored
545
+ ├── tests/
546
+ │ ├── conftest.py # shared mock fixtures
547
+ │ ├── test_species.py
548
+ │ ├── test_classify.py
549
+ │ ├── test_io.py
550
+ │ ├── test_references.py
551
+ │ ├── test_harmonize.py
552
+ │ ├── test_biotype.py
553
+ │ ├── test_merge.py
554
+ │ ├── test_report.py
555
+ │ ├── test_markdown_report.py
556
+ │ ├── test_edge_cases.py
557
+ │ ├── test_run.py
558
+ │ └── test_pbmc3k.py # integration test on real 10x data
559
+ ├── docs/ # Sphinx docs (GitHub Pages)
560
+ │ ├── conf.py
561
+ │ ├── index.md
562
+ │ ├── quickstart.md
563
+ │ ├── how-it-works.md
564
+ │ ├── api/ # auto-generated API reference
565
+ │ └── _static/logo.{svg,png}
566
+ └── .github/workflows/
567
+ ├── tests.yml # CI: pytest on Python 3.10/3.11/3.12
568
+ └── docs.yml # deploy docs to GitHub Pages
569
+ ```