weirdo 2.3.0__tar.gz → 2.5.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.
- {weirdo-2.3.0/weirdo.egg-info → weirdo-2.5.0}/PKG-INFO +4 -2
- {weirdo-2.3.0 → weirdo-2.5.0}/README.md +3 -1
- {weirdo-2.3.0 → weirdo-2.5.0}/pyproject.toml +9 -1
- weirdo-2.5.0/scripts/aggregate_braun_candidate_pmcs.py +312 -0
- weirdo-2.5.0/scripts/build_braun_mutation_aware_candidates.py +96 -0
- weirdo-2.5.0/scripts/build_fresh_iedb_cohort.py +133 -0
- weirdo-2.5.0/scripts/build_hla_self_ligand_neighborhood.py +120 -0
- weirdo-2.5.0/scripts/build_human_self_neighborhood_features.py +396 -0
- weirdo-2.5.0/scripts/build_iedb_training_pool.py +55 -0
- weirdo-2.5.0/scripts/build_pmhc_rank_reference.py +72 -0
- weirdo-2.5.0/scripts/build_protein_weirdo_context.py +67 -0
- weirdo-2.5.0/scripts/build_self_ligand_cohort.py +69 -0
- weirdo-2.5.0/scripts/build_source_context_features.py +115 -0
- weirdo-2.5.0/scripts/convert_cedar_export.py +51 -0
- weirdo-2.5.0/scripts/evaluate_construct_weighted_candidates.py +193 -0
- weirdo-2.5.0/scripts/evaluate_epitope_vs_self_ligand.py +145 -0
- weirdo-2.5.0/scripts/evaluate_fixed_pmhc_weirdo_combination.py +200 -0
- weirdo-2.5.0/scripts/evaluate_fresh_cohort.py +130 -0
- weirdo-2.5.0/scripts/evaluate_fresh_cohort_enrichment.py +65 -0
- weirdo-2.5.0/scripts/evaluate_iedb_grouped_learning.py +261 -0
- weirdo-2.5.0/scripts/evaluate_lodo_weirdo_models.py +184 -0
- weirdo-2.5.0/scripts/evaluate_mutation_contrast_weirdo.py +138 -0
- weirdo-2.5.0/scripts/evaluate_self_relative_face_weirdness.py +123 -0
- weirdo-2.5.0/scripts/evaluate_taxonomy_response_experiments.py +511 -0
- weirdo-2.5.0/scripts/evaluate_tcr_visible_external.py +114 -0
- weirdo-2.5.0/scripts/evaluate_weirdo_term_null.py +93 -0
- weirdo-2.5.0/scripts/fetch_uniprot_sequences.py +61 -0
- weirdo-2.5.0/scripts/prepare_external_neoantigen_benchmarks.py +301 -0
- weirdo-2.5.0/scripts/pull_iedb_human_class_i.py +65 -0
- weirdo-2.5.0/scripts/report_common_tcell_predictor_comparison.py +831 -0
- weirdo-2.5.0/scripts/report_tcell_predictor_comparison.py +112 -0
- weirdo-2.5.0/scripts/report_tcr_visible_nonself.py +965 -0
- weirdo-2.5.0/scripts/score_braun_mutation_aware_candidates.py +53 -0
- weirdo-2.5.0/scripts/score_common_tcell_predictors.py +569 -0
- weirdo-2.5.0/scripts/score_fresh_iedb_cohort.py +61 -0
- weirdo-2.5.0/scripts/score_shipped_weirdo_datasets.py +42 -0
- weirdo-2.5.0/scripts/train_tcr_visible_response_adapter.py +203 -0
- weirdo-2.5.0/test/test_aggregate_braun_candidate_pmcs.py +44 -0
- weirdo-2.5.0/test/test_build_braun_mutation_aware_candidates.py +22 -0
- weirdo-2.5.0/test/test_build_human_self_neighborhood_features.py +56 -0
- weirdo-2.5.0/test/test_epitope_vs_self_ligand.py +33 -0
- weirdo-2.5.0/test/test_evaluate_construct_weighted_candidates.py +41 -0
- weirdo-2.5.0/test/test_evaluate_tcr_visible_external.py +67 -0
- weirdo-2.5.0/test/test_evaluation_cohorts.py +30 -0
- weirdo-2.5.0/test/test_fresh_cohort.py +36 -0
- weirdo-2.5.0/test/test_hla_self_ligand_neighborhood.py +23 -0
- weirdo-2.5.0/test/test_iedb_grouped_learning.py +50 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_peptide_content_api.py +37 -1
- weirdo-2.5.0/test/test_pmhc_score.py +99 -0
- weirdo-2.5.0/test/test_prepare_external_neoantigen_benchmarks.py +80 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_released_model.py +3 -0
- weirdo-2.5.0/test/test_score_braun_mutation_aware_candidates.py +13 -0
- weirdo-2.5.0/test/test_score_policies.py +100 -0
- weirdo-2.5.0/test/test_source_context.py +48 -0
- weirdo-2.5.0/test/test_weirdo_search_helpers.py +33 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/__init__.py +36 -1
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/api.py +98 -13
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/cli.py +29 -0
- weirdo-2.5.0/weirdo/evaluation_cohorts.py +169 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/model_manager.py +5 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/peptide_content.py +3 -7
- weirdo-2.5.0/weirdo/peptide_content_models.py +572 -0
- weirdo-2.5.0/weirdo/pmhc_score.py +168 -0
- weirdo-2.5.0/weirdo/pretrained/peptide-content-v1/config.json +22 -0
- weirdo-2.5.0/weirdo/pretrained/peptide-content-v1/model.pt +0 -0
- weirdo-2.5.0/weirdo/pretrained/peptide-content-v1-ensemble/config.json +127 -0
- weirdo-2.5.0/weirdo/pretrained/peptide-content-v1-ensemble/evaluation.json +539 -0
- weirdo-2.5.0/weirdo/pretrained/peptide-content-v1-ensemble/members/cnn/config.json +69 -0
- weirdo-2.5.0/weirdo/pretrained/peptide-content-v1-ensemble/members/cnn/weights.pt +0 -0
- weirdo-2.5.0/weirdo/pretrained/peptide-content-v1-ensemble/members/composition_mlp/metadata.json +39 -0
- weirdo-2.5.0/weirdo/pretrained/peptide-content-v1-ensemble/members/transformer/config.json +69 -0
- weirdo-2.5.0/weirdo/pretrained/peptide-content-v1-ensemble/members/transformer/weights.pt +0 -0
- weirdo-2.5.0/weirdo/pretrained/peptide-content-v1-ensemble/metadata.json +49 -0
- weirdo-2.5.0/weirdo/pretrained/pmhc-rank-reference-v1.json +1 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/released.py +30 -8
- weirdo-2.5.0/weirdo/score_policies.py +257 -0
- {weirdo-2.3.0 → weirdo-2.5.0/weirdo.egg-info}/PKG-INFO +4 -2
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo.egg-info/SOURCES.txt +65 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo.egg-info/top_level.txt +3 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/LICENSE +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/MANIFEST.in +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/requirements.txt +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/analyze_taxonomy_buckets.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/audit_foreignness_definitions.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/category_data.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/category_eval.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/category_headroom.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/check_released_model.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/evaluate_improve_foreignness.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/evaluate_peptide_content_immunogenicity.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/evaluate_tcell_transfer.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/peptide_content_data.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/reference_proteome_data.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/tcell_stratified_eval.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/train_category_predictor.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/train_modal_long_run.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/train_peptide_content_modal.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/train_peptide_content_models.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/scripts/viral_host_peptide_content_data.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/setup.cfg +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_amino_acids.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_analyze_taxonomy_buckets.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_audit_foreignness_definitions.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_blosum.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_bundled_models.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_category_data.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_category_eval.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_cli_logic.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_data_manager.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_evaluate_improve_foreignness.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_evaluate_peptide_content_immunogenicity.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_evaluate_tcell_transfer.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_hamming.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_kmer_table.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_logic_consistency.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_mlp_scorers.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_mlp_sigmoid_head.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_model_downloads.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_ngram.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_peptide_content.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_peptide_content_data.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_peptide_features.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_pmbec.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_pretrained_category_model.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_reference_proteome_data.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_reference_proteome_manifest.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_reference_proteomes.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_scorers.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_swissprot_reference.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_tcell_stratified_eval.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_train_category_predictor.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_train_peptide_content_models.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_uniprot.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/test/test_viral_host_peptide_content_data.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/amino_acid.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/amino_acid_alphabet.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/amino_acid_properties.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/blosum.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/chou_fasman.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/common.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/data_manager.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/distances.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/kmer_table.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/matrices/BLOSUM30 +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/matrices/BLOSUM50 +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/matrices/BLOSUM62 +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/matrices/__init__.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/matrices/amino_acid_properties.txt +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/matrices/helix_vs_coil.txt +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/matrices/helix_vs_strand.txt +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/matrices/pmbec.mat +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/matrices/strand_vs_coil.txt +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/peptide_vectorizer.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/pmbec.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/pretrained/peptide-content-v1/evaluation.json +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/pretrained/peptide-content-v1/metadata.json +0 -0
- {weirdo-2.3.0/weirdo/pretrained/peptide-content-v1 → weirdo-2.5.0/weirdo/pretrained/peptide-content-v1-ensemble/members/composition_mlp}/config.json +0 -0
- {weirdo-2.3.0/weirdo/pretrained/peptide-content-v1 → weirdo-2.5.0/weirdo/pretrained/peptide-content-v1-ensemble/members/composition_mlp}/model.pt +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/pretrained/swissprot-categories/config.json +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/pretrained/swissprot-categories/manifest.json +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/pretrained/swissprot-categories/metadata.json +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/pretrained/swissprot-categories/model.pt +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/reduced_alphabet.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/reference_proteome_manifests/reference-proteomes-v1.yaml +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/reference_proteomes.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/residue_contact_energies.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/scorers/__init__.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/scorers/base.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/scorers/config.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/scorers/mlp.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/scorers/peptide_features.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/scorers/reference.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/scorers/registry.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/scorers/similarity.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/scorers/swissprot.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/scorers/trainable.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/static_data.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo/uniprot.py +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo.egg-info/dependency_links.txt +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo.egg-info/entry_points.txt +0 -0
- {weirdo-2.3.0 → weirdo-2.5.0}/weirdo.egg-info/requires.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: weirdo
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.5.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
|
|
@@ -71,7 +71,7 @@ from weirdo import predict_peptide_content
|
|
|
71
71
|
|
|
72
72
|
result = predict_peptide_content(
|
|
73
73
|
["SIINFEKL", "GILGFVFTL"],
|
|
74
|
-
|
|
74
|
+
score_policy="human-microbial-content-v1",
|
|
75
75
|
)
|
|
76
76
|
```
|
|
77
77
|
|
|
@@ -81,6 +81,8 @@ The score is useful for ranking peptide content, but it did not add a validated
|
|
|
81
81
|
T-cell immunogenicity signal beyond MHC presentation or affinity. See
|
|
82
82
|
[docs/peptide-content.md](docs/peptide-content.md) for the split, model comparison,
|
|
83
83
|
host-specific guidance, and evaluation.
|
|
84
|
+
[docs/score-policies.md](docs/score-policies.md) defines the versioned human,
|
|
85
|
+
mouse, dog, generic-mammal, and stable human-complement scoring contracts.
|
|
84
86
|
|
|
85
87
|
## Quick Start
|
|
86
88
|
|
|
@@ -29,7 +29,7 @@ from weirdo import predict_peptide_content
|
|
|
29
29
|
|
|
30
30
|
result = predict_peptide_content(
|
|
31
31
|
["SIINFEKL", "GILGFVFTL"],
|
|
32
|
-
|
|
32
|
+
score_policy="human-microbial-content-v1",
|
|
33
33
|
)
|
|
34
34
|
```
|
|
35
35
|
|
|
@@ -39,6 +39,8 @@ The score is useful for ranking peptide content, but it did not add a validated
|
|
|
39
39
|
T-cell immunogenicity signal beyond MHC presentation or affinity. See
|
|
40
40
|
[docs/peptide-content.md](docs/peptide-content.md) for the split, model comparison,
|
|
41
41
|
host-specific guidance, and evaluation.
|
|
42
|
+
[docs/score-policies.md](docs/score-policies.md) defines the versioned human,
|
|
43
|
+
mouse, dog, generic-mammal, and stable human-complement scoring contracts.
|
|
42
44
|
|
|
43
45
|
## Quick Start
|
|
44
46
|
|
|
@@ -33,7 +33,15 @@ dependencies = {file = ["requirements.txt"]}
|
|
|
33
33
|
exclude = ["test", "test.*", "examples"]
|
|
34
34
|
|
|
35
35
|
[tool.setuptools.package-data]
|
|
36
|
-
weirdo = [
|
|
36
|
+
weirdo = [
|
|
37
|
+
"logging.conf",
|
|
38
|
+
"matrices/*",
|
|
39
|
+
"pretrained/*.json",
|
|
40
|
+
"pretrained/*/*",
|
|
41
|
+
"pretrained/*/*/*",
|
|
42
|
+
"pretrained/*/*/*/*",
|
|
43
|
+
"reference_proteome_manifests/*.yaml",
|
|
44
|
+
]
|
|
37
45
|
|
|
38
46
|
[project.urls]
|
|
39
47
|
"Homepage" = "https://github.com/pirl-unc/weirdo"
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Aggregate mutation-aware candidate pMHC evidence by vaccine construct.
|
|
3
|
+
|
|
4
|
+
This is deliberately a *candidate-evidence* aggregation, not a count of
|
|
5
|
+
predicted pMHCs. A candidate receives a fixed, label-free evidence weight
|
|
6
|
+
|
|
7
|
+
sqrt(MHCflurry presentation * (1 - NetMHCpan BA rank / 100)).
|
|
8
|
+
|
|
9
|
+
MHCflurry's presentation predictor already includes its learned antigen-
|
|
10
|
+
processing component. The main construct score is the sum of the three
|
|
11
|
+
strongest distinct peptide--HLA candidate weights. Thus a construct can gain
|
|
12
|
+
from several independently strong sequences, while weak windows contribute
|
|
13
|
+
almost nothing and a fixed top-three cap prevents a longer construct from
|
|
14
|
+
winning merely because it generated more sliding windows.
|
|
15
|
+
|
|
16
|
+
The stricter secondary score additionally requires MHCflurry presentation
|
|
17
|
+
percentile <= 5 and NetMHCpan BA rank <= 2 before a candidate contributes.
|
|
18
|
+
Those are biological presentation/binding eligibility rules fixed without
|
|
19
|
+
Braun response labels; they are not fitted thresholds.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import json
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
import numpy as np
|
|
29
|
+
import pandas as pd
|
|
30
|
+
from sklearn.metrics import average_precision_score, roc_auc_score
|
|
31
|
+
|
|
32
|
+
from scripts.evaluate_taxonomy_response_experiments import group_bootstrap_delta
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
TOP_K = 3
|
|
36
|
+
PRESENTATION_PERCENTILE_GATE = 5.0
|
|
37
|
+
BA_RANK_GATE = 2.0
|
|
38
|
+
REQUIRED_COLUMNS = {
|
|
39
|
+
"record_id",
|
|
40
|
+
"patient",
|
|
41
|
+
"mutation_class",
|
|
42
|
+
"outcome",
|
|
43
|
+
"peptide",
|
|
44
|
+
"hla",
|
|
45
|
+
"mhcflurry_2_3_0_presentation_score",
|
|
46
|
+
"mhcflurry_2_3_0_presentation_percentile",
|
|
47
|
+
"netmhcpan_ba_rank",
|
|
48
|
+
}
|
|
49
|
+
TAXONOMY_WEIGHTS = {
|
|
50
|
+
"one_minus_mammals": "broad9__esm_160k__one_minus_mammals",
|
|
51
|
+
"microbial_like": "broad9__esm_160k__microbial_like",
|
|
52
|
+
"viruses": "broad9__esm_160k__viruses",
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def candidate_evidence(frame: pd.DataFrame) -> np.ndarray:
|
|
57
|
+
"""Return label-free joint pMHC evidence in [0, 1].
|
|
58
|
+
|
|
59
|
+
MHCflurry presentation supplies affinity plus antigen-processing evidence;
|
|
60
|
+
NetMHCpan BA rank supplies an independent binding view. The geometric
|
|
61
|
+
mean requires both to be high without fitting a response model.
|
|
62
|
+
"""
|
|
63
|
+
presentation = frame["mhcflurry_2_3_0_presentation_score"].to_numpy(float)
|
|
64
|
+
ba_rank = frame["netmhcpan_ba_rank"].to_numpy(float)
|
|
65
|
+
if not np.isfinite(presentation).all() or ((presentation < 0) | (presentation > 1)).any():
|
|
66
|
+
raise ValueError("MHCflurry presentation scores must be finite in [0, 1]")
|
|
67
|
+
if not np.isfinite(ba_rank).all() or ((ba_rank < 0) | (ba_rank > 100)).any():
|
|
68
|
+
raise ValueError("NetMHCpan BA ranks must be finite in [0, 100]")
|
|
69
|
+
binding = 1.0 - ba_rank / 100.0
|
|
70
|
+
return np.sqrt(presentation * binding)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _top_k_sum(values: pd.Series, top_k: int = TOP_K) -> float:
|
|
74
|
+
"""Add the strongest fixed number of candidate contributions."""
|
|
75
|
+
return float(values.nlargest(top_k).sum())
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _top_k_soft_or(values: pd.Series, top_k: int = TOP_K) -> float:
|
|
79
|
+
"""A saturating sensitivity analysis over the same top candidates."""
|
|
80
|
+
selected = values.nlargest(top_k).to_numpy(float)
|
|
81
|
+
return float(1.0 - np.prod(1.0 - selected))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def aggregate_constructs(candidates: pd.DataFrame, top_k: int = TOP_K) -> pd.DataFrame:
|
|
85
|
+
"""Produce one response-blind aggregate score per vaccine construct."""
|
|
86
|
+
missing = sorted(REQUIRED_COLUMNS - set(candidates.columns))
|
|
87
|
+
if missing:
|
|
88
|
+
raise ValueError(f"Scored candidates are missing columns: {missing}")
|
|
89
|
+
if top_k < 1:
|
|
90
|
+
raise ValueError("top_k must be positive")
|
|
91
|
+
|
|
92
|
+
rows = candidates.copy()
|
|
93
|
+
rows["candidate_evidence"] = candidate_evidence(rows)
|
|
94
|
+
rows["presentation_binding_eligible"] = (
|
|
95
|
+
rows["mhcflurry_2_3_0_presentation_percentile"].to_numpy(float)
|
|
96
|
+
<= PRESENTATION_PERCENTILE_GATE
|
|
97
|
+
) & (rows["netmhcpan_ba_rank"].to_numpy(float) <= BA_RANK_GATE)
|
|
98
|
+
rows["gated_candidate_evidence"] = rows["candidate_evidence"].where(
|
|
99
|
+
rows["presentation_binding_eligible"], 0.0
|
|
100
|
+
)
|
|
101
|
+
available_taxonomy = {
|
|
102
|
+
name: column for name, column in TAXONOMY_WEIGHTS.items() if column in rows
|
|
103
|
+
}
|
|
104
|
+
for name, column in available_taxonomy.items():
|
|
105
|
+
values = rows[column].to_numpy(float)
|
|
106
|
+
if not np.isfinite(values).all() or ((values < 0) | (values > 1)).any():
|
|
107
|
+
raise ValueError(f"Frozen taxonomy score {column} must be finite in [0, 1]")
|
|
108
|
+
# Taxonomy changes only the contribution of pMHCs that already pass
|
|
109
|
+
# the identical fixed presentation/binding gate.
|
|
110
|
+
rows[f"gated_evidence_x_{name}"] = rows["gated_candidate_evidence"] * values
|
|
111
|
+
|
|
112
|
+
# A repeated peptide/HLA pair can occur at more than one construct
|
|
113
|
+
# position. It represents one pMHC, not repeated independent evidence.
|
|
114
|
+
rows = (
|
|
115
|
+
rows.sort_values("candidate_evidence", ascending=False)
|
|
116
|
+
.drop_duplicates(["record_id", "peptide", "hla"])
|
|
117
|
+
.reset_index(drop=True)
|
|
118
|
+
)
|
|
119
|
+
identity = ["record_id", "patient", "mutation_class", "outcome"]
|
|
120
|
+
if rows.groupby("record_id")[identity[1:]].nunique().gt(1).any().any():
|
|
121
|
+
raise ValueError("Construct identity fields disagree within record_id")
|
|
122
|
+
|
|
123
|
+
aggregates = []
|
|
124
|
+
for record_id, part in rows.groupby("record_id", sort=True):
|
|
125
|
+
first = part.iloc[0]
|
|
126
|
+
evidence = part["candidate_evidence"]
|
|
127
|
+
gated = part["gated_candidate_evidence"]
|
|
128
|
+
result = {
|
|
129
|
+
"record_id": record_id,
|
|
130
|
+
"patient": first.patient,
|
|
131
|
+
"mutation_class": first.mutation_class,
|
|
132
|
+
"outcome": int(first.outcome),
|
|
133
|
+
"n_distinct_candidate_pmhcs": len(part),
|
|
134
|
+
"n_presentation_binding_eligible": int(part["presentation_binding_eligible"].sum()),
|
|
135
|
+
"best_candidate_evidence": float(evidence.max()),
|
|
136
|
+
"top3_sum_candidate_evidence": _top_k_sum(evidence, top_k),
|
|
137
|
+
"top3_soft_or_candidate_evidence": _top_k_soft_or(evidence, top_k),
|
|
138
|
+
"top3_sum_gated_candidate_evidence": _top_k_sum(gated, top_k),
|
|
139
|
+
}
|
|
140
|
+
for name in available_taxonomy:
|
|
141
|
+
result[f"top3_sum_gated_evidence_x_{name}"] = _top_k_sum(
|
|
142
|
+
part[f"gated_evidence_x_{name}"], top_k
|
|
143
|
+
)
|
|
144
|
+
aggregates.append(result)
|
|
145
|
+
return pd.DataFrame(aggregates).sort_values("record_id").reset_index(drop=True)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def evaluate_aggregates(aggregates: pd.DataFrame, bootstrap_draws: int) -> pd.DataFrame:
|
|
149
|
+
"""Evaluate fixed aggregate scores; labels are used only in this function."""
|
|
150
|
+
scores = [
|
|
151
|
+
"best_candidate_evidence",
|
|
152
|
+
"top3_sum_candidate_evidence",
|
|
153
|
+
"top3_soft_or_candidate_evidence",
|
|
154
|
+
"top3_sum_gated_candidate_evidence",
|
|
155
|
+
]
|
|
156
|
+
scores.extend(sorted(column for column in aggregates if column.startswith("top3_sum_gated_evidence_x_")))
|
|
157
|
+
subsets = {
|
|
158
|
+
"all_braun_constructs": aggregates,
|
|
159
|
+
"braun_frameshifts": aggregates.loc[aggregates["mutation_class"].eq("frameshift")],
|
|
160
|
+
}
|
|
161
|
+
rows = []
|
|
162
|
+
for subset_name, part in subsets.items():
|
|
163
|
+
y = part["outcome"].to_numpy(int)
|
|
164
|
+
best_candidate = part["best_candidate_evidence"].to_numpy(float)
|
|
165
|
+
gated_mhc = part["top3_sum_gated_candidate_evidence"].to_numpy(float)
|
|
166
|
+
for index, score_name in enumerate(scores):
|
|
167
|
+
score = part[score_name].to_numpy(float)
|
|
168
|
+
low, high, valid = group_bootstrap_delta(
|
|
169
|
+
y,
|
|
170
|
+
gated_mhc,
|
|
171
|
+
score,
|
|
172
|
+
part["patient"].astype(str).to_numpy(),
|
|
173
|
+
bootstrap_draws,
|
|
174
|
+
20261030 + index,
|
|
175
|
+
)
|
|
176
|
+
rows.append(
|
|
177
|
+
{
|
|
178
|
+
"endpoint": subset_name,
|
|
179
|
+
"score": score_name,
|
|
180
|
+
"n_constructs": len(part),
|
|
181
|
+
"n_positive": int(y.sum()),
|
|
182
|
+
"n_patients": int(part["patient"].nunique()),
|
|
183
|
+
"roc_auc": float(roc_auc_score(y, score)),
|
|
184
|
+
"average_precision": float(average_precision_score(y, score)),
|
|
185
|
+
"delta_auc_vs_best_candidate": float(
|
|
186
|
+
roc_auc_score(y, score) - roc_auc_score(y, best_candidate)
|
|
187
|
+
),
|
|
188
|
+
"delta_auc_vs_gated_mhc": float(
|
|
189
|
+
roc_auc_score(y, score) - roc_auc_score(y, gated_mhc)
|
|
190
|
+
),
|
|
191
|
+
"delta_auc_vs_gated_mhc_low": low,
|
|
192
|
+
"delta_auc_vs_gated_mhc_high": high,
|
|
193
|
+
"gated_mhc_bootstrap_valid": valid,
|
|
194
|
+
}
|
|
195
|
+
)
|
|
196
|
+
return pd.DataFrame(rows)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def write_analysis(output: Path, metrics: pd.DataFrame) -> None:
|
|
200
|
+
"""Document fixed rules and descriptive held-out results."""
|
|
201
|
+
result_rows = "\n".join(
|
|
202
|
+
"| "
|
|
203
|
+
+ " | ".join(
|
|
204
|
+
[
|
|
205
|
+
row.endpoint.replace("_", " "),
|
|
206
|
+
row.score.replace("_", " "),
|
|
207
|
+
str(row.n_constructs),
|
|
208
|
+
str(row.n_positive),
|
|
209
|
+
f"{row.roc_auc:.4f}",
|
|
210
|
+
f"{row.average_precision:.4f}",
|
|
211
|
+
f"{row.delta_auc_vs_gated_mhc:+.4f} [{row.delta_auc_vs_gated_mhc_low:+.4f}, {row.delta_auc_vs_gated_mhc_high:+.4f}]",
|
|
212
|
+
]
|
|
213
|
+
)
|
|
214
|
+
+ " |"
|
|
215
|
+
for row in metrics.itertuples(index=False)
|
|
216
|
+
)
|
|
217
|
+
text = f"""# Mutation-aware Braun construct aggregation
|
|
218
|
+
|
|
219
|
+
## Fixed candidate evidence
|
|
220
|
+
|
|
221
|
+
For each reference-absent 8--11mer candidate paired with the construct's
|
|
222
|
+
annotated HLA, the label-free pMHC evidence is
|
|
223
|
+
|
|
224
|
+
$$e_i = \\sqrt{{p_{{\\mathrm{{MHCflurry\\ presentation}},i}}
|
|
225
|
+
(1 - r_{{\\mathrm{{NetMHCpan\\ BA}},i}}/100)}}.$$
|
|
226
|
+
|
|
227
|
+
MHCflurry presentation is already its presentation model, including its learned
|
|
228
|
+
processing component. We therefore do not add the raw MHCflurry processing
|
|
229
|
+
score again and double-count that signal.
|
|
230
|
+
|
|
231
|
+
The prespecified main construct score is the **sum of the three largest distinct
|
|
232
|
+
peptide--HLA evidence values**. It is an additive evidence score rather than a
|
|
233
|
+
number of passing pMHCs. `best candidate` and `top3 soft or` are fixed controls.
|
|
234
|
+
The stricter `gated` sensitivity only lets a candidate contribute when
|
|
235
|
+
MHCflurry presentation percentile is at most {PRESENTATION_PERCENTILE_GATE:g} and
|
|
236
|
+
NetMHCpan BA rank is at most {BA_RANK_GATE:g}; neither threshold was selected on
|
|
237
|
+
Braun outcomes.
|
|
238
|
+
|
|
239
|
+
When present, each `gated evidence x ...` score uses the *identical* gate and
|
|
240
|
+
multiplies each eligible candidate's evidence by one frozen broad-nine ESM
|
|
241
|
+
taxonomy output before taking its top-three sum: `1 - P(mammals)`, independent
|
|
242
|
+
`P(viruses)`, or `microbial like = max[P(virus), P(bacterium), P(archaeon),
|
|
243
|
+
P(fungus), P(protist)]`. These independent sigmoid outputs are scores, not a
|
|
244
|
+
probability partition; microbial-like is deliberately a conservative pathogen
|
|
245
|
+
proxy. The taxonomy model and transforms were selected without Braun response
|
|
246
|
+
labels.
|
|
247
|
+
|
|
248
|
+
The candidate enumerator's reference-absence flag is still an operational proxy
|
|
249
|
+
for mutation overlap, not proof of it. These construct-level outcomes are used
|
|
250
|
+
only below to evaluate precomputed scores, never to construct them.
|
|
251
|
+
|
|
252
|
+
## Descriptive evaluation
|
|
253
|
+
|
|
254
|
+
`ΔAUC` uses a paired patient-bootstrap interval relative to the pMHC-only
|
|
255
|
+
gated top-three sum—identical candidate rule and gate, with Weirdo omitted.
|
|
256
|
+
This small cohort is not used to select one aggregation rule.
|
|
257
|
+
|
|
258
|
+
| Endpoint | Score | Constructs | Positive | AUC | AP | ΔAUC vs gated pMHC-only, 95% patient-bootstrap interval |
|
|
259
|
+
|---|---|---:|---:|---:|---:|---:|
|
|
260
|
+
{result_rows}
|
|
261
|
+
|
|
262
|
+
## Outputs
|
|
263
|
+
|
|
264
|
+
- [`raw/construct-aggregates.csv.gz`](raw/construct-aggregates.csv.gz)
|
|
265
|
+
- [`tables/aggregate-metrics.csv`](tables/aggregate-metrics.csv)
|
|
266
|
+
- [`raw/provenance.json`](raw/provenance.json)
|
|
267
|
+
"""
|
|
268
|
+
(output / "analysis.md").write_text(text)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def main() -> None:
|
|
272
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
273
|
+
parser.add_argument("--candidates", type=Path, required=True)
|
|
274
|
+
parser.add_argument("--output", type=Path, required=True)
|
|
275
|
+
parser.add_argument("--bootstrap-draws", type=int, default=10_000)
|
|
276
|
+
args = parser.parse_args()
|
|
277
|
+
if args.bootstrap_draws < 100:
|
|
278
|
+
parser.error("--bootstrap-draws must be at least 100")
|
|
279
|
+
|
|
280
|
+
candidates = pd.read_csv(args.candidates, low_memory=False)
|
|
281
|
+
aggregates = aggregate_constructs(candidates)
|
|
282
|
+
metrics = evaluate_aggregates(aggregates, args.bootstrap_draws)
|
|
283
|
+
raw = args.output / "raw"
|
|
284
|
+
tables = args.output / "tables"
|
|
285
|
+
raw.mkdir(parents=True, exist_ok=True)
|
|
286
|
+
tables.mkdir(parents=True, exist_ok=True)
|
|
287
|
+
aggregates.to_csv(raw / "construct-aggregates.csv.gz", index=False, compression="gzip")
|
|
288
|
+
metrics.to_csv(tables / "aggregate-metrics.csv", index=False)
|
|
289
|
+
(raw / "provenance.json").write_text(
|
|
290
|
+
json.dumps(
|
|
291
|
+
{
|
|
292
|
+
"schema": "braun-mutation-aware-pmhc-aggregation-v1",
|
|
293
|
+
"candidate_input": str(args.candidates),
|
|
294
|
+
"top_k": TOP_K,
|
|
295
|
+
"presentation_percentile_gate": PRESENTATION_PERCENTILE_GATE,
|
|
296
|
+
"netmhcpan_ba_rank_gate": BA_RANK_GATE,
|
|
297
|
+
"response_labels_used_to_construct_scores": False,
|
|
298
|
+
"response_labels_used_only_for": "descriptive evaluation",
|
|
299
|
+
"candidate_evidence": "sqrt(mhcflurry_presentation * (1 - netmhcpan_ba_rank / 100))",
|
|
300
|
+
},
|
|
301
|
+
indent=2,
|
|
302
|
+
sort_keys=True,
|
|
303
|
+
)
|
|
304
|
+
+ "\n"
|
|
305
|
+
)
|
|
306
|
+
write_analysis(args.output, metrics)
|
|
307
|
+
print(metrics.to_string(index=False, float_format=lambda value: f"{value:+.4f}"))
|
|
308
|
+
print(f"Wrote mutation-aware construct aggregation to {args.output}")
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
if __name__ == "__main__":
|
|
312
|
+
main()
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Enumerate mutation-aware candidate pMHCs from Braun vaccine constructs.
|
|
3
|
+
|
|
4
|
+
Candidates are every 8--11mer from a vaccinated long construct that is absent
|
|
5
|
+
from the supplied human reference proteome. This is a conservative operational
|
|
6
|
+
definition, not proof of the mutation coordinate: a reference-absent peptide
|
|
7
|
+
can arise from an unrepresented isoform, while a mutant peptide can happen to
|
|
8
|
+
occur elsewhere in human. The output retains both the filter status and every
|
|
9
|
+
construct coordinate so those edge cases remain auditable.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import pandas as pd
|
|
18
|
+
|
|
19
|
+
from scripts import peptide_content_data as content
|
|
20
|
+
from scripts.prepare_external_neoantigen_benchmarks import braun_annotated_constructs
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def windows(sequence: str, minimum: int = 8, maximum: int = 11) -> list[tuple[str, int]]:
|
|
24
|
+
"""Return each contiguous peptide and zero-based construct coordinate."""
|
|
25
|
+
return [
|
|
26
|
+
(sequence[start : start + length], start)
|
|
27
|
+
for length in range(minimum, maximum + 1)
|
|
28
|
+
for start in range(max(0, len(sequence) - length + 1))
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def reference_present(candidates: set[str], reference_sequences: list[str]) -> set[str]:
|
|
33
|
+
"""Find candidate strings occurring anywhere in the reference proteome."""
|
|
34
|
+
try:
|
|
35
|
+
import ahocorasick
|
|
36
|
+
except ImportError: # pragma: no cover - optional speedup dependency
|
|
37
|
+
return {
|
|
38
|
+
candidate
|
|
39
|
+
for candidate in candidates
|
|
40
|
+
if any(candidate in sequence for sequence in reference_sequences)
|
|
41
|
+
}
|
|
42
|
+
automaton = ahocorasick.Automaton()
|
|
43
|
+
for candidate in candidates:
|
|
44
|
+
automaton.add_word(candidate, candidate)
|
|
45
|
+
automaton.make_automaton()
|
|
46
|
+
present: set[str] = set()
|
|
47
|
+
for sequence in reference_sequences:
|
|
48
|
+
for _, candidate in automaton.iter(sequence):
|
|
49
|
+
present.add(candidate)
|
|
50
|
+
return present
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def build_candidates(constructs: pd.DataFrame, reference_sequences: list[str]) -> pd.DataFrame:
|
|
54
|
+
"""Expand each construct into annotated candidate/HLA pairs."""
|
|
55
|
+
rows = []
|
|
56
|
+
for item in constructs.itertuples(index=False):
|
|
57
|
+
for peptide, start in windows(item.vaccine_peptide):
|
|
58
|
+
for hla in item.alleles:
|
|
59
|
+
rows.append(
|
|
60
|
+
{
|
|
61
|
+
"record_id": item.record_id,
|
|
62
|
+
"patient": item.patient,
|
|
63
|
+
"mutation": item.mutation,
|
|
64
|
+
"mutation_class": item.mutation_class,
|
|
65
|
+
"construct_id": item.construct_id,
|
|
66
|
+
"vaccine_peptide": item.vaccine_peptide,
|
|
67
|
+
"outcome": item.outcome,
|
|
68
|
+
"peptide": peptide,
|
|
69
|
+
"hla": hla,
|
|
70
|
+
"construct_start": start,
|
|
71
|
+
"is_nominated_short_epitope": peptide == item.peptide,
|
|
72
|
+
}
|
|
73
|
+
)
|
|
74
|
+
result = pd.DataFrame(rows)
|
|
75
|
+
present = reference_present(set(result["peptide"]), reference_sequences)
|
|
76
|
+
result["present_in_human_reference"] = result["peptide"].isin(present)
|
|
77
|
+
result["reference_absent_candidate"] = ~result["present_in_human_reference"]
|
|
78
|
+
return result
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def main() -> None:
|
|
82
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
83
|
+
parser.add_argument("--braun", type=Path, required=True)
|
|
84
|
+
parser.add_argument("--human-dat-dir", type=Path, required=True)
|
|
85
|
+
parser.add_argument("--output", type=Path, required=True)
|
|
86
|
+
args = parser.parse_args()
|
|
87
|
+
constructs = braun_annotated_constructs(args.braun)
|
|
88
|
+
constructs.insert(0, "record_id", "braun_construct:" + constructs["construct_id"].astype(str))
|
|
89
|
+
proteins = list(content.iter_swissprot_records(content.division_path(args.human_dat_dir, "human"), "human"))
|
|
90
|
+
candidates = build_candidates(constructs, [protein.sequence for protein in proteins])
|
|
91
|
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
candidates.to_csv(args.output, index=False, compression="gzip" if args.output.suffix == ".gz" else None)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
if __name__ == "__main__":
|
|
96
|
+
main()
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Build a fresh T-cell confirmation cohort from IEDB studies never used before.
|
|
3
|
+
|
|
4
|
+
Protocol (frozen before any scoring):
|
|
5
|
+
|
|
6
|
+
* source: the local IEDB T-cell assay pages under ``data/viral-tcell-benchmark``,
|
|
7
|
+
or, with ``--assays``, the full human class I API pull from
|
|
8
|
+
``pull_iedb_human_class_i.py``;
|
|
9
|
+
* keep human host, class I, exact ``HLA-A/B/C*xx:xx`` restriction, canonical
|
|
10
|
+
8-14mers and a known positive/negative qualitative outcome;
|
|
11
|
+
* a (peptide, HLA) pair is positive if any assay for it is positive;
|
|
12
|
+
* keep only PMIDs that contributed neither to development nor validation
|
|
13
|
+
(``used``) and that have at least one positive and one negative pair;
|
|
14
|
+
* purge every exact peptide that appears in any dataset used for development,
|
|
15
|
+
screening or validation (IMPROVE, registered viral, TESLA, Braun), so the
|
|
16
|
+
cohort shares no peptide with anything scored before;
|
|
17
|
+
* clusters for bootstrap are PMIDs.
|
|
18
|
+
|
|
19
|
+
Weights of the evaluated score are fixed beforehand (shipped defaults).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import glob
|
|
26
|
+
import json
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
import re
|
|
29
|
+
|
|
30
|
+
import pandas as pd
|
|
31
|
+
|
|
32
|
+
CANONICAL = re.compile(r"^[ACDEFGHIKLMNPQRSTVWY]{8,14}$")
|
|
33
|
+
EXACT_HLA_I = re.compile(r"^HLA-[ABC]\*\d{2,3}:\d{2,3}$")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def positive(value: object) -> int | None:
|
|
37
|
+
text = str(value or "").lower()
|
|
38
|
+
if text.startswith("positive"):
|
|
39
|
+
return 1
|
|
40
|
+
if text.startswith("negative"):
|
|
41
|
+
return 0
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def used_pmids(root: Path, choices: Path) -> set[str]:
|
|
46
|
+
"""PMIDs used in any earlier development, screening or validation report."""
|
|
47
|
+
used: set[str] = set()
|
|
48
|
+
for report in choices.glob("*-report.json"):
|
|
49
|
+
payload = json.loads(report.read_text())
|
|
50
|
+
for row in payload.get("data_funnel", {}).get("audit", []):
|
|
51
|
+
if row.get("included"):
|
|
52
|
+
used.add(str(row["cohort"]))
|
|
53
|
+
used.update(pd.read_csv(root / "scored-assays.csv", usecols=["cohort"])["cohort"].astype(str))
|
|
54
|
+
return used
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def used_peptides(root: Path, improve: Path, tesla: Path, external: Path) -> set[str]:
|
|
58
|
+
"""Every peptide sequence already seen in a scored dataset."""
|
|
59
|
+
peptides = set(pd.read_csv(root / "scored-assays.csv", usecols=["peptide"])["peptide"])
|
|
60
|
+
peptides |= set(pd.read_csv(improve, sep="\t", usecols=["Mut_peptide", "Norm_peptide"]).stack().dropna())
|
|
61
|
+
peptides |= set(pd.read_excel(tesla)["peptide"])
|
|
62
|
+
peptides |= set(pd.read_csv(external, usecols=["peptide"])["peptide"])
|
|
63
|
+
return peptides
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def main() -> None:
|
|
67
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
68
|
+
parser.add_argument("--iedb-root", type=Path, default=Path("data/viral-tcell-benchmark"))
|
|
69
|
+
parser.add_argument("--choices", type=Path, default=Path("data/foreignness-choices"))
|
|
70
|
+
parser.add_argument("--improve", type=Path, required=True)
|
|
71
|
+
parser.add_argument("--tesla", type=Path, required=True)
|
|
72
|
+
parser.add_argument("--external", type=Path, required=True)
|
|
73
|
+
parser.add_argument("--assays", type=Path, help="CSV from pull_iedb_human_class_i.py")
|
|
74
|
+
parser.add_argument("--exclude-cohort", type=Path, nargs="*", default=[],
|
|
75
|
+
help="earlier fresh cohorts whose studies and peptides are also spent")
|
|
76
|
+
parser.add_argument("--output", type=Path, required=True)
|
|
77
|
+
args = parser.parse_args()
|
|
78
|
+
|
|
79
|
+
pairs: dict[tuple[str, str, str], list[int]] = {}
|
|
80
|
+
meta: dict[str, str] = {}
|
|
81
|
+
|
|
82
|
+
def add(row: dict) -> None:
|
|
83
|
+
raw_pmid = row.get("reference__pmid")
|
|
84
|
+
pmid = "" if pd.isna(raw_pmid) else str(raw_pmid).removesuffix(".0")
|
|
85
|
+
peptide = str(row.get("assay_antigen__name") or row.get("epitope__name") or "").upper()
|
|
86
|
+
hla = str(row.get("mhc_restriction__name") or "")
|
|
87
|
+
outcome = positive(row.get("assay__qualitative_measurement"))
|
|
88
|
+
if not pmid or outcome is None or not CANONICAL.fullmatch(peptide) or not EXACT_HLA_I.fullmatch(hla):
|
|
89
|
+
return
|
|
90
|
+
if row.get("host__name") != "Homo sapiens (human)" or row.get("mhc_restriction__class") != "I":
|
|
91
|
+
return
|
|
92
|
+
pairs.setdefault((pmid, peptide, hla), []).append(outcome)
|
|
93
|
+
organism = row.get("epitope__source_organism")
|
|
94
|
+
meta[pmid] = organism if isinstance(organism, str) else ""
|
|
95
|
+
|
|
96
|
+
if args.assays:
|
|
97
|
+
for row in pd.read_csv(args.assays, low_memory=False).to_dict("records"):
|
|
98
|
+
add(row)
|
|
99
|
+
else:
|
|
100
|
+
for path in sorted(glob.glob(str(args.iedb_root / "iedb-*-page-*.json"))):
|
|
101
|
+
for row in json.loads(Path(path).read_text()):
|
|
102
|
+
add(row)
|
|
103
|
+
table = pd.DataFrame(
|
|
104
|
+
[{"pmid": p, "peptide": s, "hla": h, "outcome": int(any(v)), "source_organism": meta[p]}
|
|
105
|
+
for (p, s, h), v in pairs.items()]
|
|
106
|
+
)
|
|
107
|
+
seen_pmids = used_pmids(args.iedb_root, args.choices)
|
|
108
|
+
seen_peptides = used_peptides(args.iedb_root, args.improve, args.tesla, args.external)
|
|
109
|
+
for earlier in args.exclude_cohort:
|
|
110
|
+
spent = pd.read_csv(earlier, dtype={"pmid": str})
|
|
111
|
+
seen_pmids |= set(spent["pmid"])
|
|
112
|
+
seen_peptides |= set(spent["peptide"])
|
|
113
|
+
funnel = {"pairs": len(table), "pmids": int(table["pmid"].nunique())}
|
|
114
|
+
table = table.loc[~table["pmid"].isin(seen_pmids)]
|
|
115
|
+
funnel["after_unused_pmids"] = len(table)
|
|
116
|
+
table = table.loc[~table["peptide"].isin(seen_peptides)]
|
|
117
|
+
funnel["after_peptide_purge"] = len(table)
|
|
118
|
+
balanced = table.groupby("pmid")["outcome"].agg(["min", "max"])
|
|
119
|
+
keep = balanced.index[(balanced["min"] == 0) & (balanced["max"] == 1)]
|
|
120
|
+
table = table.loc[table["pmid"].isin(keep)].reset_index(drop=True)
|
|
121
|
+
funnel.update(
|
|
122
|
+
final_pairs=len(table), final_pmids=int(table["pmid"].nunique()),
|
|
123
|
+
positives=int(table["outcome"].sum()), unique_peptides=int(table["peptide"].nunique()),
|
|
124
|
+
)
|
|
125
|
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
126
|
+
table.to_csv(args.output, index=False)
|
|
127
|
+
args.output.with_suffix(".funnel.json").write_text(json.dumps(funnel, indent=2))
|
|
128
|
+
print(json.dumps(funnel, indent=2))
|
|
129
|
+
print(table.groupby("pmid").agg(n=("outcome", "size"), pos=("outcome", "sum"), organism=("source_organism", "first")).sort_values("n", ascending=False).head(15))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if __name__ == "__main__":
|
|
133
|
+
main()
|