weirdo 2.2.0__tar.gz → 2.3.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.
Files changed (116) hide show
  1. {weirdo-2.2.0 → weirdo-2.3.0}/MANIFEST.in +1 -0
  2. {weirdo-2.2.0/weirdo.egg-info → weirdo-2.3.0}/PKG-INFO +35 -1
  3. {weirdo-2.2.0 → weirdo-2.3.0}/README.md +33 -0
  4. {weirdo-2.2.0 → weirdo-2.3.0}/pyproject.toml +1 -1
  5. {weirdo-2.2.0 → weirdo-2.3.0}/requirements.txt +1 -0
  6. weirdo-2.3.0/scripts/analyze_taxonomy_buckets.py +210 -0
  7. weirdo-2.3.0/scripts/audit_foreignness_definitions.py +178 -0
  8. weirdo-2.3.0/scripts/evaluate_improve_foreignness.py +817 -0
  9. weirdo-2.3.0/scripts/evaluate_peptide_content_immunogenicity.py +630 -0
  10. weirdo-2.3.0/scripts/evaluate_tcell_transfer.py +408 -0
  11. weirdo-2.3.0/scripts/peptide_content_data.py +452 -0
  12. weirdo-2.3.0/scripts/reference_proteome_data.py +409 -0
  13. weirdo-2.3.0/scripts/tcell_stratified_eval.py +862 -0
  14. weirdo-2.3.0/scripts/train_peptide_content_modal.py +892 -0
  15. weirdo-2.3.0/scripts/train_peptide_content_models.py +718 -0
  16. weirdo-2.3.0/scripts/viral_host_peptide_content_data.py +269 -0
  17. weirdo-2.3.0/test/test_analyze_taxonomy_buckets.py +38 -0
  18. weirdo-2.3.0/test/test_audit_foreignness_definitions.py +29 -0
  19. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_data_manager.py +95 -0
  20. weirdo-2.3.0/test/test_evaluate_improve_foreignness.py +124 -0
  21. weirdo-2.3.0/test/test_evaluate_peptide_content_immunogenicity.py +99 -0
  22. weirdo-2.3.0/test/test_evaluate_tcell_transfer.py +81 -0
  23. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_mlp_sigmoid_head.py +28 -0
  24. weirdo-2.3.0/test/test_peptide_content.py +37 -0
  25. weirdo-2.3.0/test/test_peptide_content_api.py +104 -0
  26. weirdo-2.3.0/test/test_peptide_content_data.py +66 -0
  27. weirdo-2.3.0/test/test_reference_proteome_data.py +72 -0
  28. weirdo-2.3.0/test/test_reference_proteome_manifest.py +51 -0
  29. weirdo-2.3.0/test/test_reference_proteomes.py +121 -0
  30. weirdo-2.3.0/test/test_tcell_stratified_eval.py +140 -0
  31. weirdo-2.3.0/test/test_train_peptide_content_models.py +107 -0
  32. weirdo-2.3.0/test/test_viral_host_peptide_content_data.py +67 -0
  33. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/__init__.py +36 -1
  34. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/api.py +70 -0
  35. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/cli.py +108 -3
  36. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/data_manager.py +199 -12
  37. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/model_manager.py +4 -0
  38. weirdo-2.3.0/weirdo/peptide_content.py +72 -0
  39. weirdo-2.3.0/weirdo/pretrained/peptide-content-v1/config.json +22 -0
  40. weirdo-2.3.0/weirdo/pretrained/peptide-content-v1/evaluation.json +170 -0
  41. weirdo-2.3.0/weirdo/pretrained/peptide-content-v1/metadata.json +48 -0
  42. weirdo-2.3.0/weirdo/pretrained/peptide-content-v1/model.pt +0 -0
  43. weirdo-2.3.0/weirdo/reference_proteome_manifests/reference-proteomes-v1.yaml +744 -0
  44. weirdo-2.3.0/weirdo/reference_proteomes.py +476 -0
  45. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/scorers/mlp.py +15 -0
  46. {weirdo-2.2.0 → weirdo-2.3.0/weirdo.egg-info}/PKG-INFO +35 -1
  47. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo.egg-info/SOURCES.txt +32 -0
  48. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo.egg-info/requires.txt +1 -0
  49. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo.egg-info/top_level.txt +0 -2
  50. {weirdo-2.2.0 → weirdo-2.3.0}/LICENSE +0 -0
  51. {weirdo-2.2.0 → weirdo-2.3.0}/scripts/category_data.py +0 -0
  52. {weirdo-2.2.0 → weirdo-2.3.0}/scripts/category_eval.py +0 -0
  53. {weirdo-2.2.0 → weirdo-2.3.0}/scripts/category_headroom.py +0 -0
  54. {weirdo-2.2.0 → weirdo-2.3.0}/scripts/check_released_model.py +0 -0
  55. {weirdo-2.2.0 → weirdo-2.3.0}/scripts/train_category_predictor.py +0 -0
  56. {weirdo-2.2.0 → weirdo-2.3.0}/scripts/train_modal_long_run.py +0 -0
  57. {weirdo-2.2.0 → weirdo-2.3.0}/setup.cfg +0 -0
  58. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_amino_acids.py +0 -0
  59. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_blosum.py +0 -0
  60. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_bundled_models.py +0 -0
  61. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_category_data.py +0 -0
  62. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_category_eval.py +0 -0
  63. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_cli_logic.py +0 -0
  64. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_hamming.py +0 -0
  65. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_kmer_table.py +0 -0
  66. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_logic_consistency.py +0 -0
  67. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_mlp_scorers.py +0 -0
  68. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_model_downloads.py +0 -0
  69. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_ngram.py +0 -0
  70. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_peptide_features.py +0 -0
  71. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_pmbec.py +0 -0
  72. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_pretrained_category_model.py +0 -0
  73. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_released_model.py +0 -0
  74. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_scorers.py +0 -0
  75. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_swissprot_reference.py +0 -0
  76. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_train_category_predictor.py +0 -0
  77. {weirdo-2.2.0 → weirdo-2.3.0}/test/test_uniprot.py +0 -0
  78. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/amino_acid.py +0 -0
  79. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/amino_acid_alphabet.py +0 -0
  80. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/amino_acid_properties.py +0 -0
  81. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/blosum.py +0 -0
  82. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/chou_fasman.py +0 -0
  83. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/common.py +0 -0
  84. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/distances.py +0 -0
  85. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/kmer_table.py +0 -0
  86. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/matrices/BLOSUM30 +0 -0
  87. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/matrices/BLOSUM50 +0 -0
  88. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/matrices/BLOSUM62 +0 -0
  89. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/matrices/__init__.py +0 -0
  90. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/matrices/amino_acid_properties.txt +0 -0
  91. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/matrices/helix_vs_coil.txt +0 -0
  92. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/matrices/helix_vs_strand.txt +0 -0
  93. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/matrices/pmbec.mat +0 -0
  94. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/matrices/strand_vs_coil.txt +0 -0
  95. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/peptide_vectorizer.py +0 -0
  96. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/pmbec.py +0 -0
  97. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/pretrained/swissprot-categories/config.json +0 -0
  98. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/pretrained/swissprot-categories/manifest.json +0 -0
  99. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/pretrained/swissprot-categories/metadata.json +0 -0
  100. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/pretrained/swissprot-categories/model.pt +0 -0
  101. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/reduced_alphabet.py +0 -0
  102. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/released.py +0 -0
  103. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/residue_contact_energies.py +0 -0
  104. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/scorers/__init__.py +0 -0
  105. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/scorers/base.py +0 -0
  106. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/scorers/config.py +0 -0
  107. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/scorers/peptide_features.py +0 -0
  108. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/scorers/reference.py +0 -0
  109. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/scorers/registry.py +0 -0
  110. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/scorers/similarity.py +0 -0
  111. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/scorers/swissprot.py +0 -0
  112. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/scorers/trainable.py +0 -0
  113. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/static_data.py +0 -0
  114. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo/uniprot.py +0 -0
  115. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo.egg-info/dependency_links.txt +0 -0
  116. {weirdo-2.2.0 → weirdo-2.3.0}/weirdo.egg-info/entry_points.txt +0 -0
@@ -1,2 +1,3 @@
1
1
  include requirements.txt
2
2
  recursive-include weirdo/pretrained *
3
+ recursive-include weirdo/reference_proteome_manifests *.yaml
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: weirdo
3
- Version: 2.2.0
3
+ Version: 2.3.0
4
4
  Summary: Metrics of immunological foreignness for candidate T-cell epitopes
5
5
  Author-email: Alex Rubinsteyn <alex.rubinsteyn@unc.edu>
6
6
  Project-URL: Homepage, https://github.com/pirl-unc/weirdo
@@ -24,6 +24,7 @@ License-File: LICENSE
24
24
  Requires-Dist: numpy<3.0.0,>=2.0.0
25
25
  Requires-Dist: pandas>=2.2.0
26
26
  Requires-Dist: scikit-learn<2.0.0,>=1.7.0
27
+ Requires-Dist: statsmodels>=0.14.0
27
28
  Requires-Dist: datacache>=1.24.0
28
29
  Provides-Extra: dev
29
30
  Requires-Dist: pytest>=7.0.0; extra == "dev"
@@ -60,6 +61,27 @@ WEIRDO trains a multi-layer perceptron (MLP) on k-mer presence data from SwissPr
60
61
 
61
62
  [docs/category-predictor.md](docs/category-predictor.md) explains what the numbers mean, how the model was evaluated and what its limits are. A typical peptide scores about 0.81 on the foreignness scale (peptides found only in mammalian proteins: median 0.76; only in bacteria/viruses: 0.84), so compare a score with those reference distributions rather than with 0.5. Nothing here has been shown to predict T-cell immunogenicity. The bundled weights derive from UniProtKB/Swiss-Prot sequences (CC BY 4.0).
62
63
 
64
+ For complete MHC-length peptides, the experimental `peptide-content-v1` model is
65
+ the better entry point. It was trained directly on variable-length 8--15mers and
66
+ uses independent heads for viruses, bacteria, archaea, fungi, plants, protists,
67
+ invertebrates, fish, non-mammalian tetrapods, mammals, human, mouse, and dog:
68
+
69
+ ```python
70
+ from weirdo import predict_peptide_content
71
+
72
+ result = predict_peptide_content(
73
+ ["SIINFEKL", "GILGFVFTL"],
74
+ self_categories=("mammals", "human"),
75
+ )
76
+ ```
77
+
78
+ Its primary summary is
79
+ `microbial_foreign_like = max(microbial heads) * (1 - max(selected self heads))`.
80
+ The score is useful for ranking peptide content, but it did not add a validated
81
+ T-cell immunogenicity signal beyond MHC presentation or affinity. See
82
+ [docs/peptide-content.md](docs/peptide-content.md) for the split, model comparison,
83
+ host-specific guidance, and evaluation.
84
+
63
85
  ## Quick Start
64
86
 
65
87
  ```python
@@ -126,10 +148,20 @@ scorers, build the reference data from UniProt:
126
148
  ```bash
127
149
  weirdo data download swissprot-sequences # ~670 MB from UniProt, builds a ~230 MB table
128
150
  weirdo data download # also builds the 8-mer table (several GB, some minutes)
151
+ weirdo data reference-proteome dog # complete dog proteome for exact self lookup
152
+ weirdo data reference-proteome cattle # Bos taurus / UP000009136
153
+ weirdo data reference-proteome --proteome UP000009136 # any UniProt reference proteome
154
+ weirdo data reference-proteome --manifest --dry-run # inspect the 544-proteome frozen corpus
155
+ weirdo data reference-proteome --manifest --group mammals # resumably fetch its 32 mammals
129
156
  ```
130
157
  The files are fetched with [datacache](https://github.com/openvax/datacache) from UniProt's FTP site
131
158
  (`WEIRDO_UNIPROT_URL` selects a mirror), checked against the sizes and MD5s UniProt lists and kept
132
159
  in `~/.weirdo/downloads/uniprot/release-<version>/`, so they are downloaded once per UniProt release.
160
+ Complete host references (`human`, `dog`, `cat`, `mouse`, `rat`, and `cattle`) are separately fetched as pinned
161
+ UniProt reference-proteome FASTAs, with a local SHA-256/content summary.
162
+ The same command also handles frozen multi-proteome selections. `--manifest`
163
+ downloads every selected FASTA through datacache, skips verified local files on
164
+ re-run, and supports `--group mammals`, `--group viruses`, or a specific leaf.
133
165
 
134
166
  ## Training Data
135
167
 
@@ -269,6 +301,8 @@ scorer = load_model('my-foreignness-model')
269
301
  ```bash
270
302
  # Data management
271
303
  weirdo data download # Download SwissProt from UniProt and build the reference data
304
+ weirdo data reference-proteome dog # Complete host proteome for exact self lookup
305
+ weirdo data reference-proteome cattle # Bos taurus; `cow` is also accepted
272
306
  weirdo data list # Show data status
273
307
 
274
308
  # Model management
@@ -19,6 +19,27 @@ WEIRDO trains a multi-layer perceptron (MLP) on k-mer presence data from SwissPr
19
19
 
20
20
  [docs/category-predictor.md](docs/category-predictor.md) explains what the numbers mean, how the model was evaluated and what its limits are. A typical peptide scores about 0.81 on the foreignness scale (peptides found only in mammalian proteins: median 0.76; only in bacteria/viruses: 0.84), so compare a score with those reference distributions rather than with 0.5. Nothing here has been shown to predict T-cell immunogenicity. The bundled weights derive from UniProtKB/Swiss-Prot sequences (CC BY 4.0).
21
21
 
22
+ For complete MHC-length peptides, the experimental `peptide-content-v1` model is
23
+ the better entry point. It was trained directly on variable-length 8--15mers and
24
+ uses independent heads for viruses, bacteria, archaea, fungi, plants, protists,
25
+ invertebrates, fish, non-mammalian tetrapods, mammals, human, mouse, and dog:
26
+
27
+ ```python
28
+ from weirdo import predict_peptide_content
29
+
30
+ result = predict_peptide_content(
31
+ ["SIINFEKL", "GILGFVFTL"],
32
+ self_categories=("mammals", "human"),
33
+ )
34
+ ```
35
+
36
+ Its primary summary is
37
+ `microbial_foreign_like = max(microbial heads) * (1 - max(selected self heads))`.
38
+ The score is useful for ranking peptide content, but it did not add a validated
39
+ T-cell immunogenicity signal beyond MHC presentation or affinity. See
40
+ [docs/peptide-content.md](docs/peptide-content.md) for the split, model comparison,
41
+ host-specific guidance, and evaluation.
42
+
22
43
  ## Quick Start
23
44
 
24
45
  ```python
@@ -85,10 +106,20 @@ scorers, build the reference data from UniProt:
85
106
  ```bash
86
107
  weirdo data download swissprot-sequences # ~670 MB from UniProt, builds a ~230 MB table
87
108
  weirdo data download # also builds the 8-mer table (several GB, some minutes)
109
+ weirdo data reference-proteome dog # complete dog proteome for exact self lookup
110
+ weirdo data reference-proteome cattle # Bos taurus / UP000009136
111
+ weirdo data reference-proteome --proteome UP000009136 # any UniProt reference proteome
112
+ weirdo data reference-proteome --manifest --dry-run # inspect the 544-proteome frozen corpus
113
+ weirdo data reference-proteome --manifest --group mammals # resumably fetch its 32 mammals
88
114
  ```
89
115
  The files are fetched with [datacache](https://github.com/openvax/datacache) from UniProt's FTP site
90
116
  (`WEIRDO_UNIPROT_URL` selects a mirror), checked against the sizes and MD5s UniProt lists and kept
91
117
  in `~/.weirdo/downloads/uniprot/release-<version>/`, so they are downloaded once per UniProt release.
118
+ Complete host references (`human`, `dog`, `cat`, `mouse`, `rat`, and `cattle`) are separately fetched as pinned
119
+ UniProt reference-proteome FASTAs, with a local SHA-256/content summary.
120
+ The same command also handles frozen multi-proteome selections. `--manifest`
121
+ downloads every selected FASTA through datacache, skips verified local files on
122
+ re-run, and supports `--group mammals`, `--group viruses`, or a specific leaf.
92
123
 
93
124
  ## Training Data
94
125
 
@@ -228,6 +259,8 @@ scorer = load_model('my-foreignness-model')
228
259
  ```bash
229
260
  # Data management
230
261
  weirdo data download # Download SwissProt from UniProt and build the reference data
262
+ weirdo data reference-proteome dog # Complete host proteome for exact self lookup
263
+ weirdo data reference-proteome cattle # Bos taurus; `cow` is also accepted
231
264
  weirdo data list # Show data status
232
265
 
233
266
  # Model management
@@ -33,7 +33,7 @@ dependencies = {file = ["requirements.txt"]}
33
33
  exclude = ["test", "test.*", "examples"]
34
34
 
35
35
  [tool.setuptools.package-data]
36
- weirdo = ["logging.conf", "matrices/*", "pretrained/*/*"]
36
+ weirdo = ["logging.conf", "matrices/*", "pretrained/*/*", "reference_proteome_manifests/*.yaml"]
37
37
 
38
38
  [project.urls]
39
39
  "Homepage" = "https://github.com/pirl-unc/weirdo"
@@ -2,4 +2,5 @@
2
2
  numpy>=2.0.0,<3.0.0
3
3
  pandas>=2.2.0
4
4
  scikit-learn>=1.7.0,<2.0.0
5
+ statsmodels>=0.14.0
5
6
  datacache>=1.24.0
@@ -0,0 +1,210 @@
1
+ #!/usr/bin/env python3
2
+ """Count SwissProt lineage clades to design balanced taxonomy leaves."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import gzip
8
+ import json
9
+ import re
10
+ from collections import defaultdict
11
+ from pathlib import Path
12
+
13
+
14
+ DIVISIONS = (
15
+ "archaea",
16
+ "bacteria",
17
+ "fungi",
18
+ "human",
19
+ "invertebrates",
20
+ "mammals",
21
+ "plants",
22
+ "rodents",
23
+ "vertebrates",
24
+ "viruses",
25
+ )
26
+ MAMMAL_DIVISIONS = frozenset(("human", "mammals", "rodents"))
27
+ GENERIC_LINEAGES = frozenset(
28
+ (
29
+ "cellular organisms",
30
+ "Bacteria",
31
+ "Eukaryota",
32
+ "Opisthokonta",
33
+ "Metazoa",
34
+ "Eumetazoa",
35
+ "Bilateria",
36
+ "Deuterostomia",
37
+ "Chordata",
38
+ "Craniata",
39
+ "Vertebrata",
40
+ "Euteleostomi",
41
+ "Mammalia",
42
+ "Theria",
43
+ )
44
+ )
45
+
46
+
47
+ def proposed_bacterial_bucket(lineage: tuple[str, ...]) -> str:
48
+ """Mutually exclusive bacterial leaf with roughly <=20M corpus residues."""
49
+ clades = set(lineage)
50
+ if "Enterobacterales" in clades:
51
+ return "enterobacterales"
52
+ if "Gammaproteobacteria" in clades:
53
+ return "other_gammaproteobacteria"
54
+ if "Alphaproteobacteria" in clades:
55
+ return "alphaproteobacteria"
56
+ if clades.intersection(("Pseudomonadota", "Proteobacteria")):
57
+ return "other_pseudomonadota"
58
+ if "Bacilli" in clades:
59
+ return "bacilli"
60
+ if clades.intersection(("Actinomycetota", "Actinobacteria")):
61
+ return "actinomycetota"
62
+ return "other_bacteria"
63
+
64
+
65
+ def proposed_mammal_bucket(lineage: tuple[str, ...]) -> str:
66
+ """Mutually exclusive mammalian leaf proposed for the next model."""
67
+ clades = set(lineage)
68
+ if "Primates" in clades:
69
+ return "primates"
70
+ if "Glires" in clades:
71
+ return "glires"
72
+ if "Carnivora" in clades:
73
+ return "carnivora"
74
+ return "other_mammals"
75
+
76
+
77
+ def division_path(dat_dir: Path, division: str) -> Path:
78
+ for suffix in (".dat.gz", ".dat"):
79
+ candidate = dat_dir / f"uniprot_sprot_{division}{suffix}"
80
+ if candidate.is_file():
81
+ return candidate
82
+ raise FileNotFoundError(f"No SwissProt {division!r} division in {dat_dir}")
83
+
84
+
85
+ def iter_records(path: Path):
86
+ opener = gzip.open if path.suffix == ".gz" else open
87
+ taxon_id = None
88
+ lineage_chunks: list[str] = []
89
+ length = None
90
+ with opener(path, "rt", encoding="ascii", errors="replace") as stream:
91
+ for line in stream:
92
+ tag = line[:2]
93
+ if tag == "ID":
94
+ taxon_id = None
95
+ lineage_chunks = []
96
+ length = None
97
+ elif tag == "OX":
98
+ match = re.search(r"NCBI_TaxID=(\d+)", line)
99
+ if match:
100
+ taxon_id = int(match.group(1))
101
+ elif tag == "OC":
102
+ lineage_chunks.append(line[5:].strip())
103
+ elif tag == "SQ":
104
+ length = int(line.split()[2])
105
+ elif tag == "//" and length is not None:
106
+ lineage = tuple(
107
+ item.strip().rstrip(".")
108
+ for item in " ".join(lineage_chunks).split(";")
109
+ if item.strip()
110
+ )
111
+ yield taxon_id, lineage, length
112
+
113
+
114
+ def lineage_counts(dat_dir: Path, divisions: frozenset[str]) -> dict[str, dict]:
115
+ proteins = defaultdict(int)
116
+ amino_acids = defaultdict(int)
117
+ taxa = defaultdict(set)
118
+ total_proteins = 0
119
+ total_amino_acids = 0
120
+ total_taxa = set()
121
+ for division in DIVISIONS:
122
+ if division not in divisions:
123
+ continue
124
+ for taxon_id, lineage, length in iter_records(division_path(dat_dir, division)):
125
+ total_proteins += 1
126
+ total_amino_acids += length
127
+ if taxon_id is not None:
128
+ total_taxa.add(taxon_id)
129
+ for clade in set(lineage):
130
+ proteins[clade] += 1
131
+ amino_acids[clade] += length
132
+ if taxon_id is not None:
133
+ taxa[clade].add(taxon_id)
134
+ rows = {
135
+ clade: {
136
+ "taxa": len(taxa[clade]),
137
+ "proteins": proteins[clade],
138
+ "amino_acids": amino_acids[clade],
139
+ }
140
+ for clade in proteins
141
+ }
142
+ return {
143
+ "total": {
144
+ "taxa": len(total_taxa),
145
+ "proteins": total_proteins,
146
+ "amino_acids": total_amino_acids,
147
+ },
148
+ "lineages": rows,
149
+ }
150
+
151
+
152
+ def partition_counts(dat_dir: Path, divisions: frozenset[str], classify) -> dict:
153
+ proteins = defaultdict(int)
154
+ amino_acids = defaultdict(int)
155
+ taxa = defaultdict(set)
156
+ for division in DIVISIONS:
157
+ if division not in divisions:
158
+ continue
159
+ for taxon_id, lineage, length in iter_records(division_path(dat_dir, division)):
160
+ bucket = classify(lineage)
161
+ proteins[bucket] += 1
162
+ amino_acids[bucket] += length
163
+ if taxon_id is not None:
164
+ taxa[bucket].add(taxon_id)
165
+ return {
166
+ bucket: {
167
+ "taxa": len(taxa[bucket]),
168
+ "proteins": proteins[bucket],
169
+ "amino_acids": amino_acids[bucket],
170
+ }
171
+ for bucket in proteins
172
+ }
173
+
174
+
175
+ def top_rows(summary: dict, limit: int) -> list[dict]:
176
+ rows = [
177
+ {"clade": clade, **counts}
178
+ for clade, counts in summary["lineages"].items()
179
+ if clade not in GENERIC_LINEAGES
180
+ ]
181
+ return sorted(rows, key=lambda row: row["amino_acids"], reverse=True)[:limit]
182
+
183
+
184
+ def analyze(dat_dir: Path, limit: int = 100) -> dict:
185
+ bacteria = lineage_counts(dat_dir, frozenset(("bacteria",)))
186
+ mammals = lineage_counts(dat_dir, MAMMAL_DIVISIONS)
187
+ return {
188
+ "bacteria_total": bacteria["total"],
189
+ "bacteria_top_lineages": top_rows(bacteria, limit),
190
+ "proposed_bacterial_buckets": partition_counts(
191
+ dat_dir, frozenset(("bacteria",)), proposed_bacterial_bucket
192
+ ),
193
+ "mammals_total": mammals["total"],
194
+ "mammals_top_lineages": top_rows(mammals, limit),
195
+ "proposed_mammal_buckets": partition_counts(
196
+ dat_dir, MAMMAL_DIVISIONS, proposed_mammal_bucket
197
+ ),
198
+ }
199
+
200
+
201
+ def main() -> None:
202
+ parser = argparse.ArgumentParser(description=__doc__)
203
+ parser.add_argument("--dat-dir", required=True)
204
+ parser.add_argument("--limit", type=int, default=100)
205
+ args = parser.parse_args()
206
+ print(json.dumps(analyze(Path(args.dat_dir), args.limit), indent=2))
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
@@ -0,0 +1,178 @@
1
+ #!/usr/bin/env python3
2
+ """Compare human/mammal and viral/pathogen-like score definitions.
3
+
4
+ This is an exploratory transfer audit, not a new lockbox. The response
5
+ coefficient is fit on broad development data and frozen before scoring the
6
+ registered validation table. It exists to prevent changing the taxonomy
7
+ summary (for example, human versus mammals) from being confused with a new
8
+ T-cell model.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import importlib.util
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ from sklearn.metrics import roc_auc_score
22
+
23
+
24
+ ROOT = Path(__file__).resolve().parents[1]
25
+ TRANSFER = ROOT / "scripts" / "evaluate_tcell_transfer.py"
26
+
27
+ # A deliberately explicit, reviewable set rather than a post-hoc prevalence
28
+ # threshold. Yellow fever is kept out because the validation cohort is a
29
+ # vaccine/travel challenge, not ordinary community exposure.
30
+ COMMON_EXPOSURE_VIRUSES = frozenset(
31
+ {
32
+ "Influenza A virus",
33
+ "Influenza B virus",
34
+ "Human betaherpesvirus 5", # CMV
35
+ "human gammaherpesvirus 4", # EBV
36
+ "Human alphaherpesvirus 1", # HSV-1
37
+ "Human alphaherpesvirus 2", # HSV-2
38
+ "Human alphaherpesvirus 3", # VZV
39
+ "human respiratory syncytial virus",
40
+ "human metapneumovirus",
41
+ "Severe acute respiratory syndrome coronavirus 2",
42
+ "Alphapapillomavirus 7",
43
+ "Measles morbillivirus",
44
+ "Mumps orthorubulavirus",
45
+ "Rotavirus alphagastroenteritidis",
46
+ "Norovirus norwalkense",
47
+ }
48
+ )
49
+
50
+
51
+ def _load_transfer():
52
+ spec = importlib.util.spec_from_file_location("tcell_transfer_for_definition_audit", TRANSFER)
53
+ if spec is None or spec.loader is None:
54
+ raise ValueError(f"Could not import {TRANSFER}")
55
+ module = importlib.util.module_from_spec(spec)
56
+ sys.modules[spec.name] = module
57
+ spec.loader.exec_module(module)
58
+ return module
59
+
60
+
61
+ def _filter(frame: pd.DataFrame) -> pd.DataFrame:
62
+ result = frame.loc[frame["outcome"].isin(("Positive", "Negative"))].copy()
63
+ required = [
64
+ "mhcflurry_presentation_score",
65
+ "mhcflurry_affinity",
66
+ "mhcflurry_processing_score",
67
+ ]
68
+ return result.loc[result[required].notna().all(axis=1)].reset_index(drop=True)
69
+
70
+
71
+ def _joint_filter(development: pd.DataFrame, validation: pd.DataFrame, transfer) -> tuple[pd.DataFrame, pd.DataFrame, np.ndarray]:
72
+ combined = pd.concat((development, validation), ignore_index=True)
73
+ components = transfer._joint_peptide_components(combined).to_numpy()
74
+ validation_components = components[len(development) :]
75
+ seen = set(validation_components)
76
+ keep = ~np.isin(components[: len(development)], list(seen))
77
+ return development.loc[keep].reset_index(drop=True), validation.reset_index(drop=True), validation_components
78
+
79
+
80
+ def _score_definitions(frame: pd.DataFrame) -> dict[str, np.ndarray]:
81
+ prefix = "esm_finetune__"
82
+ p_virus = frame[f"{prefix}p_viruses"].to_numpy(float)
83
+ p_mammal = frame[f"{prefix}p_mammals"].to_numpy(float)
84
+ p_human = frame[f"{prefix}p_human"].to_numpy(float)
85
+ return {
86
+ "p_viruses": p_virus,
87
+ "one_minus_mammals": 1.0 - p_mammal,
88
+ "one_minus_human": 1.0 - p_human,
89
+ "virus_vs_mammals": p_virus * (1.0 - p_mammal),
90
+ "virus_vs_human": p_virus * (1.0 - p_human),
91
+ "microbial_foreign_like": frame[f"{prefix}microbial_foreign_like"].to_numpy(float),
92
+ "microbial_like": frame[f"{prefix}microbial_like"].to_numpy(float),
93
+ }
94
+
95
+
96
+ def audit(args: argparse.Namespace) -> dict:
97
+ transfer = _load_transfer()
98
+ development = _filter(pd.read_csv(args.development))
99
+ validation = _filter(pd.read_csv(args.validation))
100
+ if "role" in validation:
101
+ validation = validation.loc[validation["role"].eq("validation")].reset_index(drop=True)
102
+ development, validation, validation_groups = _joint_filter(development, validation, transfer)
103
+ train_y = (development["outcome"] == "Positive").to_numpy(int)
104
+ test_y = (validation["outcome"] == "Positive").to_numpy(int)
105
+ train_base, _ = transfer._continuous_mhc_features(development)
106
+ test_base, _ = transfer._continuous_mhc_features(validation)
107
+ baseline, _ = transfer._fit_predict(train_base, train_y, test_base)
108
+ common_mask = validation["source_species"].isin(COMMON_EXPOSURE_VIRUSES).to_numpy()
109
+ subsets = {"all_validation": np.ones(len(validation), dtype=bool), "common_exposure": common_mask}
110
+ definitions = _score_definitions(pd.concat((development, validation), ignore_index=True))
111
+ results = []
112
+ for subset_name, subset_mask in subsets.items():
113
+ if subset_mask.sum() == 0 or len(np.unique(test_y[subset_mask])) < 2:
114
+ continue
115
+ groups = validation_groups[subset_mask]
116
+ for name, all_score in definitions.items():
117
+ train_score = all_score[: len(development)]
118
+ test_score = all_score[len(development) :]
119
+ augmented, coefficient = transfer._fit_predict(
120
+ np.column_stack((train_base, train_score)),
121
+ train_y,
122
+ np.column_stack((test_base[subset_mask], test_score[subset_mask])),
123
+ )
124
+ y = test_y[subset_mask]
125
+ base = baseline[subset_mask]
126
+ raw = test_score[subset_mask]
127
+ bootstrap = transfer._cluster_bootstrap(
128
+ y,
129
+ base,
130
+ augmented,
131
+ groups,
132
+ draws=args.bootstrap_draws,
133
+ seed=args.seed,
134
+ )
135
+ results.append(
136
+ {
137
+ "subset": subset_name,
138
+ "score": name,
139
+ "n_validation": int(len(y)),
140
+ "positive": int(y.sum()),
141
+ "raw_score_auc": float(roc_auc_score(y, raw)),
142
+ "baseline_auc": float(roc_auc_score(y, base)),
143
+ "augmented_auc": float(roc_auc_score(y, augmented)),
144
+ "delta_auc": float(roc_auc_score(y, augmented) - roc_auc_score(y, base)),
145
+ "standardized_coefficient": coefficient,
146
+ "cluster_bootstrap": bootstrap,
147
+ }
148
+ )
149
+ report = {
150
+ "protocol": "broad-development response calibration; joint peptide-component exclusion; frozen registered validation scoring",
151
+ "common_exposure_virus_set": sorted(COMMON_EXPOSURE_VIRUSES),
152
+ "common_exposure_n": int(common_mask.sum()),
153
+ "development_n": int(len(development)),
154
+ "validation_n": int(len(validation)),
155
+ "validation_positive": int(test_y.sum()),
156
+ "foreignness_scores": "ESM fine-tuned taxonomy outputs already present in input tables",
157
+ "pathogen_like_note": "No independent pathogen head is present in this virus/mammal taxonomy model; microbial_like is effectively virus-like here.",
158
+ "results": results,
159
+ }
160
+ output = Path(args.out)
161
+ output.parent.mkdir(parents=True, exist_ok=True)
162
+ output.write_text(json.dumps(report, indent=2))
163
+ print(json.dumps(report, indent=2))
164
+ return report
165
+
166
+
167
+ def main() -> None:
168
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
169
+ parser.add_argument("--development", required=True)
170
+ parser.add_argument("--validation", required=True)
171
+ parser.add_argument("--out", required=True)
172
+ parser.add_argument("--bootstrap-draws", type=int, default=200)
173
+ parser.add_argument("--seed", type=int, default=42)
174
+ audit(parser.parse_args())
175
+
176
+
177
+ if __name__ == "__main__":
178
+ main()