Coverage for src/python/ensembl/vep/explain/summary.py: 95%
132 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"""Text and HTML summaries of explained overlaps.
16The summary describes the variant, transcript, affected positions, codons, and full-sequence
17changes before presenting how the annotator reached its result.
18"""
20from __future__ import annotations
22from html import escape
24from ensembl.vep.common import Strand
25from ensembl.vep.common.constants import EMPTY_ALLELE, UNKNOWN_VALUE
26from ensembl.vep.models.overlap import TranscriptVariationAllele
27from ensembl.vep.models.overlap.transcript_variation_allele import Position
28from ensembl.vep.common.methods import format_coords
30__all__ = ["format_summary", "summary_html", "summary_rows"]
32_CONTEXT_LENGTH = 12
33"""Bases or residues shown either side of the first difference in a full CDS or peptide."""
36def summary_rows(overlap: TranscriptVariationAllele) -> list[tuple[str, str]]:
37 """Return applicable overlap details as labelled rows.
39 Args:
40 overlap (TranscriptVariationAllele): The overlap to describe.
42 Returns:
43 list[tuple[str, str]]: Label-value pairs in reading order.
44 """
45 rows = [("variant", _variant_text(overlap)), ("transcript", _transcript_text(overlap))]
46 rows.append(("location", _location_text(overlap)))
47 rows.append(("coding", _coding_text(overlap)))
49 positions = _positions_text(overlap)
50 if positions:
51 rows.append(("positions", positions))
53 if overlap.reference_codon is not None:
54 rows.append(("codons", f"{overlap.reference_codon or '-'}/{overlap.alternate_codon or '-'}"))
55 rows.append(("amino acids", f"{overlap.reference_peptide or '-'}/{overlap.alternate_peptide or '-'}"))
57 if overlap.reference_cds is not None and overlap.alternate_cds is not None:
58 rows.append(("full CDS", _sequence_change(overlap.reference_cds, overlap.alternate_cds, "bp")))
59 if overlap.reference_cds_peptide is not None and overlap.alternate_cds_peptide is not None:
60 peptide_change = _sequence_change(overlap.reference_cds_peptide, overlap.alternate_cds_peptide, "aa")
61 rows.append(("full peptide", peptide_change))
62 return rows
65def format_summary(overlap: TranscriptVariationAllele) -> str:
66 """Return the summary as an aligned text block headed ``summary:``."""
67 rows = summary_rows(overlap)
68 width = max(len(label) for label, _value in rows)
69 lines = ["summary:"]
70 for label, value in rows:
71 lines.append(f" {label:<{width}} {value}")
72 return "\n".join(lines)
75def summary_html(overlap: TranscriptVariationAllele) -> str:
76 """Return the summary as an HTML table for an explanation page."""
77 cells = []
78 for label, value in summary_rows(overlap):
79 cells.append(f"<tr><th>{escape(label)}</th><td><code>{escape(value)}</code></td></tr>")
80 return f'<table class="vep-table">{"".join(cells)}</table>'
83def _variant_text(overlap: TranscriptVariationAllele) -> str:
84 """Return the allele's locus and alleles, with the record's id and the allele's number."""
85 allele = overlap.overlapping_feature
86 region = allele.slice.seq_region_name if allele.slice is not None else UNKNOWN_VALUE
87 text = f"{region}:{format_coords(allele.start, allele.end)} "
88 text += f"{allele.reference_allele or EMPTY_ALLELE}>{allele.alternate_allele or EMPTY_ALLELE}"
90 variation = allele.variation
91 if variation is None:
92 return text
93 details = []
94 if variation.stable_id: 94 ↛ 96line 94 didn't jump to line 96 because the condition on line 94 was always true
95 details.append(f"id {variation.stable_id}")
96 alleles = list(variation.variation_alleles or ())
97 for number, candidate in enumerate(alleles, start=1):
98 if candidate is allele:
99 details.append(f"alternate allele {number} of {len(alleles)}")
100 if variation.uploaded_locus is not None and variation.uploaded_locus.allele_string: 100 ↛ 102line 100 didn't jump to line 102 because the condition on line 100 was always true
101 details.append(f"input {variation.uploaded_locus.start} {variation.uploaded_locus.allele_string}")
102 return f"{text} ({', '.join(details)})" if details else text
105def _transcript_text(overlap: TranscriptVariationAllele) -> str:
106 """Return the transcript's id, span, strand, biotype and gene."""
107 transcript = overlap.feature
108 strand = "+" if transcript.strand == Strand.FORWARD else "-"
109 details = [f"{transcript.start}-{transcript.end}", f"strand {strand}"]
110 gene = transcript.gene
111 biotype = transcript.biotype or (gene.biotype if gene is not None else None)
112 if biotype:
113 details.append(biotype)
114 if gene is not None:
115 gene_text = gene.stable_id
116 if gene.symbol: 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true
117 gene_text += f" {gene.symbol}"
118 details.append(f"gene {gene_text}")
119 return f"{transcript.stable_id} ({', '.join(details)})"
122def _location_text(overlap: TranscriptVariationAllele) -> str:
123 """Return which exons and introns the variant touches, or how far outside it lies."""
124 transcript = overlap.feature
125 allele = overlap.overlapping_feature
126 variant_min, variant_max = min(allele.start, allele.end), max(allele.start, allele.end)
128 touched = []
129 for label, features in (("exon", transcript.spliced_exons), ("intron", transcript.introns)):
130 numbers = []
131 for number, feature in enumerate(features, start=1):
132 if variant_min <= feature.end and variant_max >= feature.start:
133 numbers.append(number)
134 if numbers:
135 touched.append(f"{label} {_number_range(numbers)}/{len(features)}")
136 if touched:
137 return ", ".join(touched)
139 if variant_max < transcript.start: 139 ↛ 142line 139 didn't jump to line 142 because the condition on line 139 was always true
140 distance = transcript.start - variant_max
141 else:
142 distance = variant_min - transcript.end
143 upstream = (variant_max < transcript.start) == (transcript.strand == Strand.FORWARD)
144 return f"{distance} bp {'upstream' if upstream else 'downstream'} of the transcript"
147def _number_range(numbers: list[int]) -> str:
148 """Return ``[3]`` as ``3`` and ``[3, 4]`` as ``3-4``."""
149 return str(numbers[0]) if len(numbers) == 1 else f"{numbers[0]}-{numbers[-1]}"
152def _coding_text(overlap: TranscriptVariationAllele) -> str:
153 """Return the coding span and length, and the padding of an incomplete 5' end."""
154 transcript = overlap.feature
155 if transcript.coding_start is None or transcript.coding_end is None:
156 return "non-coding"
158 low, high = sorted((transcript.coding_start, transcript.coding_end))
159 text = f"genomic {low}-{high}"
160 if transcript.cdna_coding_start is not None and transcript.cdna_coding_end is not None: 160 ↛ 162line 160 didn't jump to line 162 because the condition on line 160 was always true
161 text += f", cDNA {transcript.cdna_coding_start}-{transcript.cdna_coding_end}"
162 if transcript.cds_length is not None: 162 ↛ 164line 162 didn't jump to line 164 because the condition on line 162 was always true
163 text += f", {transcript.cds_length} bp"
164 phase = transcript.cds_start_phase
165 if phase: 165 ↛ 166line 165 didn't jump to line 166 because the condition on line 165 was never true
166 text += f" including {phase} N (5' incomplete, start phase {phase})"
167 return text
170def _positions_text(overlap: TranscriptVariationAllele) -> str:
171 """Return the cDNA, CDS and protein positions VEP would write, where there are any."""
172 positions: list[tuple[str, Position | None]] = [
173 ("cDNA", overlap.cdna_position),
174 ("CDS", overlap.cds_position),
175 ("protein", overlap.protein_position),
176 ]
177 texts = []
178 for label, position in positions:
179 if position is not None:
180 texts.append(f"{label} {format_coords(*position)}")
181 return ", ".join(texts)
184def _sequence_change(reference: str, alternate: str, unit: str) -> str:
185 """Return sequence lengths and the first difference, or report no change."""
186 if reference == alternate:
187 return f"unchanged, {len(reference)} {unit}"
189 first_difference = 0
190 for reference_symbol, alternate_symbol in zip(reference, alternate):
191 if reference_symbol != alternate_symbol:
192 break
193 first_difference += 1
195 window_start = max(0, first_difference - _CONTEXT_LENGTH)
196 window_end = first_difference + _CONTEXT_LENGTH + 1
197 reference_window = _marked_window(reference, window_start, first_difference, window_end)
198 alternate_window = _marked_window(alternate, window_start, first_difference, window_end)
199 return (
200 f"{len(reference)} -> {len(alternate)} {unit}, first difference at {first_difference + 1}: "
201 f"{reference_window} -> {alternate_window}"
202 )
205def _marked_window(sequence: str, window_start: int, marked: int, window_end: int) -> str:
206 """Return ``sequence[window_start:window_end]``, the symbol at ``marked`` in brackets."""
207 before = sequence[window_start:marked]
208 symbol = sequence[marked : marked + 1] or "-"
209 after = sequence[marked + 1 : window_end]
210 leading = "..." if window_start > 0 else ""
211 trailing = "..." if window_end < len(sequence) else ""
212 return f"{leading}{before}[{symbol}]{after}{trailing}"