diff --git a/tests/test_cli_errors.py b/tests/test_cli_errors.py index ddbea95b..04f3c0ee 100644 --- a/tests/test_cli_errors.py +++ b/tests/test_cli_errors.py @@ -455,3 +455,24 @@ def test_final_outputs_block_lists_what_was_written(tmp_path, capsys): assert "Outputs written:" in err assert str(out / "ranked_candidates.csv") in err assert str(out / "run_summary.txt") in err + + +def test_vaxrank_version_replaces_upstream_parser_version(monkeypatch, capsys): + """varcode>=11.18.0 adds --version in make_variants_parser (openvax/varcode#759).""" + from vaxrank.cli import arg_parser + from vaxrank.version import __version__ + + real_make = arg_parser.make_isovar_arg_parser + + def make_with_upstream_version(*args, **kwargs): + parser = real_make(*args, **kwargs) + if '--version' not in parser._option_string_actions: + parser.add_argument('--version', action='version', version='varcode 11.18.0') + return parser + + monkeypatch.setattr(arg_parser, 'make_isovar_arg_parser', make_with_upstream_version) + parser = arg_parser.make_vaxrank_arg_parser() + with pytest.raises(SystemExit) as exit_info: + parser.parse_args(['--version']) + assert exit_info.value.code == 0 + assert f"Vaxrank {__version__}" in capsys.readouterr().out diff --git a/tests/test_cta_targeting.py b/tests/test_cta_targeting.py index ba478f48..dee7d747 100644 --- a/tests/test_cta_targeting.py +++ b/tests/test_cta_targeting.py @@ -363,3 +363,196 @@ def test_admission_only_saved_cta_retains_reference_policy(bundle, monkeypatch, lambda path: SimpleNamespace(identity='oncoref:different')) with pytest.raises(ValueError, match='Saved CTA targeting retains'): report_config([report], EpitopeConfig(cta_sequence_bundle='/different')) + + +def _target_selection_fixture(): + import hashlib + context = ReferenceContext.from_genome(EnsemblRelease(115)) + reference = dict( + taxon_id=9606, assembly_accession=context.assembly_accession, + annotation_source='Ensembl', annotation_release='115', + identifier_namespaces={'gene': 'Ensembl gene', 'transcript': 'Ensembl transcript', + 'protein': 'Ensembl protein'}, reference_id='fixture-reference', + ) + genes = { + 'CTA_GENE': ('ENSG00000185686', 'PRAME', 'SIINFEKLGILGFVFTL', 'allow', True), + 'RESCUED_CTA': ('ENSG00000046774', 'MAGEC2', 'MNPQRSTVWYACDEFGH', 'review', False), + 'CA_ONLY': ('ENSG00000186919', 'ZACN', 'KLMNPQRSTVWYACDEF', 'allow', True), + 'UNSCREENED': ('ENSG00000184478', 'OR56A3', 'ACDEFGHIKLMNPQRST', 'allow', True), + 'REVIEW_GENE': ('ENSG00000213973', 'ZNF99', 'VWXYZZZZZZZZZZZZZ'.replace('X', 'A').replace('Z', 'L'), 'allow', True), + 'NEWLY_UNSAFE': ('ENSG00000122136', 'OBP2A', 'AASIINFEKLGKK', 'allow', True), + } + rows = [] + for rec_id, (gid, sym, seq, role, qualified) in genes.items(): + rows.append(dict( + record_id=rec_id, + sequence=seq, + sequence_sha256=hashlib.sha256(seq.encode()).hexdigest(), + shared_sequence=role, + direct_target_candidate=qualified, + valid_segments=[dict(start=0, end=len(seq))], + occurrences=[dict( + gene_id=gid, gene_name=sym, transcript_id='ENST00000000001.1', + direct_target_candidate=qualified, shared_sequence=role, + )], + )) + + def segments(**kwargs): + for row in rows: + for interval in row['valid_segments']: + yield dict(**interval, sequence=row['sequence'][interval['start']:interval['end']], + record_id=row['record_id'], shared_sequence=row['shared_sequence'], + occurrences=row['occurrences']) + + bundle = SimpleNamespace( + identity='oncoref:fixture-ts', manifest={'reference': reference}, + coverage={'fixture': True}, records=lambda: iter(rows), segments=segments, + ) + ts_index = dict( + policy_id='oncoref.target-selection.test.1', + reference_id='fixture-reference', + oncoref_version='1.43.0', + by_gene={ + 'ENSG00000185686': dict( + entity_id='e1', protein_group_label='PRAME', category='CTA', subtype='', + classification='CTA', decision_reason='Cancer and reproductive qualify', + cta_tier='core', + representative_sequence_sha256s=frozenset({rows[0]['sequence_sha256']}), + representative_transcripts=frozenset({'ENST00000000001.1'}), + ), + 'ENSG00000046774': dict( + entity_id='e2', protein_group_label='MAGEC2', category='CTA', subtype='', + classification='CTA', decision_reason='Cancer and reproductive qualify', + cta_tier='core', + representative_sequence_sha256s=frozenset({rows[1]['sequence_sha256']}), + representative_transcripts=frozenset({'ENST00000000001.1'}), + ), + 'ENSG00000186919': dict( + entity_id='e3', protein_group_label='ZACN', category='Cancer Antigen only', subtype='', + classification='Cancer Antigen only', + decision_reason='Cancer tenfold qualifies; reproductive does not', + cta_tier='', + representative_sequence_sha256s=frozenset({rows[2]['sequence_sha256']}), + representative_transcripts=frozenset({'ENST00000000001.1'}), + ), + 'ENSG00000184478': dict( + entity_id='e4', protein_group_label='OR56A3', category='Other', subtype='Unscreened tissue', + classification='Other:Unscreened tissue', + decision_reason='Normal home is olfactory epithelium', + cta_tier='', + representative_sequence_sha256s=frozenset({rows[3]['sequence_sha256']}), + representative_transcripts=frozenset({'ENST00000000001.1'}), + ), + 'ENSG00000213973': dict( + entity_id='e5', protein_group_label='ZNF99', category='Other', subtype='Review', + classification='Other:Review', + decision_reason='Normal-expression evidence blocks admission', + cta_tier='', + representative_sequence_sha256s=frozenset({rows[4]['sequence_sha256']}), + representative_transcripts=frozenset({'ENST00000000001.1'}), + ), + 'ENSG00000122136': dict( + entity_id='e6', protein_group_label='OBP2A', category='Unsafe', subtype='', + classification='Unsafe', + decision_reason='Published normal-tissue expression', + cta_tier='', + representative_sequence_sha256s=frozenset({rows[5]['sequence_sha256']}), + representative_transcripts=frozenset({'ENST00000000001.1'}), + ), + }, + ) + return bundle, ts_index + + +def test_target_selection_admits_rescued_cta_and_blocks_other_and_unsafe(tmp_path): + from vaxrank.antigen_biology import antigen_biology + from vaxrank.coding_context import antigen_source_label + + bundle, ts_index = _target_selection_fixture() + expr = tmp_path / 'expr.tsv' + expr.write_text( + 'feature_id\tpatient_tpm\n' + 'ENSG00000185686\t20.0\n' + 'ENSG00000046774\t51.8\n' + 'ENSG00000186919\t25.3\n' + 'ENSG00000184478\t3.9\n' + 'ENSG00000213973\t8.8\n' + 'ENSG00000122136\t16.4\n' + ) + scope = InputScope( + patient_id='p1', reference_assembly='GRCh38', annotation='ensembl:115', + host_taxon_id=9606, mhc_alleles=('HLA-A*02:01',), + ) + + cta_only = admit_expression( + expr, contract(), CTAAdmissionPolicy(2.0, 'TPM'), bundle, scope, + target_policy='target_selection', target_selection_index=ts_index, + ) + by_id = {d.input_identifier: d for d in cta_only.decisions} + assert by_id['ENSG00000185686'].status == 'admitted' + assert by_id['ENSG00000046774'].status == 'admitted' # Rescued MAGEC2 CTA + assert by_id['ENSG00000186919'].status == 'not_current_cta' # Cancer Antigen only excluded in CTA-only + assert by_id['ENSG00000184478'].status == 'blocked_target_selection' + assert by_id['ENSG00000184478'].gene_identity['target_selection_classification'] == 'Other:Unscreened tissue' + assert by_id['ENSG00000213973'].status == 'blocked_target_selection' + assert by_id['ENSG00000213973'].gene_identity['target_selection_classification'] == 'Other:Review' + assert by_id['ENSG00000122136'].status == 'unsafe_reference' + assert cta_only.target_reference['target_policy'] == 'target_selection' + assert cta_only.target_reference['target_selection']['policy_id'] == 'oncoref.target-selection.test.1' + + with_ca = admit_expression( + expr, contract(), CTAAdmissionPolicy(2.0, 'TPM'), bundle, scope, + target_policy='target_selection_cancer_antigens', target_selection_index=ts_index, + ) + ca_by_id = {d.input_identifier: d for d in with_ca.decisions} + assert ca_by_id['ENSG00000186919'].status == 'admitted' + assert ca_by_id['ENSG00000184478'].status == 'blocked_target_selection' + assert ca_by_id['ENSG00000213973'].status == 'blocked_target_selection' + assert ca_by_id['ENSG00000122136'].status == 'unsafe_reference' + zacn = ca_by_id['ENSG00000186919'].assessment.antigen + prame = ca_by_id['ENSG00000185686'].assessment.antigen + assert antigen_source_label(zacn) == 'Cancer Antigen only' + assert antigen_source_label(prame) == 'CTA' + view = antigen_biology(zacn) + assert ('OncoRef target class', 'Cancer Antigen only (oncoref.target-selection.test.1)') in view['facts'] + + +def test_target_selection_containment_excludes_newly_unsafe_and_reviews_other(): + bundle, ts_index = _target_selection_fixture() + data = dataset() + # SIINFEKL is in PRAME (CTA) and OBP2A (newly Unsafe under target_selection!) + # GILGFVFTL is only in PRAME (CTA) + # ACDEFGHIK is in OR56A3 (Other:Unscreened tissue under target_selection -> review) + # LMNPQRSTV is in OR56A3 (Other:Unscreened tissue -> review) + apply_cta_targeting(data, bundle, target_policy='target_selection', target_selection_index=ts_index) + statuses = [targeting_evidence(e)['status'] for e in data.epitopes] + assert statuses == ['excluded', 'eligible', 'review', 'review'] + assert [e.is_targetable for e in data.epitopes] == [False, True, False, False] + assert data.epitopes[0].occurs_in_non_CTA_reference is True + assert data.epitopes[0].self_reference_match.sources[0].gene_name == 'OBP2A' + assert data.epitopes[2].occurs_in_non_CTA_reference is False + assert targeting_evidence(data.epitopes[1])['target_policy'] == 'target_selection' + assert targeting_evidence(data.epitopes[1])['target_selection_policy_id'] == 'oncoref.target-selection.test.1' + + +def test_target_policy_config_validation_and_replay_consistency(): + from msgspec.structs import replace as replace_config + from vaxrank.external_rescoring import report_config + + with pytest.raises(ValueError, match='Unknown cta_target_policy'): + EpitopeConfig(cta_sequence_bundle='current', cta_target_policy='bogus') + with pytest.raises(ValueError, match='cta_target_policy requires cta_sequence_bundle'): + EpitopeConfig(cta_target_policy='target_selection') + + bundle, ts_index = _target_selection_fixture() + first = dataset() + apply_cta_targeting(first, bundle, target_policy='target_selection', target_selection_index=ts_index) + first.config = replace_config( + first.config, cta_sequence_bundle='current', cta_target_policy='target_selection') + report = SimpleNamespace(dataset=first, source_format='epitopes') + resolved = report_config([report], EpitopeConfig(score_expr='2.0')) + assert resolved.cta_sequence_bundle == 'current' + assert resolved.cta_target_policy == 'target_selection' + with pytest.raises(ValueError, match='Saved CTA targeting retains its target policy'): + report_config([report], EpitopeConfig( + cta_sequence_bundle='current', cta_target_policy='target_selection_cancer_antigens')) diff --git a/tests/test_hitlist_evidence.py b/tests/test_hitlist_evidence.py index dc312547..966e0463 100644 --- a/tests/test_hitlist_evidence.py +++ b/tests/test_hitlist_evidence.py @@ -381,3 +381,103 @@ def test_ms_scaling_cli_keeps_components_and_replays_without_data( replayed = EpitopeDataset.load(second / 'candidate_predictions.tsv') assert [e.ms_scoring for e in replayed.epitopes] == [e.ms_scoring for e in original.epitopes] assert (first / 'vaccine.fasta').read_bytes() == (second / 'vaccine.fasta').read_bytes() + + +def test_hitlist_2124_bundle_policy_columns_and_policy_verification(tmp_path, monkeypatch): + from importlib.metadata import version as pkg_version + from types import SimpleNamespace + from vaxrank.cta_input import load_hitlist_bundle + + bundle = dict( + manifest={'kind': 'cta_expression'}, + artifacts={ + 'peptides.parquet': { + 'columns': [ + 'peptide', 'n_ms_observations', 'cta_specific', 'avoid_sequence', + 'tissue_review_required', 'n_essential_tissue_donors', + 'has_policy_unsafe_match', 'policy_categories', 'avoid_reasons', + ], + 'rows': [ + dict( + peptide='SIINFEKL', + n_ms_observations=4, + cta_specific=True, + avoid_sequence=False, + tissue_review_required=False, + n_essential_tissue_donors=0, + has_policy_unsafe_match=False, + policy_categories='["CTA"]', + avoid_reasons='', + ), + dict( + peptide='GILGFVFTL', + n_ms_observations=1, + cta_specific=False, + avoid_sequence=True, + tissue_review_required=False, + n_essential_tissue_donors=0, + has_policy_unsafe_match=True, + policy_categories='["CTA", "Unsafe"]', + avoid_reasons='non_cta_reference_match;policy_unsafe_reference_match', + ), + ], + }, + 'presentation.parquet': {'columns': [], 'rows': []}, + }, + ) + frame = hitlist_annotations(['SIINFEKL', 'GILGFVFTL'], bundle, [ALLELES[0], ALLELES[0]]) + assert frame.hitlist_policy_unsafe_match.tolist() == [False, True] + assert frame.hitlist_policy_categories.tolist() == ['["CTA"]', '["CTA", "Unsafe"]'] + assert frame.hitlist_avoid_reasons.tolist() == ['', 'non_cta_reference_match;policy_unsafe_reference_match'] + + # Verify load_hitlist_bundle enforces Hitlist 2.1.24 cta_policy agreement + artifact_file = tmp_path / 'meta.txt' + artifact_file.write_text('ok') + digest = hashlib.sha256(artifact_file.read_bytes()).hexdigest() + base_manifest = { + 'kind': 'cta_expression', + 'expression': { + 'oncoref_version': pkg_version('oncoref'), + 'input': {'sha256': 'a' * 64}, + 'level': 'gene', + 'id_column': 'gene_id', + 'tpm_column': 'TPM', + 'units': 'TPM', + 'ensembl_release': 115, + 'cta_policy': { + 'selector': 'target_selection', + 'policy_id': 'oncoref.target-selection.test.1', + }, + }, + 'artifacts': {'meta.txt': {'sha256': digest}}, + } + monkeypatch.setattr('hitlist.evidence_bundle.verify_evidence_bundle', lambda d: base_manifest) + contract = SimpleNamespace( + measurement_level='gene', id_column='gene_id', value_column='TPM', expression_unit='TPM', + ) + matching_admission = SimpleNamespace( + input_contract=contract, + annotation_version='115', + input_sha256='a' * 64, + target_reference={'target_selection': {'policy_id': 'oncoref.target-selection.test.1'}}, + ) + loaded = load_hitlist_bundle(tmp_path, matching_admission) + assert loaded['manifest']['expression']['cta_policy']['policy_id'] == 'oncoref.target-selection.test.1' + + mismatch_policy = SimpleNamespace( + input_contract=contract, + annotation_version='115', + input_sha256='a' * 64, + target_reference={'target_selection': {'policy_id': 'oncoref.target-selection.other'}}, + ) + with pytest.raises(ValueError, match='different target_selection policy IDs'): + load_hitlist_bundle(tmp_path, mismatch_policy) + + legacy_admission = SimpleNamespace( + input_contract=contract, + annotation_version='115', + input_sha256='a' * 64, + target_reference=None, + ) + with pytest.raises(ValueError, match='requires target_selection CTA admission'): + load_hitlist_bundle(tmp_path, legacy_admission) diff --git a/tests/test_osteosarc_selection.py b/tests/test_osteosarc_selection.py index 6c9a28a6..e8396d46 100644 --- a/tests/test_osteosarc_selection.py +++ b/tests/test_osteosarc_selection.py @@ -128,6 +128,7 @@ def test_pinned_predictions_are_complete_real_model_outputs(): assert expected_epitope_config.pop("comparison_reference") == 'annotation_reference' assert expected_epitope_config.pop("patient_background_baseline") == 'focal' assert expected_epitope_config.pop("cta_sequence_bundle") is None + assert expected_epitope_config.pop("cta_target_policy") is None assert metadata["epitope_config"] == expected_epitope_config cache = CachedPredictor.from_topiary_output(str(DATA / "netmhcpan42.tsv")) assert cache.fallback is None diff --git a/vaxrank/antigen_biology.py b/vaxrank/antigen_biology.py index de78e4eb..5a3b0765 100644 --- a/vaxrank/antigen_biology.py +++ b/vaxrank/antigen_biology.py @@ -149,6 +149,15 @@ def antigen_biology(antigen, *, source_evidence=None, peptides=()): targeting.append(row) if antigen.kind == 'CTA' and not targeting: facts.append(('Unsafe containment', 'Not assessed with the current OncoRef sequence bundle')) + if antigen.kind == 'CTA': + meta = dict(antigen.source_metadata) + ts_cat = meta.get('oncoref_target_selection_category') + ts_policy = meta.get('oncoref_target_selection_policy_id') + if ts_cat: + label = ts_cat + (f' ({ts_policy})' if ts_policy else '') + facts.append(('OncoRef target class', label)) + elif ts_policy: + facts.append(('OncoRef target policy', ts_policy)) return dict(kind=antigen_source_label(antigen, source_evidence), gene=antigen.display_gene_name, identifier=antigen.display_identifier, facts=list(dict.fromkeys(facts)), junctions=junctions, comparisons=comparisons, diff --git a/vaxrank/antigen_input.py b/vaxrank/antigen_input.py index db07eef5..abe981dd 100644 --- a/vaxrank/antigen_input.py +++ b/vaxrank/antigen_input.py @@ -395,7 +395,7 @@ def occurrence_id(name, peptide, offset): attach_antigen_backgrounds(dataset, predictor, patient_backgrounds, source_evidence) if cta_bundle is not None: from .cta_targeting import apply_cta_targeting - apply_cta_targeting(dataset, cta_bundle) + apply_cta_targeting(dataset, cta_bundle, target_policy=config.cta_target_policy) return dataset diff --git a/vaxrank/cli/arg_parser.py b/vaxrank/cli/arg_parser.py index 2e84d00c..f663f0e2 100644 --- a/vaxrank/cli/arg_parser.py +++ b/vaxrank/cli/arg_parser.py @@ -104,9 +104,7 @@ def __call__(self, parser, namespace, values, option_string=None): def make_vaxrank_arg_parser(): - # create common parser with the --version flag parent_parser = ArgumentParser('parent', add_help=False) - parent_parser.add_argument('--version', action='version', version='Vaxrank %s' % (__version__,)) parent_parser.add_argument( '--print-default-config', action=_PrintDefaultConfigAction, @@ -128,6 +126,17 @@ def make_vaxrank_arg_parser(): "reports, peptide constructs, or mRNA constructs."), parents=[parent_parser], ) + # Replace any upstream --version (e.g. varcode>=11.18.0, openvax/varcode#759) + # with Vaxrank's own version flag while preserving conflict_handler='error'. + for action in list(arg_parser._actions): + if '--version' in action.option_strings: + arg_parser._remove_action(action) + for group in (arg_parser._optionals, *arg_parser._action_groups): + if action in group._group_actions: + group._group_actions.remove(action) + for opt in action.option_strings: + arg_parser._option_string_actions.pop(opt, None) + arg_parser.add_argument('--version', action='version', version='Vaxrank %s' % (__version__,)) # None distinguishes omission from explicitly passing even the upstream # default (e.g. --min-variant-sequence-coverage 2) over a YAML override. # Resolve these only in the RNA entry point, after merging configuration. @@ -1104,6 +1113,11 @@ def add_external_rescoring_args(arg_parser): arg_parser.add_argument('--cta-sequence-bundle', metavar='PATH', help='Verified OncoRef sequence bundle for CTA peptide targeting. Use current for the installed ' 'bundle. Unsafe matches are excluded; unresolved matches require review. Saved decisions replay offline.') + arg_parser.add_argument('--cta-target-policy', + choices=('sequence_bundle', 'target_selection', 'target_selection_cancer_antigens'), + default=None, + help='OncoRef CTA target policy layered over --cta-sequence-bundle: sequence_bundle (default), ' + 'target_selection (confirmed CTA only), or target_selection_cancer_antigens (CTA + Cancer Antigen only).') arg_parser.add_argument('--host-reference', metavar='SNAPSHOT', help='Experimental: ORFdata host proteome snapshot, including selected extra ORFs.') arg_parser.add_argument('--reference-context', metavar='JSON', diff --git a/vaxrank/cli/epitope_config_args.py b/vaxrank/cli/epitope_config_args.py index 7bd27dcd..95327b3e 100644 --- a/vaxrank/cli/epitope_config_args.py +++ b/vaxrank/cli/epitope_config_args.py @@ -129,6 +129,8 @@ def epitope_config_from_args(args : argparse.Namespace, merged_config=None) -> E epitope_config_kwargs = extract_epitope_config_kwargs(merged_config) if getattr(args, 'cta_sequence_bundle', None) is not None: epitope_config_kwargs['cta_sequence_bundle'] = args.cta_sequence_bundle + if getattr(args, 'cta_target_policy', None) is not None: + epitope_config_kwargs['cta_target_policy'] = args.cta_target_policy if getattr(args, 'ms_evidence', False) or getattr(args, 'ms_evidence_package', None): options = dict(epitope_config_kwargs.get('ms_evidence') or {}) if getattr(args, 'ms_evidence_package', None): @@ -183,4 +185,5 @@ def has_epitope_config_overrides(args, merged_config): "min_epitope_score", "scoring_mode", "allele_free_evidence", "allele_selection_axis", "default_affinity_predictor", "default_stability_predictor", "default_presentation_predictor", - "comparison_reference", "patient_background_baseline", "cta_sequence_bundle")) + "comparison_reference", "patient_background_baseline", + "cta_sequence_bundle", "cta_target_policy")) diff --git a/vaxrank/coding_context.py b/vaxrank/coding_context.py index 20ff9008..facf9e52 100644 --- a/vaxrank/coding_context.py +++ b/vaxrank/coding_context.py @@ -77,5 +77,10 @@ def source_label(kind, origin=None, contexts=(), *, show_context=False): def antigen_source_label(antigen, source_evidence=None): - return source_label(antigen.kind, antigen.origin, coding_contexts(antigen, source_evidence), + base = source_label(antigen.kind, antigen.origin, coding_contexts(antigen, source_evidence), show_context=('isovar_family', 'variant_orfs') in antigen.source_metadata) + if antigen.kind == 'CTA': + ts_cat = dict(antigen.source_metadata).get('oncoref_target_selection_category') + if ts_cat and ts_cat != 'CTA' and base == 'CTA': + return ts_cat + return base diff --git a/vaxrank/construct_replay.py b/vaxrank/construct_replay.py index 517db01a..cedede73 100644 --- a/vaxrank/construct_replay.py +++ b/vaxrank/construct_replay.py @@ -273,6 +273,8 @@ def _assembly_identity(args, ranked, options, context): epitopes.pop('ms_evidence', None) if epitopes.get('cta_sequence_bundle') is None: epitopes.pop('cta_sequence_bundle', None) + if epitopes.get('cta_target_policy') is None: + epitopes.pop('cta_target_policy', None) if 'epitopes' in policy: policy['epitopes'] = epitopes definition = (graph, configuration, context, policy) diff --git a/vaxrank/cta_input.py b/vaxrank/cta_input.py index da34aeb5..7459fd8c 100644 --- a/vaxrank/cta_input.py +++ b/vaxrank/cta_input.py @@ -31,7 +31,7 @@ def validate_cta_args(args): if getattr(args, 'hitlist_evidence_bundle', None): raise ValueError('--hitlist-evidence-bundle requires --input-cta-expression') explicit = getattr(args, '_explicit_cli_args', ()) - if any(name.startswith('cta_') and name != 'cta_sequence_bundle' for name in explicit): + if any(name.startswith('cta_') and name not in ('cta_sequence_bundle', 'cta_target_policy') for name in explicit): raise ValueError('Declare CTA expression options per input in --input-manifest') required = ('cta_expression_level', 'cta_id_column', 'cta_value_column', 'cta_expression_unit', 'cta_sample_id', 'cta_expression_source', @@ -152,7 +152,7 @@ class CTAExpressionSource: @classmethod def load(cls, path, *, options, scope, genome, manifest_path=None, declarations=None, host_reference=None, - sequence_bundle=None, target_reference=None): + sequence_bundle=None, target_reference=None, target_policy=None): if host_reference is not None: scope = host_reference.validate(scope, genome=genome, location=str(path)) scope = resolve_host_scope(scope, genome, location=str(path)) @@ -181,7 +181,8 @@ def load(cls, path, *, options, scope, genome, manifest_path=None, declarations= raise ValueError('Current CTA sequence policy cannot be combined with legacy admission overrides') from .cta_targeting import admit_expression, load_bundle target_reference = target_reference or load_bundle(sequence_bundle) - admission = admit_expression(path, contract, policy, target_reference, scope) + admission = admit_expression( + path, contract, policy, target_reference, scope, target_policy=target_policy) else: admission = admit_cta_expression(path, input_contract=contract, admission_policy=policy, exclusion_policy=exclusions, genome=genome, host_reference=host_reference, @@ -216,6 +217,16 @@ def load_hitlist_bundle(path, admission): if (expression['input']['sha256'] != admission.input_sha256 or any(expression.get(k) != v for k, v in expected.items())): raise ValueError('Hitlist bundle expression/reference contract differs from this input') + bundle_cta_policy = expression.get('cta_policy') + target_ref = getattr(admission, 'target_reference', None) or {} + admission_ts = target_ref.get('target_selection') + if admission_ts is not None: + if bundle_cta_policy is None or bundle_cta_policy.get('selector') != 'target_selection': + raise ValueError('Hitlist bundle CTA policy differs from target_selection CTA admission') + if bundle_cta_policy.get('policy_id') != admission_ts.get('policy_id'): + raise ValueError('Hitlist bundle and CTA admission use different target_selection policy IDs') + elif bundle_cta_policy is not None and bundle_cta_policy.get('selector') == 'target_selection': + raise ValueError('Hitlist target_selection CTA bundle requires target_selection CTA admission') artifacts = {} files = {} for name in manifest['artifacts']: @@ -332,9 +343,14 @@ def annotate(frame): dataset.selection['cta_expression_admission'] = to_native_json(admission) if getattr(admission, 'target_reference', None) is not None: reference = admission.target_reference - dataset.selection.setdefault('source_evidence', {})[reference['bundle_id']] = dict( + ref_record = dict( schema='vaxrank.oncoref_target_reference.v1', manifest=reference['manifest'], coverage=reference['coverage']) + if reference.get('target_policy') is not None: + ref_record['target_policy'] = reference['target_policy'] + if reference.get('target_selection') is not None: + ref_record['target_selection'] = reference['target_selection'] + dataset.selection.setdefault('source_evidence', {})[reference['bundle_id']] = ref_record if bundle is not None: dataset.selection['hitlist_evidence_bundle'] = bundle if local_evidence is not None: diff --git a/vaxrank/cta_targeting.py b/vaxrank/cta_targeting.py index 951fd836..8895f227 100644 --- a/vaxrank/cta_targeting.py +++ b/vaxrank/cta_targeting.py @@ -2,7 +2,9 @@ from dataclasses import replace from collections import defaultdict +from functools import lru_cache import hashlib +import json import math from .file_digest import file_sha256 @@ -10,6 +12,143 @@ SCHEMA = 'vaxrank.cta_peptide_targeting.v1' +CTA_TARGET_POLICIES = ('sequence_bundle', 'target_selection', 'target_selection_cancer_antigens') +TARGET_SELECTION_POLICIES = ('target_selection', 'target_selection_cancer_antigens') +_ROLE_ORDER = {'allow': 0, 'review': 1, 'exclude': 2} +_CATEGORY_PRIORITY = { + 'Unsafe': 5, + 'Other': 4, + 'Unassessed': 3, + 'Reproductive Antigen only': 2, + 'Cancer Antigen only': 1, + 'CTA': 0, +} + + +def validate_target_policy(policy): + """Validate an optional CTA target policy selector.""" + if policy is None: + return None + if policy not in CTA_TARGET_POLICIES: + raise ValueError( + f'Unknown cta_target_policy {policy!r}; expected one of {", ".join(CTA_TARGET_POLICIES)}' + ) + return policy + + +def _allowed_target_selection_categories(policy): + if policy == 'target_selection': + return frozenset({'CTA'}) + if policy == 'target_selection_cancer_antigens': + return frozenset({'CTA', 'Cancer Antigen only'}) + return None + + +def _parse_str_list(raw): + if raw is None or (isinstance(raw, float) and math.isnan(raw)): + return () + if isinstance(raw, (list, tuple, set, frozenset)): + return tuple(str(v).strip() for v in raw if str(v).strip()) + text = str(raw).strip() + if not text: + return () + if text.startswith('['): + parsed = json.loads(text) + return tuple(str(v).strip() for v in parsed if str(v).strip()) + return tuple(part.strip() for part in text.split(';') if part.strip()) + + +def _clean_text(raw): + if raw is None or (isinstance(raw, float) and math.isnan(raw)): + return '' + text = str(raw).strip() + return '' if text.lower() == 'nan' else text + + +@lru_cache(maxsize=1) +def _cached_target_selection(): + from importlib.metadata import version + try: + from oncoref import target_selection + except ImportError as error: + raise ImportError( + 'cta_target_policy targeting oncoref.target_selection requires oncoref>=1.37.0' + ) from error + + frame = target_selection.results() + defn = target_selection.definition() if hasattr(target_selection, 'definition') else {} + meta = target_selection.metadata() if hasattr(target_selection, 'metadata') else {} + policy_id = _clean_text( + defn.get('policy_id') + or meta.get('policy_id') + or getattr(target_selection, 'POLICY_ID', 'oncoref.target-selection') + ) + reference_id = _clean_text(meta.get('reference_id') or meta.get('reference')) + by_gene = {} + for row in frame.to_dict(orient='records'): + category = _clean_text(row.get('category')) or 'Unassessed' + subtype = _clean_text(row.get('subtype')) + classification = _clean_text(row.get('classification')) or ( + f'{category}:{subtype}' if category == 'Other' and subtype else category + ) + entry = dict( + entity_id=_clean_text(row.get('entity_id')), + protein_group_label=_clean_text(row.get('protein_group_label') or row.get('label')), + category=category, + subtype=subtype, + classification=classification, + decision_reason=_clean_text(row.get('decision_reason')), + cta_tier=_clean_text(row.get('cta_tier')), + representative_sequence_sha256s=frozenset(_parse_str_list(row.get('representative_sequence_sha256s'))), + representative_transcripts=frozenset(_parse_str_list(row.get('representative_transcripts'))), + ) + for gene_id in _parse_str_list(row.get('member_gene_ids') or row.get('gene_ids')): + canonical = gene_id.split('.')[0] + prior = by_gene.get(canonical) + if prior is None or _CATEGORY_PRIORITY.get(category, 3) > _CATEGORY_PRIORITY.get(prior['category'], 3): + by_gene[canonical] = entry + return dict( + policy_id=policy_id, + reference_id=reference_id, + oncoref_version=version('oncoref'), + by_gene=by_gene, + ) + + +def load_target_selection(): + """Load OncoRef's versioned target_selection catalog (cached per process).""" + return _cached_target_selection() + + +def _effective_occurrence_role(occurrence, fallback_role, target_selection_index, allowed_categories): + if target_selection_index is None: + return occurrence.get('shared_sequence', fallback_role) + gene_id = (occurrence.get('gene_id') or '').split('.')[0] + entry = target_selection_index['by_gene'].get(gene_id) if gene_id else None + if entry is None: + return occurrence.get('shared_sequence', fallback_role) + if entry['category'] == 'Unsafe': + return 'exclude' + if entry['category'] in allowed_categories: + return 'allow' + return 'review' + + +def _effective_record_role(record, target_selection_index, allowed_categories): + if target_selection_index is None: + return record['shared_sequence'] + occurrences = record.get('occurrences') or () + if not occurrences: + return record['shared_sequence'] + return max( + (_effective_occurrence_role(o, record['shared_sequence'], target_selection_index, allowed_categories) + for o in occurrences), + key=_ROLE_ORDER.get, + ) + + +def _record_sequence_sha256(record): + return record.get('sequence_sha256') or hashlib.sha256(record['sequence'].encode()).hexdigest() def load_bundle(path): @@ -27,7 +166,8 @@ def bundle_scope(bundle): annotation='%s:%s' % (context.annotation_name, context.annotation_version)) -def admit_expression(path, contract, policy, bundle, scope): +def admit_expression(path, contract, policy, bundle, scope, *, target_policy=None, + target_selection_index=None): """Resolve current qualified representatives directly from the owner bundle.""" from orfdata.reference import species_name_for_taxon from .cta_expression import (CTAExpressionDecision, CTAExpressionResult, CTASequenceAssessment, @@ -35,6 +175,9 @@ def admit_expression(path, contract, policy, bundle, scope): from .input_scope import combine_scopes from .vaccine_antigen import (AminoAcidInterval, TargetableMask, TumorSpecificityAttestation, TumorSpecificityEvidence, VaccineAntigen) + target_policy = validate_target_policy(target_policy) + allowed_categories = _allowed_target_selection_categories(target_policy) + ts = (target_selection_index if target_selection_index is not None else load_target_selection()) if allowed_categories else None reference = bundle_scope(bundle) combine_scopes(scope, reference, 'CTA sequence bundle') if contract.expression_unit != policy.expression_unit: @@ -54,13 +197,62 @@ def admit_expression(path, contract, policy, bundle, scope): candidates = by_feature.get(feature, []) if contract.measurement_level == 'transcript' and '.' in identifier: candidates = [(r, o) for r, o in candidates if o['transcript_id'] == identifier] - allowed = [(r, o) for r, o in candidates if r['direct_target_candidate'] - and o['direct_target_candidate'] and r['shared_sequence'] == 'allow'] - if not allowed: - decisions.append(CTAExpressionDecision(identifier, float(value) if measured else None, - status='unsafe_reference' if any(r['shared_sequence'] == 'exclude' for r, _ in candidates) - else 'not_current_cta' if candidates else 'unresolved_reference')) - continue + if ts is None: + allowed = [(r, o) for r, o in candidates if r['direct_target_candidate'] + and o['direct_target_candidate'] and r['shared_sequence'] == 'allow'] + if not allowed: + decisions.append(CTAExpressionDecision(identifier, float(value) if measured else None, + status='unsafe_reference' if any(r['shared_sequence'] == 'exclude' for r, _ in candidates) + else 'not_current_cta' if candidates else 'unresolved_reference')) + continue + else: + allowed = [] + for r, o in candidates: + gene_key = (o.get('gene_id') or '').split('.')[0] + entry = ts['by_gene'].get(gene_key) if gene_key else None + if entry is None or entry['category'] not in allowed_categories: + continue + if _effective_record_role(r, ts, allowed_categories) != 'allow': + continue + rep_shas = entry['representative_sequence_sha256s'] + is_rep = ( + (_record_sequence_sha256(r) in rep_shas) + if rep_shas else (r['direct_target_candidate'] and o['direct_target_candidate']) + ) + if is_rep or (r['direct_target_candidate'] and o['direct_target_candidate']): + allowed.append((r, o)) + if not allowed: + first_occ = candidates[0][1] if candidates else {} + gene_id = first_occ.get('gene_id') or (feature if contract.measurement_level == 'gene' else '') + gene_name = first_occ.get('gene_name') or '' + entry = ts['by_gene'].get(gene_id.split('.')[0]) if gene_id else None + if not gene_name and entry is not None: + gene_name = entry.get('protein_group_label') or '' + if ((entry is not None and entry['category'] == 'Unsafe') + or any(_effective_record_role(r, ts, allowed_categories) == 'exclude' for r, _ in candidates)): + status = 'unsafe_reference' + elif entry is not None and entry['category'] == 'Other': + status = 'blocked_target_selection' + elif candidates or entry is not None: + status = 'not_current_cta' + else: + status = 'unresolved_reference' + gene_identity = None + if entry is not None: + gene_identity = dict( + canonical_gene_id=gene_id, + source_gene_id=gene_id, + status='target_selection', + target_selection_policy_id=ts['policy_id'], + target_selection_category=entry['category'], + target_selection_classification=entry['classification'], + target_selection_reason=entry['decision_reason'], + ) + decisions.append(CTAExpressionDecision( + identifier, float(value) if measured else None, + gene_id=gene_id, gene_name=gene_name, + status=status, gene_identity=gene_identity)) + continue groups = defaultdict(list) for record, occurrence in allowed: groups[(occurrence['gene_id'], record['sequence'])].append((record, occurrence)) @@ -75,6 +267,17 @@ def admit_expression(path, contract, policy, bundle, scope): if not complete: raise ValueError('OncoRef allowed a representative with interrupted sequence') admitted = measured and value >= policy.min_tumor_expression + ts_entry = ts['by_gene'].get(gene_id.split('.')[0]) if ts is not None else None + source_metadata = (('oncoref_sequence_bundle', bundle.identity),) + if ts is not None and ts_entry is not None: + source_metadata += ( + ('oncoref_target_policy', target_policy), + ('oncoref_target_selection_policy_id', ts['policy_id']), + ('oncoref_target_selection_category', ts_entry['category']), + ('oncoref_target_selection_classification', ts_entry['classification']), + ) + if ts_entry.get('decision_reason'): + source_metadata += (('oncoref_target_selection_reason', ts_entry['decision_reason']),) antigen = VaccineAntigen(kind='CTA', amino_acids=sequence, targetable_mask=TargetableMask((AminoAcidInterval(0, len(sequence)),)), gene_id=gene_id, gene_name=occurrence.get('gene_name') or '', @@ -83,11 +286,12 @@ def admit_expression(path, contract, policy, bundle, scope): source_identifier=gene_id + ':' + ( identifier + ':' if contract.measurement_level == 'transcript' else '' ) + hashlib.sha256(sequence.encode()).hexdigest(), - source_metadata=(('oncoref_sequence_bundle', bundle.identity),), + source_metadata=source_metadata, source_protein_completeness='complete', tumor_specificity=TumorSpecificityAttestation( status='admitted' if admitted else 'held_out', evidence_kind='cta_expression', - evidence_source='OncoRef current representative and patient expression', + evidence_source=('OncoRef target_selection representative and patient expression' + if ts is not None else 'OncoRef current representative and patient expression'), patient_specific=True, rationale_code='expressed_current_cta' if admitted else 'insufficient_tumor_expression', evidence_records=(TumorSpecificityEvidence(evidence_kind='patient_expression', evidence_source=contract.evidence_source, evidence_version=contract.evidence_version, @@ -96,21 +300,43 @@ def admit_expression(path, contract, policy, bundle, scope): threshold=policy.min_tumor_expression, passed=admitted),))) assessment = CTASequenceAssessment(antigen, bundle.identity, record['record_id'], occurrence, equivalent_occurrences=tuple(dict(record_id=r['record_id'], **o) for r, o in origins)) + gene_identity = dict(canonical_gene_id=occurrence['gene_id'], + source_gene_id=occurrence['gene_id'], + status='verified_sequence_bundle') + if ts is not None and ts_entry is not None: + gene_identity.update( + target_selection_policy_id=ts['policy_id'], + target_selection_category=ts_entry['category'], + target_selection_classification=ts_entry['classification'], + target_selection_reason=ts_entry['decision_reason'], + ) decisions.append(CTAExpressionDecision(identifier, float(value) if measured else None, gene_id=occurrence['gene_id'], gene_name=antigen.gene_name, transcript_id=';'.join(transcripts), status='admitted' if admitted else 'held_out', - assessment=assessment, gene_identity=dict(canonical_gene_id=occurrence['gene_id'], - source_gene_id=occurrence['gene_id'], status='verified_sequence_bundle'))) + assessment=assessment, gene_identity=gene_identity)) + target_reference = dict(bundle_id=bundle.identity, manifest=bundle.manifest, coverage=bundle.coverage) + if target_policy is not None: + target_reference['target_policy'] = target_policy + if ts is not None: + target_reference['target_selection'] = dict( + policy_id=ts['policy_id'], + reference_id=ts.get('reference_id', ''), + oncoref_version=ts.get('oncoref_version', ''), + allowed_categories=sorted(allowed_categories), + ) return CTAExpressionResult(contract, policy, CTATargetExclusionPolicy((), ()), file_sha256(path), reference.reference_assembly, - annotation_name, annotation_version, tuple(decisions), target_reference=dict( - bundle_id=bundle.identity, manifest=bundle.manifest, coverage=bundle.coverage)) + annotation_name, annotation_version, tuple(decisions), target_reference=target_reference) -def peptide_containment(peptides, bundle): +def peptide_containment(peptides, bundle, *, target_policy=None, target_selection_index=None): """Match all contiguous occurrences, preserving exclusion/review precedence.""" import ahocorasick + target_policy = validate_target_policy(target_policy) + allowed_categories = _allowed_target_selection_categories(target_policy) + ts = (target_selection_index if target_selection_index is not None else load_target_selection()) if allowed_categories else None + peptides = sorted(set(peptides)) matches = {peptide: [] for peptide in peptides} if not peptides: @@ -120,11 +346,19 @@ def peptide_containment(peptides, bundle): query.add_word(peptide, peptide) query.make_automaton() for segment in bundle.segments(min_length=min(map(len, peptides))): + role = segment['shared_sequence'] + occurrences = segment['occurrences'] + if ts is not None: + occurrences = [ + {**occ, 'shared_sequence': _effective_occurrence_role(occ, role, ts, allowed_categories)} + for occ in occurrences + ] + role = max((occ['shared_sequence'] for occ in occurrences), key=_ROLE_ORDER.get) if occurrences else role for end, peptide in query.iter(segment['sequence']): matches[peptide].append(dict( - record_id=segment['record_id'], role=segment['shared_sequence'], + record_id=segment['record_id'], role=role, start=segment['start'] + end + 1 - len(peptide), end=segment['start'] + end + 1, - occurrences=segment['occurrences'])) + occurrences=occurrences)) return matches @@ -151,6 +385,25 @@ def recorded_bundle_ids(dataset): return identities +def recorded_target_policies(dataset): + """Identify frozen CTA target policies from saved evidence.""" + policies = set() + for epitope in dataset.epitopes: + antigen = dataset.antigens.get(epitope.prediction_group_source) + if antigen is not None and antigen.kind == 'CTA': + evidence = targeting_evidence(epitope) + if evidence and evidence.get('target_policy'): + policies.add(evidence['target_policy']) + for antigen in dataset.antigens.values(): + if antigen.kind == 'CTA': + policies.update(value for key, value in antigen.source_metadata + if key == 'oncoref_target_policy') + for evidence in dataset.selection.get('source_evidence', {}).values(): + if evidence.get('schema') == 'vaxrank.oncoref_target_reference.v1' and evidence.get('target_policy'): + policies.add(evidence['target_policy']) + return policies + + def matching_gene_summary(matches, roles=('exclude', 'review')): """Compact display only; exact protein occurrences stay in native evidence.""" genes = defaultdict(set) @@ -199,13 +452,17 @@ def _targeting_summary(epitopes, antigens, bundle_id): yield identity, summary -def apply_cta_targeting(dataset, bundle): +def apply_cta_targeting(dataset, bundle, *, target_policy=None, target_selection_index=None): """Attach shared targeting decisions before ranking; native replay is offline. Source admission remains separate. A peptide can be targeted only if it has a qualified allowed occurrence and no exclusion or unresolved occurrence. This is exact containment, not a near-self or clinical safety model. """ + target_policy = validate_target_policy(target_policy) + allowed_categories = _allowed_target_selection_categories(target_policy) + ts = (target_selection_index if target_selection_index is not None else load_target_selection()) if allowed_categories else None + cta = [epitope for epitope in dataset.epitopes if dataset.antigens[epitope.prediction_id].kind == 'CTA'] if not cta: @@ -216,7 +473,10 @@ def apply_cta_targeting(dataset, bundle): reference_scope = bundle_scope(bundle) for provenance in dataset.provenance: combine_scopes(provenance.scope, reference_scope, 'OncoRef sequence bundle') - matches = peptide_containment((e.sequence for e in cta), bundle) + matches = peptide_containment( + (e.sequence for e in cta), bundle, + target_policy=target_policy, target_selection_index=ts, + ) updated = {} for epitope in cta: occurrences = matches[epitope.sequence] @@ -225,6 +485,10 @@ def apply_cta_targeting(dataset, bundle): else 'eligible' if 'allow' in roles else 'unassessed') evidence = dict(schema=SCHEMA, peptide=epitope.sequence, status=status, bundle_id=bundle.identity, matches=occurrences) + if target_policy is not None: + evidence['target_policy'] = target_policy + if ts is not None: + evidence['target_selection_policy_id'] = ts['policy_id'] antigen = dataset.antigens[epitope.prediction_id] sources = [] for match in occurrences: @@ -246,8 +510,18 @@ def apply_cta_targeting(dataset, bundle): reference_sha256=bundle.identity, genome_release=reference.get('reference_id', '')), input_evidence=tuple(r for r in epitope.input_evidence if r.get('schema') != SCHEMA) + (evidence,)) dataset.epitopes = tuple(updated.get(e.prediction_id, e) for e in dataset.epitopes) - dataset.selection.setdefault('source_evidence', {})[bundle.identity] = dict( + reference_record = dict( schema='vaxrank.oncoref_target_reference.v1', manifest=manifest, coverage=bundle.coverage) + if target_policy is not None: + reference_record['target_policy'] = target_policy + if ts is not None: + reference_record['target_selection'] = dict( + policy_id=ts['policy_id'], + reference_id=ts.get('reference_id', ''), + oncoref_version=ts.get('oncoref_version', ''), + allowed_categories=sorted(allowed_categories), + ) + dataset.selection.setdefault('source_evidence', {})[bundle.identity] = reference_record dataset.selection['source_evidence'].update(_targeting_summary(updated.values(), dataset.antigens, bundle.identity)) dataset.result.df['cta_target_status'] = dataset.result.df.prediction_id.map( {key: targeting_evidence(e)['status'] for key, e in updated.items()}) diff --git a/vaxrank/epitope_config.py b/vaxrank/epitope_config.py index 2e07bbaf..a92b09fa 100644 --- a/vaxrank/epitope_config.py +++ b/vaxrank/epitope_config.py @@ -168,6 +168,7 @@ class EpitopeConfig(msgspec.Struct, frozen=True, forbid_unknown_fields=True): comparison_reference: str = 'annotation_reference' patient_background_baseline: str = 'focal' cta_sequence_bundle: Optional[str] = None + cta_target_policy: Optional[str] = None @property def allele_policy(self): @@ -190,6 +191,11 @@ def __post_init__(self): raise ValueError('patient_background_baseline must be focal or supplied_somatic_haplotype') if self.comparison_reference == 'annotation_reference' and self.patient_background_baseline != 'focal': raise ValueError('A patient-background reversion policy requires comparison_reference=patient_background') + if self.cta_target_policy is not None: + from .cta_targeting import validate_target_policy + validate_target_policy(self.cta_target_policy) + if self.cta_sequence_bundle is None: + raise ValueError('cta_target_policy requires cta_sequence_bundle') if self.selection_policy is not None: from topiary import resolve_selection_policy policy = resolve_selection_policy(self.selection_policy) diff --git a/vaxrank/external_rescoring.py b/vaxrank/external_rescoring.py index ffea3568..ff0d77fe 100644 --- a/vaxrank/external_rescoring.py +++ b/vaxrank/external_rescoring.py @@ -555,7 +555,8 @@ def resolve_cta_bundle(): scope=declared, genome=genome, manifest_path=manifest_path, declarations=declarations, host_reference=host_reference, sequence_bundle=epitope_config.cta_sequence_bundle, - target_reference=resolve_cta_bundle()) + target_reference=resolve_cta_bundle(), + target_policy=epitope_config.cta_target_policy) provenance = source.provenance else: source = sequences[input_index] @@ -654,19 +655,24 @@ def resolve_cta_bundle(): def report_config(reports, epitope_config=None): """Resolve an explicit policy or require agreement between saved policies.""" from msgspec.structs import replace as replace_config - from .cta_targeting import recorded_bundle_ids + from .cta_targeting import recorded_bundle_ids, recorded_target_policies identities = set().union(*(recorded_bundle_ids(r.dataset) for r in reports if r.dataset is not None)) if len(identities) > 1: raise ValueError('Saved CTA targeting uses different sequence bundle identities; ' 'predict the CTA inputs with one reference before combining them.') + recorded_policies = set().union(*(recorded_target_policies(r.dataset) + for r in reports if r.dataset is not None)) + if len(recorded_policies) > 1: + raise ValueError('Saved CTA targeting uses different target policies; ' + 'predict the CTA inputs with one target policy before combining them.') if epitope_config is None: from .epitope_config import EpitopeConfig configs = [r.dataset.config for r in reports if r.dataset is not None and r.dataset.config is not None] # A path/current alias locates a bundle; frozen evidence above defines # its identity. Equivalent copies must not become different policies. - comparable = [replace_config(cfg, cta_sequence_bundle=None) for cfg in configs] + comparable = [replace_config(cfg, cta_sequence_bundle=None, cta_target_policy=None) for cfg in configs] if comparable and any(cfg != comparable[0] for cfg in comparable): raise ValueError("Saved inputs use different scoring policies; supply an explicit epitope config") epitope_config = configs[0] if configs else EpitopeConfig() @@ -692,7 +698,18 @@ def report_config(reports, epitope_config=None): if len(saved_cta_bundles) > 1 and (not identities or None in identities): raise ValueError('Saved CTA targeting lacks a common frozen sequence reference identity') requested = next((r.dataset.config.cta_sequence_bundle for r in saved_cta_reports), None) - epitope_config = replace_config(epitope_config, cta_sequence_bundle=requested) + saved_cta_policies = {r.dataset.config.cta_target_policy for r in saved_cta_reports} + requested_policy = epitope_config.cta_target_policy + if requested_policy is not None and requested_policy not in saved_cta_policies: + if not recorded_policies or {requested_policy} != recorded_policies: + raise ValueError('Saved CTA targeting retains its target policy. ' + 'Create new CTA inputs to change the OncoRef target policy.') + elif requested_policy is None: + if len(saved_cta_policies) > 1: + raise ValueError('Saved CTA targeting uses different target policies') + requested_policy = next((r.dataset.config.cta_target_policy for r in saved_cta_reports), None) + epitope_config = replace_config( + epitope_config, cta_sequence_bundle=requested, cta_target_policy=requested_policy) return epitope_config diff --git a/vaxrank/hitlist_evidence.py b/vaxrank/hitlist_evidence.py index 95635729..5dca101b 100644 --- a/vaxrank/hitlist_evidence.py +++ b/vaxrank/hitlist_evidence.py @@ -62,10 +62,21 @@ def hitlist_annotations(sequences, bundle, alleles=None, *, local_evidence=None) """Exact public observations; an unqueried sequence has unknown support.""" columns = ('hitlist_ms_observations', 'hitlist_cta_specific', 'hitlist_avoid_sequence', 'hitlist_tissue_review_required', 'hitlist_essential_tissue_donors') - summaries = ({row['peptide']: row for row in bundle['artifacts']['peptides.parquet']['rows']} + peptides_artifact = bundle['artifacts'].get('peptides.parquet', {}) if bundle else {} + peptides_cols = set(peptides_artifact.get('columns', ())) + summaries = ({row['peptide']: row for row in peptides_artifact.get('rows', ())} if bundle else {}) source_fields = ('n_ms_observations', 'cta_specific', 'avoid_sequence', 'tissue_review_required', 'n_essential_tissue_donors') + optional_policy_fields = tuple( + (dest, src) + for dest, src in ( + ('hitlist_policy_unsafe_match', 'has_policy_unsafe_match'), + ('hitlist_policy_categories', 'policy_categories'), + ('hitlist_avoid_reasons', 'avoid_reasons'), + ) + if src in peptides_cols + ) from mhcgnomes import ParseError, parse from .allele_validation import parse_prediction_allele observations = {} @@ -94,6 +105,8 @@ def hitlist_annotations(sequences, bundle, alleles=None, *, local_evidence=None) summary = dict(n_ms_observations=len(measured)) row = dict(zip(columns, (summary.get(k) if summary is not None else None for k in source_fields))) + for dest, src in optional_policy_fields: + row[dest] = summary.get(src) if summary is not None else None row['hitlist_query_status'] = 'captured' if summary is not None else 'unqueried' counts = dict(hitlist_ms_monoallelic=0, hitlist_ms_experimental_restriction=0, hitlist_ms_predicted_restriction=0, hitlist_ms_donor_hla_candidate=0, diff --git a/vaxrank/input_coverage.py b/vaxrank/input_coverage.py index 0e5f04dc..7d4c0e48 100644 --- a/vaxrank/input_coverage.py +++ b/vaxrank/input_coverage.py @@ -276,7 +276,10 @@ def coverage_view(coverage, source_evidence, ranked_candidates, products): supplied.add('cta') decisions = [] omitted_not_cta_count = 0 - background_statuses = {'not_cta', 'unresolved_reference', 'unsafe_reference', 'not_current_cta'} + background_statuses = { + 'not_cta', 'unresolved_reference', 'unsafe_reference', + 'not_current_cta', 'blocked_target_selection', + } for decision in admission.decisions: if decision.status in background_statuses: omitted_not_cta_count += 1 diff --git a/vaxrank/version.py b/vaxrank/version.py index 857d7d4d..ac20eb3b 100644 --- a/vaxrank/version.py +++ b/vaxrank/version.py @@ -1,4 +1,4 @@ -__version__ = "3.61.0" +__version__ = "3.62.0" def print_version():