gain-vep-annotator 2026.11.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.
@@ -0,0 +1,113 @@
1
+ # A .claude directory at any depth is ignored (Claude Code started from a
2
+ # member project writes <member>/.claude/settings.local.json). The root one is
3
+ # un-ignored only so that its committed skills/ can be re-included;
4
+ # .claude/worktrees/ and the rest of the root .claude stay ignored.
5
+ **/.claude/
6
+ !/.claude/
7
+ /.claude/*
8
+ !/.claude/skills/
9
+ # verify-gain run output (.claude/skills/verify-gain)
10
+ .verify/
11
+ .specify
12
+ *.pyc
13
+ __pycache__
14
+ .cache
15
+ .DS_Store
16
+ ._.DS_Store
17
+ *.log
18
+ *.cache
19
+ *.db
20
+ *.tmp
21
+ *.temp
22
+ *.swp
23
+ *.retry
24
+ *.egg-info
25
+
26
+ .project
27
+ .pydevproject
28
+ .settings
29
+ .ipynb_checkpoints
30
+ .vagrant
31
+ .vscode/
32
+ .idea/
33
+
34
+ .coverage
35
+ .coverage*
36
+ coverage/
37
+ coverage.xml
38
+ htmlcov
39
+ junit.xml
40
+ .pytest_cache
41
+ .mypy_cache
42
+
43
+ logs
44
+ output
45
+ tmp/
46
+ builds
47
+ downloads
48
+ results
49
+ test_data/
50
+ /test_data/
51
+ test-results/
52
+ /test-results
53
+ test_results
54
+ comp-data/
55
+ comp
56
+ cache
57
+ import
58
+ /import
59
+ _build/
60
+ _html
61
+ denovo-cache
62
+ dask-worker-space/
63
+ .grr
64
+ /data/
65
+ /build-env/
66
+ build-env/*
67
+ projects
68
+ /work
69
+
70
+ Jenkinsfile.generated-stages
71
+ Jenkinsfile.generated-stages.all
72
+ /.build-scripts-tmp-sessions
73
+
74
+ monkeytype.sqlite3
75
+ monkeytype_config.py
76
+
77
+ VERSION
78
+ BUILD
79
+
80
+ CLAUDE*.md
81
+
82
+ .task-progress
83
+
84
+ # uv-managed virtual environment
85
+ .venv/
86
+
87
+ # Generated by hatch-vcs at build/install time
88
+ core/gain/_version.py
89
+
90
+ # Root-level build artefact dirs created by the root Jenkinsfile
91
+ # (uv build wheels, rattler-build conda packages). Cleaned and
92
+ # re-created in CI's `Prepare workspace` stage; never checked in.
93
+ /dist/
94
+ /conda/
95
+ /reports/
96
+ web_api/data/db.sqlite3
97
+
98
+ # Linked git worktrees used by Claude Code for isolated
99
+ # feature development (see superpowers `using-git-worktrees`).
100
+ /.worktrees/
101
+
102
+ # Sphinx docs build artefacts. The tarball is consumed by
103
+ # docs/deploy/docs_deploy.yaml; both are produced by
104
+ # docs/build_docs.sh.
105
+ /docs/build/
106
+ /docs/gaindocs-html.tar.gz
107
+ /docs/.tmp/
108
+
109
+ # Running the spliceai tests opens this fixture directory as a GRR, which
110
+ # writes a compressed contents index beside the authored `.CONTENTS.json`.
111
+ # Only this one path: `web_api`'s fixture GRR tracks its `.CONTENTS.*.gz`
112
+ # on purpose, so this must not be a repo-wide pattern.
113
+ /spliceai_annotator/tests/fixtures/.CONTENTS.json.gz
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Cold Spring Harbor Laboratory
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.5
2
+ Name: gain-vep-annotator
3
+ Version: 2026.11.0
4
+ Summary: GAIn VEP Annotator
5
+ Project-URL: Homepage, https://github.com/IossifovLab/gain
6
+ Author-email: Lubomir Chorbadjiev <lubomir.chorbadjiev@gmail.com>
7
+ License: MIT
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Requires-Python: <3.15,>=3.12
13
+ Requires-Dist: gain-core
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "gain-vep-annotator"
7
+ description = "GAIn VEP Annotator"
8
+ requires-python = "<3.15,>=3.12"
9
+ license = { text = "MIT" }
10
+ authors = [
11
+ { name = "Lubomir Chorbadjiev", email = "lubomir.chorbadjiev@gmail.com" },
12
+ ]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Programming Language :: Python :: 3.12",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ dependencies = [
20
+ "gain-core",
21
+ ]
22
+ dynamic = ["version"]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/IossifovLab/gain"
26
+
27
+ [project.scripts]
28
+ install_vep_cache = "vep_annotator.install_vep_cache:main"
29
+
30
+ [project.entry-points."gain.annotation.annotators"]
31
+ vep_full_annotator = "vep_annotator.vep_annotator:build_vep_cache_annotator"
32
+ vep_effect_annotator = "vep_annotator.vep_annotator:build_vep_effect_annotator"
33
+
34
+ [dependency-groups]
35
+ dev = [
36
+ "mypy==1.15.0",
37
+ "pylint",
38
+ "pylint-junit",
39
+ "pytest",
40
+ "pytest-cov",
41
+ "pytest-mock",
42
+ "pytest-xdist",
43
+ "ruff==0.16.5",
44
+ ]
45
+
46
+ [tool.hatch.version]
47
+ source = "vcs"
48
+ fallback-version = "0.0.0.dev0"
49
+
50
+ [tool.hatch.version.raw-options]
51
+ root = ".."
52
+ version_scheme = "no-guess-dev"
53
+
54
+ [tool.hatch.build.targets.wheel]
55
+ packages = ["vep_annotator"]
56
+ exclude = ["vep_annotator/tests"]
57
+
58
+ [tool.hatch.build.targets.sdist]
59
+ include = ["/vep_annotator"]
60
+ exclude = ["vep_annotator/tests"]
61
+
62
+ # The repository LICENSE sits one level up. The sdist copies it to its
63
+ # top level as a regular file, and the wheel, which uv builds from the
64
+ # unpacked sdist, picks it up there as a PEP 639 license file (#1961).
65
+ [tool.hatch.build.targets.sdist.force-include]
66
+ "../LICENSE" = "LICENSE"
File without changes
@@ -0,0 +1,95 @@
1
+ import argparse
2
+ import logging
3
+ import subprocess
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ def _build_argument_parser() -> argparse.ArgumentParser:
11
+ """Create the command line parser of the tool."""
12
+ parser = argparse.ArgumentParser(
13
+ description="VEP cache installer",
14
+ formatter_class=argparse.RawDescriptionHelpFormatter,
15
+ )
16
+ parser.add_argument(
17
+ "cache_dir",
18
+ help="Destination directory to download and unpack the cache in",
19
+ )
20
+ parser.add_argument(
21
+ "--force", "-f", default=False, action="store_true",
22
+ help="Download and unpack regardless of destination status",
23
+ )
24
+ parser.add_argument(
25
+ "--continue", "-c", dest="cont", default=False, action="store_true",
26
+ help="Continue a previous partial download",
27
+ )
28
+ return parser
29
+
30
+
31
+ def main(argv: list[str] | None = None) -> int:
32
+ """VEP cache installation tool"""
33
+ parser = _build_argument_parser()
34
+ args = parser.parse_args(argv)
35
+
36
+ cache_dir = Path(args.cache_dir).absolute()
37
+
38
+ force = args.force
39
+ cont = args.cont
40
+
41
+ filename = "homo_sapiens_vep_113_GRCh38.tar.gz"
42
+ filepath = cache_dir / filename
43
+
44
+ if cont:
45
+ other_files = list(filter(
46
+ lambda file: file.name != filename, cache_dir.iterdir(),
47
+ ))
48
+ else:
49
+ other_files = list(cache_dir.iterdir())
50
+
51
+ if cache_dir.exists() and len(other_files) > 0 and not force:
52
+ raise ValueError(
53
+ "Destination cache directory is not empty! "
54
+ "Use --force or cleanup the directory.",
55
+ )
56
+
57
+ file_url = (
58
+ "https://ftp.ensembl.org/"
59
+ "pub/release-113/variation/vep/"
60
+ "homo_sapiens_vep_113_GRCh38.tar.gz"
61
+ )
62
+
63
+ wget_command = [
64
+ "wget",
65
+ file_url,
66
+ "-O",
67
+ str(filepath),
68
+ ]
69
+ if cont:
70
+ wget_command.append("-c")
71
+ try:
72
+ subprocess.run(wget_command, check=True)
73
+ except subprocess.CalledProcessError:
74
+ logger.exception("Error downloading cache")
75
+ return 1
76
+
77
+ tar_command = [
78
+ "tar",
79
+ "xzf",
80
+ str(filepath),
81
+ "-C",
82
+ str(cache_dir),
83
+ ]
84
+
85
+ try:
86
+ subprocess.run(tar_command, check=True)
87
+ except subprocess.CalledProcessError:
88
+ logger.exception("Error extracting cache")
89
+ return 2
90
+
91
+ return 0
92
+
93
+
94
+ if __name__ == "__main__":
95
+ main(sys.argv[1:])
@@ -0,0 +1,566 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import logging
5
+ import os
6
+ import subprocess
7
+ import textwrap
8
+ from collections.abc import Sequence
9
+ from pathlib import Path
10
+ from typing import Any, TextIO, cast
11
+
12
+ import pysam
13
+ from gain.annotation.annotatable import Annotatable, VCFAllele
14
+ from gain.annotation.annotation_config import AnnotationConfigurationError
15
+ from gain.annotation.annotation_factory import AnnotationConfigParser
16
+ from gain.annotation.annotation_pipeline import (
17
+ AnnotationPipeline,
18
+ Annotator,
19
+ AnnotatorInfo,
20
+ AttributeSpec,
21
+ )
22
+ from gain.annotation.annotator_base import AnnotatedValues
23
+ from gain.annotation.docker_annotator import DockerAnnotator
24
+ from gain.annotation.utils import (
25
+ find_annotator_gene_models,
26
+ find_annotator_reference_genome,
27
+ )
28
+ from gain.genomic_resources.cached_repository import GenomicResourceCachedRepo
29
+ from gain.genomic_resources.gene_models.gene_models_factory import (
30
+ build_gene_models_from_resource,
31
+ )
32
+ from gain.genomic_resources.gene_models.serialization import (
33
+ gene_models_to_gtf,
34
+ )
35
+ from gain.genomic_resources.reference_genome import reference_genome_files
36
+ from gain.genomic_resources.repository import GenomicResource
37
+
38
+ from vep_annotator.vep_attributes import effect_attributes, full_attributes
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ CONSEQUENCES: dict[str, int] = {t[1]: t[0] for t in enumerate([
43
+ "sequence_variant",
44
+ "intergenic_variant",
45
+ "regulatory_region_variant",
46
+ "regulatory_region_amplification",
47
+ "regulatory_region_ablation",
48
+ "TF_binding_site_variant",
49
+ "TFBS_amplification",
50
+ "TFBS_ablation",
51
+ "downstream_gene_variant",
52
+ "upstream_gene_variant",
53
+ "coding_transcript_variant",
54
+ "non_coding_transcript_variant",
55
+ "NMD_transcript_variant",
56
+ "intron_variant",
57
+ "non_coding_transcript_exon_variant",
58
+ "3_prime_UTR_variant",
59
+ "5_prime_UTR_variant",
60
+ "mature_miRNA_variant",
61
+ "coding_sequence_variant",
62
+ "synonymous_variant",
63
+ "stop_retained_variant",
64
+ "start_retained_variant",
65
+ "incomplete_terminal_codon_variant",
66
+ "splice_polypyrimidine_tract_variant",
67
+ "splice_donor_region_variant",
68
+ "splice_region_variant",
69
+ "splice_donor_5th_base_variant",
70
+ "protein_altering_variant",
71
+ "missense_variant",
72
+ "inframe_deletion",
73
+ "inframe_insertion",
74
+ "feature_truncation",
75
+ "feature_elongation",
76
+ "transcript_amplification",
77
+ "start_lost",
78
+ "stop_lost",
79
+ "frameshift_variant",
80
+ "stop_gained",
81
+ "splice_donor_variant",
82
+ "splice_acceptor_variant",
83
+ "transcript_ablation",
84
+ ])}
85
+
86
+ IMPACTS = {
87
+ "HIGH": 3,
88
+ "MODERATE": 2,
89
+ "LOW": 1,
90
+ "MODIFIER": 0,
91
+ }
92
+
93
+
94
+ def _resolve_vep_image_tag(vep_version: Any) -> str:
95
+ """Turn a `vep_version` parameter into an `ensembl-vep` image tag."""
96
+ if vep_version is None:
97
+ return "release_latest"
98
+
99
+ if isinstance(vep_version, float):
100
+ raise AnnotationConfigurationError(
101
+ f"the `vep_version` parameter must be quoted; YAML read it as "
102
+ f"the number {vep_version}, which can silently drop a trailing "
103
+ f"zero of the minor version. Use "
104
+ f'`vep_version: "<major>.<minor>"` instead',
105
+ )
106
+
107
+ version = str(vep_version)
108
+ if "." not in version:
109
+ version = f"{version}.0"
110
+ return f"release_{version}"
111
+
112
+
113
+ class VEPAnnotatorBase(DockerAnnotator):
114
+ """
115
+ Base class for VEP annotators
116
+
117
+ Provides utilities for preparing and parsing files for VEP
118
+ """
119
+ def __init__(
120
+ self, pipeline: AnnotationPipeline | None,
121
+ info: AnnotatorInfo,
122
+ extra_attributes: list[str] | None = None,
123
+ ):
124
+ if not info.attributes:
125
+ attributes = [
126
+ "Gene",
127
+ "Feature",
128
+ "Feature_type",
129
+ "Consequence",
130
+ "worst_consequence",
131
+ "highest_impact",
132
+ "gene_consequence",
133
+ ]
134
+
135
+ if extra_attributes is not None:
136
+ attributes.extend(extra_attributes)
137
+
138
+ info.attributes = AnnotationConfigParser.parse_raw_attributes(
139
+ attributes)
140
+
141
+ self._vep_version = _resolve_vep_image_tag(
142
+ info.parameters.get("vep_version", None))
143
+
144
+ super().__init__(
145
+ pipeline, info,
146
+ )
147
+
148
+ def _init_images(self) -> None:
149
+ if self._vep_version is not None:
150
+ self.client.images.pull(
151
+ f"ensemblorg/ensembl-vep:{self._vep_version}",
152
+ )
153
+ else:
154
+ self.client.images.pull(
155
+ "ensemblorg/ensembl-vep:release_latest",
156
+ )
157
+
158
+ def _do_annotate(
159
+ self, annotatable: Annotatable | None,
160
+ context: dict[str, Any],
161
+ ) -> AnnotatedValues:
162
+ raise NotImplementedError(
163
+ "External annotator supports only batch mode",
164
+ )
165
+
166
+ def annotate(
167
+ self, annotatable: Annotatable | None,
168
+ context: dict[str, Any],
169
+ ) -> dict[str, Any]:
170
+ raise NotImplementedError(
171
+ "External annotator supports only batch mode",
172
+ )
173
+
174
+ def aggregate_attributes(
175
+ self, contexts: list[dict[str, Any]],
176
+ attr_name_list: list[str] | None = None,
177
+ ) -> None:
178
+ """Join list of attributes to display as one column in output."""
179
+ if attr_name_list is None:
180
+ attr_name_list = [attr.source for attr in self.attributes]
181
+
182
+ for context in contexts:
183
+ for attr in attr_name_list:
184
+ context[attr] = ";".join(context[attr])
185
+
186
+ def prepare_input(
187
+ self, file: TextIO, annotatables: list[VCFAllele | None],
188
+ ) -> None:
189
+ """Prepare input files for VEP in standard VEP variant format."""
190
+ writer = csv.writer(file, delimiter="\t", lineterminator="\n")
191
+ for idx, annotatable in enumerate(annotatables, 1):
192
+ if annotatable is None:
193
+ continue
194
+ if annotatable.type in [
195
+ Annotatable.Type.SMALL_DELETION,
196
+ Annotatable.Type.SMALL_INSERTION,
197
+ ]:
198
+ if annotatable.type == Annotatable.Type.SMALL_DELETION:
199
+ ref_alt = f"{annotatable.ref[1:]}/-"
200
+ else:
201
+ ref_alt = f"-/{annotatable.alt[1:]}"
202
+ writer.writerow([
203
+ annotatable.chrom,
204
+ annotatable.pos + 1,
205
+ annotatable.end_position - 1,
206
+ ref_alt,
207
+ "+",
208
+ idx,
209
+ ])
210
+ else:
211
+ writer.writerow([
212
+ annotatable.chrom,
213
+ annotatable.pos,
214
+ annotatable.end_position,
215
+ f"{annotatable.ref}/{annotatable.alt}",
216
+ "+",
217
+ idx,
218
+ ])
219
+ file.flush()
220
+
221
+ def read_output(
222
+ self, file: TextIO, contexts: list[dict[str, Any]],
223
+ attributes: dict[str, Any],
224
+ ) -> None:
225
+ """Read and return subprocess output contents."""
226
+ for context in contexts:
227
+ for attr in attributes:
228
+ context[attr] = []
229
+
230
+ reader = csv.reader(
231
+ filter(lambda row: not row.startswith("##"), file),
232
+ delimiter="\t",
233
+ )
234
+
235
+ header = next(reader)[1:]
236
+ unsupported_cols = {col for col in header if col not in contexts[0]}
237
+ if len(unsupported_cols) > 0:
238
+ logger.info(
239
+ "VEP annotator detected new unsupported columns: %s",
240
+ unsupported_cols,
241
+ )
242
+ columns_map = dict(enumerate(header))
243
+
244
+ for row in reader:
245
+ idx = int(row[0]) - 1
246
+ context = contexts[idx]
247
+
248
+ for idx, col in enumerate(row[1:]):
249
+ col_name = columns_map[idx]
250
+ if col_name not in context:
251
+ continue
252
+ context[col_name].append(col)
253
+
254
+ for context in contexts:
255
+ gene_consequences = set()
256
+ gene_consequences.update([
257
+ f"{gene}:{consequence}"
258
+ for gene, consequence in
259
+ zip(context["SYMBOL"], context["Consequence"], strict=True)
260
+ ])
261
+ context["gene_consequence"] = list(gene_consequences)
262
+ context["gene_consequence"].sort()
263
+
264
+ consequences: list[str] = []
265
+ for conseq in context["Consequence"]:
266
+ consequences.extend(conseq.split(","))
267
+
268
+ context["worst_consequence"] = [sorted(
269
+ consequences, key=lambda x: CONSEQUENCES[x],
270
+ reverse=True,
271
+ )[0]]
272
+ context["highest_impact"] = [sorted(
273
+ context["IMPACT"], key=lambda x: IMPACTS[x],
274
+ reverse=True,
275
+ )[0]]
276
+
277
+ def run_vep(self, args: list[str]) -> None:
278
+ command = ["vep"]
279
+ command.extend(args)
280
+ subprocess.run(command, check=True)
281
+
282
+ def open_files(self, work_dir: Path) -> tuple[TextIO, Path]:
283
+ return (
284
+ (work_dir / "input.tsv").open("w+t"),
285
+ (work_dir / "output.tsv"),
286
+ )
287
+
288
+
289
+ # The base raises NotImplementedError: this annotator is batch-only.
290
+ class VEPCacheAnnotator(VEPAnnotatorBase): # pylint: disable=abstract-method
291
+ """Annotation pipeline adapter for dummy_annotate using tempfiles."""
292
+
293
+ def __init__(
294
+ self, pipeline: AnnotationPipeline | None,
295
+ info: AnnotatorInfo,
296
+ ):
297
+ self.vep_cache_dir: Path | None = cast(
298
+ Path | None, info.parameters.get("cache_dir"),
299
+ )
300
+
301
+ assert self.vep_cache_dir is not None
302
+ super().__init__(
303
+ pipeline, info,
304
+ )
305
+
306
+ info.documentation += textwrap.dedent(f"""
307
+
308
+ Ensembl VEP plugin annotator that annotates using VEP through
309
+ a docker container with a prepared VEP cache.
310
+
311
+ This annotator is configured to run with VEP version {self._vep_version}
312
+
313
+ <a href="{self.BASE_DOC_URL}#vep-annotators" target="_blank">More info</a>
314
+
315
+ """) # ruff: ignore[line-too-long]
316
+
317
+ def get_attribute_specs(self) -> dict[str, AttributeSpec]:
318
+ return {
319
+ k: AttributeSpec(source=k, value_type=v[0], description=v[1])
320
+ for k, v in full_attributes.items()
321
+ }
322
+
323
+ def _do_batch_annotate(
324
+ self,
325
+ annotatables: Sequence[Annotatable | None],
326
+ contexts: list[dict[str, Any]],
327
+ batch_work_dir: str | None = None,
328
+ ) -> list[AnnotatedValues]:
329
+ assert self.work_dir is not None
330
+ if batch_work_dir is None:
331
+ work_dir = self.work_dir
332
+ else:
333
+ work_dir = self.work_dir / batch_work_dir
334
+ os.makedirs(work_dir, exist_ok=True)
335
+ work_dir.chmod(0o0777)
336
+ input_file, out_path = self.open_files(work_dir)
337
+ with input_file:
338
+ self.prepare_input(
339
+ input_file, cast(list[VCFAllele | None], annotatables),
340
+ )
341
+
342
+ self.run(
343
+ input_file_name=Path(input_file.name).name,
344
+ output_file_name=out_path.name,
345
+ work_dir=str(work_dir.absolute()),
346
+ )
347
+
348
+ with out_path.open("r") as out_file:
349
+ self.read_output(
350
+ out_file, contexts, self.get_attribute_specs(),
351
+ )
352
+
353
+ self.aggregate_attributes(contexts)
354
+
355
+ return [
356
+ self._from_sources(context)
357
+ for context in contexts
358
+ ]
359
+
360
+ def run(self, **kwargs: Any) -> None:
361
+ args = [
362
+ "vep",
363
+ "-i", str(Path("/work", kwargs["input_file_name"])),
364
+ "-o", str(Path("/work", kwargs["output_file_name"])),
365
+ "--tab", "--cache",
366
+ "--offline",
367
+ "--dir", "/vep_cache",
368
+ "--everything",
369
+ "--symbol",
370
+ "--no_stats",
371
+ "--force_overwrite",
372
+ ]
373
+ self.client.containers.run(
374
+ f"ensemblorg/ensembl-vep:{self._vep_version}",
375
+ args,
376
+ volumes={
377
+ kwargs["work_dir"]: {"bind": "/work", "mode": "rw"},
378
+ str(self.vep_cache_dir): {"bind": "/vep_cache", "mode": "ro"},
379
+ },
380
+ )
381
+
382
+
383
+ # The base raises NotImplementedError: this annotator is batch-only.
384
+ class VEPEffectAnnotator(VEPAnnotatorBase): # pylint: disable=abstract-method
385
+ """Annotation pipeline adapter for dummy_annotate using tempfiles."""
386
+
387
+ def __init__(
388
+ self, pipeline: AnnotationPipeline | None,
389
+ info: AnnotatorInfo,
390
+ ):
391
+ super().__init__(pipeline, info)
392
+
393
+ assert pipeline is not None
394
+ assert self.work_dir is not None
395
+
396
+ self.cache_repo = GenomicResourceCachedRepo(
397
+ pipeline.repository, str(self.work_dir / "grr_cache"),
398
+ )
399
+ self.genome_filename = None
400
+ self.gtf_path: Path | None = None
401
+ self.gtf_path_gz: Path | None = None
402
+ self.gene_models_resource: GenomicResource | None = None
403
+ self.genome_resource: GenomicResource | None = None
404
+
405
+ self.annotator_attributes = effect_attributes
406
+
407
+ gene_models = find_annotator_gene_models(info, self.cache_repo)
408
+ genome = find_annotator_reference_genome(
409
+ info, gene_models, pipeline, self.cache_repo)
410
+
411
+ self.gene_models_resource = gene_models.resource
412
+ self.genome_resource = genome.resource
413
+
414
+ info.resources.append(self.gene_models_resource)
415
+ info.resources.append(self.genome_resource)
416
+
417
+
418
+ info.documentation += textwrap.dedent(f"""
419
+
420
+ Ensembl VEP plugin annotator that annotates using VEP through
421
+ a docker container with GTF and FASTA files.
422
+
423
+ This annotator is configured to run with VEP version {self._vep_version}
424
+
425
+ <a href="{self.BASE_DOC_URL}#vep-annotators" target="_blank">More info</a>
426
+
427
+ """) # ruff: ignore[too-many-blank-lines, line-too-long]
428
+
429
+ self.resources_dir = (self.work_dir / "annotator_resources").absolute()
430
+ self.resources_dir.mkdir(exist_ok=True)
431
+
432
+ def find_gene_models(self) -> GenomicResource:
433
+ """Find gene models from info or genomic context."""
434
+ return cast(GenomicResource, self.gene_models_resource)
435
+
436
+ def find_genome(self) -> GenomicResource:
437
+ """Find genome from info, resource label or genomic context."""
438
+ return cast(GenomicResource, self.genome_resource)
439
+
440
+ def get_attribute_specs(self) -> dict[str, AttributeSpec]:
441
+ return {
442
+ k: AttributeSpec(source=k, value_type=v[0], description=v[1])
443
+ for k, v in effect_attributes.items()
444
+ }
445
+
446
+ def _do_batch_annotate(
447
+ self,
448
+ annotatables: Sequence[Annotatable | None],
449
+ contexts: list[dict[str, Any]],
450
+ batch_work_dir: str | None = None,
451
+ ) -> list[AnnotatedValues]:
452
+
453
+ assert self.genome_resource is not None
454
+ assert self.genome_filename is not None
455
+ assert self.gtf_path_gz is not None
456
+ assert self.work_dir is not None
457
+
458
+ for file_name in reference_genome_files(
459
+ self.genome_resource.get_config()):
460
+ self.genome_resource.get_file_url(file_name)
461
+
462
+ genome_filepath = Path(
463
+ "/grr",
464
+ self.genome_resource.get_full_id(),
465
+ self.genome_filename,
466
+ )
467
+
468
+ if batch_work_dir is None:
469
+ work_dir = self.work_dir
470
+ else:
471
+ work_dir = self.work_dir / batch_work_dir
472
+ os.makedirs(work_dir, exist_ok=True)
473
+ work_dir.chmod(0o0777)
474
+ input_file, out_path = self.open_files(work_dir)
475
+ with input_file:
476
+ self.prepare_input(
477
+ input_file, cast(list[VCFAllele | None], annotatables),
478
+ )
479
+ self.run(
480
+ input_file_name=Path(input_file.name).name,
481
+ output_file_name=out_path.name,
482
+ work_dir=str(work_dir.absolute()),
483
+ genome_filepath=str(genome_filepath),
484
+ gtf_filename=self.gtf_path_gz.name,
485
+ )
486
+
487
+ with out_path.open("r") as out_file:
488
+ self.read_output(
489
+ out_file, contexts, self.get_attribute_specs(),
490
+ )
491
+
492
+ self.aggregate_attributes(contexts)
493
+
494
+ return [
495
+ self._from_sources(context)
496
+ for context in contexts
497
+ ]
498
+
499
+ def run(self, **kwargs: Any) -> None:
500
+ assert self.genome_resource is not None
501
+ args = [
502
+ "vep",
503
+ "-i", str(Path("/work", kwargs["input_file_name"])),
504
+ "-o", str(Path("/work", kwargs["output_file_name"])),
505
+ "--tab",
506
+ "--fasta", str(Path("/grr", kwargs["genome_filepath"])),
507
+ "--gtf", str(Path("/resources", kwargs["gtf_filename"])),
508
+ "--symbol",
509
+ "--no_stats",
510
+ "--force_overwrite",
511
+ ]
512
+ cache_path = Path(self.genome_resource.proto.url[7:]).absolute()
513
+ self.client.containers.run(
514
+ f"ensemblorg/ensembl-vep:{self._vep_version}",
515
+ args,
516
+ volumes={
517
+ kwargs["work_dir"]: {"bind": "/work", "mode": "rw"},
518
+ str(cache_path): {"bind": "/grr", "mode": "ro"},
519
+ str(self.resources_dir): {"bind": "/resources", "mode": "ro"},
520
+ },
521
+ )
522
+
523
+ def open(self) -> Annotator:
524
+ assert self.genome_resource is not None
525
+ assert self.gene_models_resource is not None
526
+
527
+ self.genome_filename = \
528
+ self.genome_resource.get_config()["filename"]
529
+
530
+ gtf_file_name = self.gene_models_resource.resource_id.replace("/", "_")
531
+
532
+ self.gtf_path = self.resources_dir / f"{gtf_file_name}.gtf"
533
+ self.gtf_path_gz = self.gtf_path.with_suffix(
534
+ f"{self.gtf_path.suffix}.gz",
535
+ )
536
+
537
+ if not self.gtf_path_gz.exists():
538
+ gene_models = build_gene_models_from_resource(
539
+ self.gene_models_resource,
540
+ )
541
+
542
+ gene_models.load()
543
+ gtf_content = gene_models_to_gtf(gene_models).getvalue()
544
+
545
+ self.gtf_path.write_text(gtf_content)
546
+
547
+ pysam.tabix_compress(
548
+ str(self.gtf_path), str(self.gtf_path_gz),
549
+ )
550
+ pysam.tabix_index(str(self.gtf_path_gz), preset="gff")
551
+
552
+ return super().open()
553
+
554
+
555
+ def build_vep_cache_annotator(
556
+ pipeline: AnnotationPipeline,
557
+ info: AnnotatorInfo,
558
+ ) -> Annotator:
559
+ return VEPCacheAnnotator(pipeline, info)
560
+
561
+
562
+ def build_vep_effect_annotator(
563
+ pipeline: AnnotationPipeline,
564
+ info: AnnotatorInfo,
565
+ ) -> Annotator:
566
+ return VEPEffectAnnotator(pipeline, info)
@@ -0,0 +1,482 @@
1
+
2
+ full_attributes = {
3
+ "Location": (
4
+ "str",
5
+ ("Location of variant in standard "
6
+ "coordinate format (chr:start or chr:start-end)"),
7
+ ),
8
+ "Allele": (
9
+ "str",
10
+ "The variant allele used to calculate the consequence",
11
+ ),
12
+ "Gene": (
13
+ "str",
14
+ "Stable ID of affected gene",
15
+ ),
16
+ "Feature": (
17
+ "str",
18
+ "Stable ID of feature",
19
+ ),
20
+ "Feature_type": (
21
+ "str",
22
+ ("Type of feature - Transcript, "
23
+ "RegulatoryFeature or MotifFeature"),
24
+ ),
25
+ "Consequence": (
26
+ "str",
27
+ "Consequence type",
28
+ ),
29
+ "cDNA_position": (
30
+ "str",
31
+ "Relative position of base pair in cDNA sequence",
32
+ ),
33
+ "CDS_position": (
34
+ "str",
35
+ "Relative position of base pair in coding sequence",
36
+ ),
37
+ "Protein_position": (
38
+ "str",
39
+ "Relative position of amino acid in protein",
40
+ ),
41
+ "Amino_acids": (
42
+ "str",
43
+ "Reference and variant amino acids",
44
+ ),
45
+ "Codons": (
46
+ "str",
47
+ "Reference and variant codon sequence",
48
+ ),
49
+ "Existing_variation": (
50
+ "str",
51
+ "Identifier(s) of co-located known variants",
52
+ ),
53
+ "IMPACT": (
54
+ "str",
55
+ "Subjective impact classification of consequence type",
56
+ ),
57
+ "DISTANCE": (
58
+ "str",
59
+ "Shortest distance from variant to transcript",
60
+ ),
61
+ "STRAND": (
62
+ "str",
63
+ "Strand of the feature (1/-1)",
64
+ ),
65
+ "FLAGS": (
66
+ "str",
67
+ "Transcript quality flags",
68
+ ),
69
+ "VARIANT_CLASS": (
70
+ "str",
71
+ "SO variant class",
72
+ ),
73
+ "SYMBOL": (
74
+ "str",
75
+ "Gene symbol (e.g. HGNC)",
76
+ ),
77
+ "SYMBOL_SOURCE": (
78
+ "str",
79
+ "Source of gene symbol",
80
+ ),
81
+ "HGNC_ID": (
82
+ "str",
83
+ "Stable identifer of HGNC gene symbol",
84
+ ),
85
+ "BIOTYPE": (
86
+ "str",
87
+ "Biotype of transcript or regulatory feature",
88
+ ),
89
+ "CANONICAL": (
90
+ "str",
91
+ "Indicates if transcript is canonical for this gene",
92
+ ),
93
+ "MANE": (
94
+ "str",
95
+ ("MANE (Matched Annotation from NCBI and EMBL-EBI) "
96
+ "set(s) the transcript belongs to"),
97
+ ),
98
+ "MANE_SELECT": (
99
+ "str",
100
+ ("MANE Select (Matched Annotation "
101
+ "from NCBI and EMBL-EBI) Transcript"),
102
+ ),
103
+ "MANE_PLUS_CLINICAL": (
104
+ "str",
105
+ ("MANE Plus Clinical (Matched Annotation "
106
+ "from NCBI and EMBL-EBI) Transcript"),
107
+ ),
108
+ "TSL": (
109
+ "str",
110
+ "Transcript support level",
111
+ ),
112
+ "APPRIS": (
113
+ "str",
114
+ ("Annotates alternatively spliced transcripts as primary "
115
+ "or alternate based on a range of computational methods"),
116
+ ),
117
+ "CCDS": (
118
+ "str",
119
+ "Indicates if transcript is a CCDS transcript",
120
+ ),
121
+ "ENSP": (
122
+ "str",
123
+ "Protein identifer",
124
+ ),
125
+ "SWISSPROT": (
126
+ "str",
127
+ "UniProtKB/Swiss-Prot accession",
128
+ ),
129
+ "TREMBL": (
130
+ "str",
131
+ "UniProtKB/TrEMBL accession",
132
+ ),
133
+ "UNIPARC": (
134
+ "str",
135
+ "UniParc accession",
136
+ ),
137
+ "UNIPROT_ISOFORM": (
138
+ "str",
139
+ "Direct mappings to UniProtKB isoforms",
140
+ ),
141
+ "GENE_PHENO": (
142
+ "str",
143
+ ("Indicates if gene is associated with "
144
+ "a phenotype, disease or trait"),
145
+ ),
146
+ "SIFT": (
147
+ "str",
148
+ "SIFT prediction and/or score",
149
+ ),
150
+ "PolyPhen": (
151
+ "str",
152
+ "PolyPhen prediction and/or score",
153
+ ),
154
+ "EXON": (
155
+ "str",
156
+ "Exon number(s) / total",
157
+ ),
158
+ "INTRON": (
159
+ "str",
160
+ "Intron number(s) / total",
161
+ ),
162
+ "DOMAINS": (
163
+ "str",
164
+ ("The source and identifer of "
165
+ "any overlapping protein domains"),
166
+ ),
167
+ "miRNA": (
168
+ "str",
169
+ ("SO terms of overlapped miRNA "
170
+ "secondary structure feature(s)"),
171
+ ),
172
+ "HGVSc": (
173
+ "str",
174
+ "HGVS coding sequence name",
175
+ ),
176
+ "HGVSp": (
177
+ "str",
178
+ "HGVS protein sequence name",
179
+ ),
180
+ "HGVS_OFFSET": (
181
+ "str",
182
+ ("Indicates by how many bases the "
183
+ "HGVS notations for this variant have been shifted"),
184
+ ),
185
+ "AF": (
186
+ "str",
187
+ ("Frequency of existing variant in "
188
+ "1000 Genomes combined population"),
189
+ ),
190
+ "AFR_AF": (
191
+ "str",
192
+ ("Frequency of existing variant in "
193
+ "1000 Genomes combined African population"),
194
+ ),
195
+ "AMR_AF": (
196
+ "str",
197
+ ("Frequency of existing variant in "
198
+ "1000 Genomes combined American population"),
199
+ ),
200
+ "EAS_AF": (
201
+ "str",
202
+ ("Frequency of existing variant in "
203
+ "1000 Genomes combined East Asian population"),
204
+ ),
205
+ "EUR_AF": (
206
+ "str",
207
+ ("Frequency of existing variant in "
208
+ "1000 Genomes combined European population"),
209
+ ),
210
+ "SAS_AF": (
211
+ "str",
212
+ ("Frequency of existing variant in "
213
+ "1000 Genomes combined South Asian population"),
214
+ ),
215
+ "gnomADe_AF": (
216
+ "str",
217
+ ("Frequency of existing variant in "
218
+ "gnomAD exomes combined population"),
219
+ ),
220
+ "gnomADe_AFR_AF": (
221
+ "str",
222
+ ("Frequency of existing variant in "
223
+ "gnomAD exomes African/American population"),
224
+ ),
225
+ "gnomADe_AMR_AF": (
226
+ "str",
227
+ ("Frequency of existing variant in "
228
+ "gnomAD exomes American population"),
229
+ ),
230
+ "gnomADe_ASJ_AF": (
231
+ "str",
232
+ ("Frequency of existing variant in "
233
+ "gnomAD exomes Ashkenazi Jewish population"),
234
+ ),
235
+ "gnomADe_EAS_AF": (
236
+ "str",
237
+ ("Frequency of existing variant in "
238
+ "gnomAD exomes East Asian population"),
239
+ ),
240
+ "gnomADe_FIN_AF": (
241
+ "str",
242
+ ("Frequency of existing variant in "
243
+ "gnomAD exomes Finnish population"),
244
+ ),
245
+ "gnomADe_MID_AF": (
246
+ "str",
247
+ ("Frequency of existing variant in "
248
+ "gnomAD exomes Mid-eastern population"),
249
+ ),
250
+ "gnomADe_NFE_AF": (
251
+ "str",
252
+ ("Frequency of existing variant in "
253
+ "gnomAD exomes Non-Finnish European population"),
254
+ ),
255
+ "gnomADe_OTH_AF": (
256
+ "str",
257
+ ("Frequency of existing variant in "
258
+ "gnomAD exomes other combined populations"),
259
+ ),
260
+ "gnomADe_SAS_AF": (
261
+ "str",
262
+ ("Frequency of existing variant in "
263
+ "gnomAD exomes South Asian population"),
264
+ ),
265
+ "gnomADe_REMAINING_AF": (
266
+ "str",
267
+ ("Frequency of existing variant in "
268
+ "gnomAD exomes remaining combined populations"),
269
+ ),
270
+ "gnomADg_AF": (
271
+ "str",
272
+ ("Frequency of existing variant in "
273
+ "gnomAD genomes combined population"),
274
+ ),
275
+ "gnomADg_AFR_AF": (
276
+ "str",
277
+ ("Frequency of existing variant in "
278
+ "gnomAD genomes African/American population"),
279
+ ),
280
+ "gnomADg_AMI_AF": (
281
+ "str",
282
+ ("Frequency of existing variant in "
283
+ "gnomAD genomes Amish population"),
284
+ ),
285
+ "gnomADg_AMR_AF": (
286
+ "str",
287
+ ("Frequency of existing variant in "
288
+ "gnomAD genomes American population"),
289
+ ),
290
+ "gnomADg_ASJ_AF": (
291
+ "str",
292
+ ("Frequency of existing variant in "
293
+ "gnomAD genomes Ashkenazi Jewish population"),
294
+ ),
295
+ "gnomADg_EAS_AF": (
296
+ "str",
297
+ ("Frequency of existing variant in "
298
+ "gnomAD genomes East Asian population"),
299
+ ),
300
+ "gnomADg_FIN_AF": (
301
+ "str",
302
+ ("Frequency of existing variant in "
303
+ "gnomAD genomes Finnish population"),
304
+ ),
305
+ "gnomADg_MID_AF": (
306
+ "str",
307
+ ("Frequency of existing variant in "
308
+ "gnomAD genomes Mid-eastern population"),
309
+ ),
310
+ "gnomADg_NFE_AF": (
311
+ "str",
312
+ ("Frequency of existing variant in "
313
+ "gnomAD genomes Non-Finnish European population"),
314
+ ),
315
+ "gnomADg_OTH_AF": (
316
+ "str",
317
+ ("Frequency of existing variant in "
318
+ "gnomAD genomes other combined populations"),
319
+ ),
320
+ "gnomADg_SAS_AF": (
321
+ "str",
322
+ ("Frequency of existing variant in "
323
+ "gnomAD genomes South Asian population"),
324
+ ),
325
+ "gnomADg_REMAINING_AF": (
326
+ "str",
327
+ ("Frequency of existing variant in "
328
+ "gnomAD genomes remaining combined populations"),
329
+ ),
330
+ "MAX_AF": (
331
+ "str",
332
+ ("Maximum observed allele frequency in "
333
+ "1000 Genomes, ESP and ExAC/gnomAD"),
334
+ ),
335
+ "MAX_AF_POPS": (
336
+ "str",
337
+ ("Populations in which maximum "
338
+ "allele frequency was observed"),
339
+ ),
340
+ "CLIN_SIG": (
341
+ "str",
342
+ "ClinVar clinical significance of the dbSNP variant",
343
+ ),
344
+ "SOMATIC": (
345
+ "str",
346
+ "Somatic status of existing variant",
347
+ ),
348
+ "PHENO": (
349
+ "str",
350
+ ("Indicates if existing variant(s) is associated with "
351
+ "a phenotype, disease or trait; "
352
+ "multiple values correspond to multiple variants"),
353
+ ),
354
+ "PUBMED": (
355
+ "str",
356
+ "Pubmed ID(s) of publications that cite existing variant",
357
+ ),
358
+ "MOTIF_NAME": (
359
+ "str",
360
+ ("The stable identifier of a transcription factor "
361
+ "binding profile (TFBP) aligned at this position"),
362
+ ),
363
+ "MOTIF_POS": (
364
+ "str",
365
+ ("The relative position of the "
366
+ "variation in the aligned TFBP"),
367
+ ),
368
+ "HIGH_INF_POS": (
369
+ "str",
370
+ ("A flag indicating if the variant falls in a "
371
+ "high information position of the TFBP"),
372
+ ),
373
+ "MOTIF_SCORE_CHANGE": (
374
+ "str",
375
+ ("The difference in motif score of the reference "
376
+ "and variant sequences for the TFBP"),
377
+ ),
378
+ "TRANSCRIPTION_FACTORS": (
379
+ "str",
380
+ ("List of transcription factors which bind to "
381
+ "the transcription factor binding profile"),
382
+ ),
383
+ "worst_consequence": (
384
+ "str", "Worst consequence reported by VEP",
385
+ ),
386
+ "highest_impact": ("str", "Highest impact reported by VEP"),
387
+ "gene_consequence": (
388
+ "str", "List of gene consequence pairs reported by VEP",
389
+ ),
390
+ }
391
+
392
+ effect_attributes = {
393
+ "Location": (
394
+ "str",
395
+ ("Location of variant in standard "
396
+ "coordinate format (chr:start or chr:start-end)"),
397
+ ),
398
+ "Allele": (
399
+ "str",
400
+ "The variant allele used to calculate the consequence",
401
+ ),
402
+ "Gene": (
403
+ "str",
404
+ "Stable ID of affected gene",
405
+ ),
406
+ "Feature": (
407
+ "str",
408
+ "Stable ID of feature",
409
+ ),
410
+ "Feature_type": (
411
+ "str",
412
+ ("Type of feature - Transcript, "
413
+ "RegulatoryFeature or MotifFeature"),
414
+ ),
415
+ "Consequence": (
416
+ "str",
417
+ "Consequence type",
418
+ ),
419
+ "cDNA_position": (
420
+ "str",
421
+ "Relative position of base pair in cDNA sequence",
422
+ ),
423
+ "CDS_position": (
424
+ "str",
425
+ "Relative position of base pair in coding sequence",
426
+ ),
427
+ "Protein_position": (
428
+ "str",
429
+ "Relative position of amino acid in protein",
430
+ ),
431
+ "Amino_acids": (
432
+ "str",
433
+ "Reference and variant amino acids",
434
+ ),
435
+ "Codons": (
436
+ "str",
437
+ "Reference and variant codon sequence",
438
+ ),
439
+ "Existing_variation": (
440
+ "str",
441
+ "Identifier(s) of co-located known variants",
442
+ ),
443
+ "IMPACT": (
444
+ "str",
445
+ "Subjective impact classification of consequence type",
446
+ ),
447
+ "DISTANCE": (
448
+ "str",
449
+ "Shortest distance from variant to transcript",
450
+ ),
451
+ "STRAND": (
452
+ "str",
453
+ "Strand of the feature (1/-1)",
454
+ ),
455
+ "FLAGS": (
456
+ "str",
457
+ "Transcript quality flags",
458
+ ),
459
+ "SYMBOL": (
460
+ "str",
461
+ "Gene symbol (e.g. HGNC)",
462
+ ),
463
+ "SYMBOL_SOURCE": (
464
+ "str",
465
+ "Source of gene symbol",
466
+ ),
467
+ "HGNC_ID": (
468
+ "str",
469
+ "Stable identifer of HGNC gene symbol",
470
+ ),
471
+ "SOURCE": (
472
+ "str",
473
+ "Source of transcript",
474
+ ),
475
+ "worst_consequence": (
476
+ "str", "Worst consequence reported by VEP",
477
+ ),
478
+ "highest_impact": ("str", "Highest impact reported by VEP"),
479
+ "gene_consequence": (
480
+ "str", "List of gene consequence pairs reported by VEP",
481
+ ),
482
+ }