Coverage for src/python/ensembl/vep/runner/corpus/describe.py: 97%
84 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"""Registered corpus descriptions."""
16from __future__ import annotations
18import logging
19from typing import ClassVar
21from attrs import asdict
23from ensembl.vep.annotators.factory import build_annotator
24from ensembl.vep.config import Config
25from ensembl.vep.config.report import resolve_report_format
26from ensembl.vep.corpus.annotate import annotated_variations
27from ensembl.vep.corpus.base import Corpus
28from ensembl.vep.corpus.describe import (
29 CHROMOSOME_HEADERS,
30 CLASS_HEADERS,
31 OVERLAP_HEADERS,
32 TRANSCRIPT_HEADERS,
33 CorpusDescription,
34)
35from ensembl.vep.corpus.registry import CorpusOptionsError, build_corpus_from_options
36from ensembl.vep.render.page import Section, render_page
37from ensembl.vep.render.table import TableFormat, render_table
38from ensembl.vep.runner.base import ExitCode
39from ensembl.vep.runner.registry import register_runner
40from ensembl.vep.stats.summary import RunSummary, RunSummaryCollector
42__all__ = ["Runner"]
44logger = logging.getLogger(__name__)
47@register_runner("corpus.describe")
48class Runner:
49 """Runner for describing a registered corpus.
51 With ``--annotate``, also run the configured annotator over the whole corpus and count the
52 terms it emits -- what the corpus exercises, not only what it contains.
54 Attributes:
55 name (ClassVar[str]): The registry name.
56 sections (ClassVar[tuple[str, ...]]): The configuration sections read.
57 description (ClassVar[str]): One-line description for the subcommand list.
58 """
60 name: ClassVar[str] = "corpus.describe"
61 sections: ClassVar[tuple[str, ...]] = ("logging", "corpus", "annotation", "corpus_describe")
62 description: ClassVar[str] = "describe a registered corpus and list its selectable overlaps"
64 def __init__(self, config: Config) -> None:
65 """Hold the configuration."""
66 self.config = config
68 def run(self) -> ExitCode:
69 """Describe the configured corpus in the requested format."""
70 corpus = self.config.corpus
71 try:
72 built_corpus = build_corpus_from_options(corpus)
73 except CorpusOptionsError as unusable:
74 logger.error("%s", unusable)
75 return ExitCode.USAGE
76 try:
77 return self._describe(built_corpus)
78 finally:
79 built_corpus.close()
81 def _describe(self, built_corpus: Corpus) -> ExitCode:
82 """Describe one successfully built corpus."""
83 describe = self.config.corpus_describe
84 description = CorpusDescription.build(
85 built_corpus,
86 select=describe.select,
87 batch_size=self.config.annotation.batch_size,
88 )
89 if describe.select is not None and not description.overlaps:
90 logger.error("no overlap is named %r in %s", describe.select, built_corpus.description)
91 return ExitCode.USAGE
93 logger.info(
94 "%s: %d transcripts, %d overlaps, %.1f distinct transcripts per chunk of %d",
95 built_corpus.description,
96 len(description.transcripts),
97 len(description.overlaps),
98 description.transcripts_per_chunk,
99 description.batch_size,
100 )
101 summary = self._summary(built_corpus) if describe.annotate else None
102 try:
103 table_format = resolve_report_format(
104 describe.output_format, graph=False, table_default="markdown", graph_formats=()
105 )
106 except ValueError as unusable:
107 logger.error("%s", unusable)
108 return ExitCode.USAGE
109 self._emit(self._render(description, table_format, summary))
110 return ExitCode.OK
112 def _summary(self, corpus: Corpus) -> RunSummary:
113 """Annotate every variant of the corpus with the configured annotator and summarise the terms."""
114 annotation = self.config.annotation
115 annotator = build_annotator(
116 **asdict(annotation),
117 upstream_distance=self.config.source.upstream_distance,
118 downstream_distance=self.config.source.downstream_distance,
119 )
120 collector = RunSummaryCollector(metadata={"annotator": annotation.annotator})
121 for variation in annotated_variations(corpus, annotator):
122 collector.observe(variation)
123 summary = collector.finish()
124 logger.info("annotated %s with %s", summary.subtitle, annotation.annotator)
125 return summary
127 @staticmethod
128 def _render(description: CorpusDescription, table_format: str, summary: RunSummary | None = None) -> str:
129 """Render the description's tables, and the term counts when there are any, as one page or text."""
130 tables: list[tuple[str, str, tuple[str, ...], list[tuple[object, ...]]]] = [
131 ("chromosomes", "Chromosomes", CHROMOSOME_HEADERS, description.chromosome_rows()),
132 ("transcripts", "Transcripts", TRANSCRIPT_HEADERS, description.transcript_rows()),
133 ("classes", "Variant classes", CLASS_HEADERS, description.class_rows()),
134 ]
135 if summary is not None:
136 tables.extend(
137 [
138 (
139 "most_severe",
140 "Most severe consequences",
141 ("Term", "Variants"),
142 list(summary.most_severe),
143 ),
144 ("consequences", "Consequences", ("Term", "Occurrences"), list(summary.consequences)),
145 (
146 "coding",
147 "Coding consequences",
148 ("Term", "Occurrences"),
149 list(summary.coding_consequences),
150 ),
151 ]
152 )
153 tables.append(("overlaps", "Overlaps", OVERLAP_HEADERS, description.overlap_rows()))
154 chosen = TableFormat(table_format)
155 subtitle = (
156 f"{description.transcripts_per_chunk:.1f} distinct transcripts per chunk "
157 f"of {description.batch_size} overlaps"
158 )
159 if chosen is TableFormat.HTML:
160 sections = []
161 for identifier, title, headers, rows in tables:
162 sections.append(
163 Section(identifier=identifier, title=title, blocks=(render_table(headers, rows, chosen),))
164 )
165 return render_page(f"Corpus: {description.kind}", sections, subtitle)
167 blocks = [f"# Corpus: {description.kind}", subtitle]
168 for _identifier, title, headers, rows in tables:
169 blocks.append(f"\n## {title}\n")
170 blocks.append(render_table(headers, rows, chosen))
171 return "\n".join(blocks)
173 def _emit(self, rendered: str) -> None:
174 """Write the rendering to the configured destination."""
175 destination = self.config.corpus_describe.output_file
176 if destination is None:
177 print(rendered)
178 return
179 destination.write_text(rendered, encoding="utf-8")
180 logger.info("wrote %s", destination)