Coverage for src/python/ensembl/vep/corpus/golden/resolve.py: 81%
76 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Resolve a loaded golden corpus or explicitly generate its fallback."""
16from __future__ import annotations
18from contextlib import AbstractContextManager
19from importlib.resources import as_file, files
20from pathlib import Path
22from ensembl.vep.corpus.base import Corpus
23from ensembl.vep.corpus.golden.base import GoldenCorpus
24from ensembl.vep.corpus.golden.terms import GoldenTerms, record_golden
25from ensembl.vep.corpus.registry import build_corpus, register_corpus
26from ensembl.vep.corpus.spec import CorpusSpec
28__all__ = ["load_golden_corpus"]
30_PACKAGE = "ensembl.vep.corpus.golden"
31_DEFAULT_DATASET = "default"
34def _loaded_spec(directory: Path) -> CorpusSpec:
35 """Return the file-loader specification for a golden directory."""
36 return CorpusSpec(
37 kind="loaded.files",
38 parameters={
39 "fasta": str(directory / "corpus.fa"),
40 "gff3": str(directory / "corpus.gff3"),
41 "vcf": str(directory / "corpus.vcf"),
42 },
43 )
46def _identity_spec(specification: CorpusSpec) -> CorpusSpec:
47 """Return dataset identity without directory or generation policy parameters."""
48 return CorpusSpec(
49 kind="golden.file",
50 parameters={"dataset": specification.parameter("dataset", _DEFAULT_DATASET)},
51 )
54def _build_golden_from_synthetic(
55 specification: CorpusSpec, synthetic_specification: CorpusSpec
56) -> GoldenCorpus:
57 """Build an in-memory golden corpus from a synthetic corpus specification."""
58 # Import lazily so registering the golden corpus does not couple the corpus package import to
59 # annotator discovery. Generation is an explicit fallback, not part of ordinary loading.
60 from ensembl.vep.annotators.factory import build_annotator # pylint: disable=import-outside-toplevel
62 corpus = build_corpus(synthetic_specification)
63 try:
64 annotator = build_annotator(annotator="consequence.linear")
65 recorded = record_golden(corpus, annotator, "consequence.linear")
66 except Exception:
67 corpus.close()
68 raise
69 expected = GoldenTerms(
70 spec=specification,
71 annotator=recorded.annotator,
72 catalogue=recorded.catalogue,
73 terms=recorded.terms,
74 )
75 return GoldenCorpus(spec=specification, corpus=corpus, expected_terms=expected)
78def load_golden_corpus(
79 specification: CorpusSpec,
80 *,
81 directory: Path | None = None,
82 fallback: CorpusSpec | None = None,
83 allow_generate: bool = False,
84) -> GoldenCorpus:
85 """Load pinned corpus files and terms, or explicitly generate a missing fallback.
87 Existing but malformed data always raises. Generation is limited to absent data so a corrupt
88 golden reference cannot silently validate against newly generated expectations.
90 Args:
91 specification (CorpusSpec): Identity of the requested golden dataset.
92 directory (Path | None): Explicit bundle directory, or ``None`` for packaged data.
93 fallback (CorpusSpec | None): Corpus to annotate when missing data may be generated.
94 allow_generate (bool): Whether an absent dataset may use ``fallback``.
96 Returns:
97 GoldenCorpus: Loaded or generated corpus with pinned expected terms.
99 Raises:
100 FileNotFoundError: If required corpus or term files are absent without an allowed fallback.
101 TypeError: If the dataset parameter has an invalid type.
102 ValueError: If loaded terms identify a different corpus specification.
103 """
104 resource_context: AbstractContextManager[object] | None = None
105 if directory is None:
106 dataset = specification.parameter("dataset", _DEFAULT_DATASET)
107 if not isinstance(dataset, str): 107 ↛ 108line 107 didn't jump to line 108 because the condition on line 107 was never true
108 raise TypeError("golden corpus dataset must be a string")
109 resource_context = as_file(files(_PACKAGE).joinpath("data", dataset))
110 try:
111 # The context has to remain open for the lifetime of the returned GoldenCorpus.
112 directory = Path(resource_context.__enter__()) # pylint: disable=unnecessary-dunder-call
113 except FileNotFoundError:
114 if not allow_generate or fallback is None:
115 raise
116 return _build_golden_from_synthetic(specification, fallback)
118 if not directory.is_dir():
119 if resource_context is not None: 119 ↛ 120line 119 didn't jump to line 120 because the condition on line 119 was never true
120 resource_context.__exit__(None, None, None)
121 if allow_generate and fallback is not None:
122 return _build_golden_from_synthetic(specification, fallback)
123 raise FileNotFoundError(directory)
125 terms_path = directory / "terms.json"
126 required = (directory / "corpus.fa", directory / "corpus.gff3", directory / "corpus.vcf", terms_path)
127 missing = [path for path in required if not path.is_file()]
128 if missing:
129 if resource_context is not None: 129 ↛ 130line 129 didn't jump to line 130 because the condition on line 129 was never true
130 resource_context.__exit__(None, None, None)
131 raise FileNotFoundError(missing[0])
133 corpus: Corpus | None = None
134 try:
135 # Load the corpus files through the regular file-backed factory
136 corpus = build_corpus(_loaded_spec(directory))
137 expected = GoldenTerms.load(terms_path)
138 if expected.spec != specification:
139 raise ValueError(
140 f"golden bundle identifies {expected.spec.as_dict()!r}, "
141 f"not requested {specification.as_dict()!r}"
142 )
143 except Exception:
144 if corpus is not None: 144 ↛ 146line 144 didn't jump to line 146 because the condition on line 144 was always true
145 corpus.close()
146 if resource_context is not None: 146 ↛ 147line 146 didn't jump to line 147 because the condition on line 146 was never true
147 resource_context.__exit__(None, None, None)
148 raise
149 return GoldenCorpus(
150 spec=expected.spec,
151 corpus=corpus,
152 expected_terms=expected,
153 resource_context=resource_context,
154 )
157@register_corpus("golden.file")
158def _registered_golden_corpus(specification: CorpusSpec) -> Corpus:
159 """Build the registered packaged golden corpus."""
160 directory_value = specification.parameter("directory")
161 directory = Path(directory_value) if isinstance(directory_value, str) else None
162 allow_generate = specification.parameter("allow_generate", False) is True
163 fallback_kind = specification.parameter("fallback", "synthetic.default")
164 fallback = None
165 if isinstance(fallback_kind, str): 165 ↛ 167line 165 didn't jump to line 167 because the condition on line 165 was always true
166 fallback = CorpusSpec(kind=fallback_kind, parameters=specification.parameters)
167 return load_golden_corpus(
168 _identity_spec(specification),
169 directory=directory,
170 fallback=fallback,
171 allow_generate=allow_generate,
172 )