Coverage for src/python/ensembl/vep/sources/synonym.py: 100%
75 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"""Sequence-region synonyms, and resolving a name against one source's own spellings."""
16from __future__ import annotations
18import logging
19from collections.abc import Iterable, Mapping
20from pathlib import Path
22from attrs import define, field
24__all__ = ["ChromosomeSynonyms", "SequenceRegionResolver"]
26logger = logging.getLogger(__name__)
29@define(kw_only=True, auto_attribs=True)
30class ChromosomeSynonyms:
31 """Sequence-region names that name the same region, held once for the whole run.
33 Perl VEP keeps one synonym map per run and asks it for every source (``BaseVEP::
34 chromosome_synonyms``); a name is not a synonym *of a source*, it is a synonym full stop, and
35 which spelling a given source wants is decided by that source's own valid names. Keeping one
36 map is what lets ``22 -> NC_000022.11`` serve the FASTA and the transcript file at once, in
37 whichever direction each of them needs.
39 Attributes:
40 by_name (Mapping[str, frozenset[str]]): Every name, mapped to the other names for it.
41 """
43 by_name: Mapping[str, frozenset[str]] = field(factory=dict)
45 @classmethod
46 def from_file(cls, path: Path | str) -> ChromosomeSynonyms:
47 """Read a synonyms file in Perl VEP's format.
49 Each line lists whitespace-separated names for one region. The first name is the reference
50 spelling and every later name is a synonym of it, recorded in both directions -- as Perl
51 does, so two synonyms of one reference name are not made synonyms of each other.
53 Args:
54 path (Path | str): The file to read.
56 Returns:
57 ChromosomeSynonyms: The map the file describes.
59 Raises:
60 OSError: If the file cannot be read. Allowed to propagate: its message names the path,
61 and a synonyms file the caller asked for and that is not there is not a run to
62 continue silently.
63 """
65 pairs: dict[str, set[str]] = {}
66 with open(path, encoding="utf-8") as synonyms_file:
67 for line in synonyms_file:
68 names = line.split()
69 if len(names) < 2:
70 continue
71 if len(names) > 2:
72 logger.warning(
73 f"Only two columns are expected in the synonyms file, {path}. "
74 "Other columns will be ignored."
75 )
76 reference_name, synonym = names[0], names[1]
77 pairs.setdefault(reference_name, set()).add(synonym)
78 pairs.setdefault(synonym, set()).add(reference_name)
79 logger.info("read %d sequence-region synonyms from %s", len(pairs), path)
80 return cls(by_name={name: frozenset(synonyms) for name, synonyms in pairs.items()})
82 def synonyms_of(self, name: str) -> frozenset[str]:
83 """Return the other names for a region.
85 Args:
86 name (str): The name to look up.
88 Returns:
89 frozenset[str]: Its synonyms, empty when the map has none.
90 """
92 return self.by_name.get(name, frozenset())
95@define(kw_only=True, auto_attribs=True)
96class SequenceRegionResolver:
97 """Resolve uploaded sequence-region names against one source.
99 Perl's ``BaseVEP::get_source_chr_name`` in our shape: an exact source name wins, then a synonym
100 the source declares, then the conventional case-insensitive ``chr`` prefix adjustment, and an
101 unresolved name keeps its uploaded spelling. Resolution is memoised per instance, which is why
102 each source gets its own resolver over the shared synonym map.
104 Attributes:
105 source_names (frozenset[str]): Names this source declares.
106 synonyms (ChromosomeSynonyms): The run's synonym map, shared by every source.
107 """
109 source_names: frozenset[str]
110 synonyms: ChromosomeSynonyms = field(factory=ChromosomeSynonyms)
111 _resolved: dict[str, str] = field(factory=dict, init=False, repr=False)
113 def __attrs_post_init__(self) -> None:
114 """Reject source names that cannot be matched case-insensitively without ambiguity."""
116 folded_names: dict[str, str] = {}
117 for source_name in self.source_names:
118 folded_name = source_name.casefold()
119 previous_name = folded_names.get(folded_name)
120 if previous_name is not None and previous_name != source_name:
121 raise ValueError(f"source names {previous_name!r} and {source_name!r} differ only by case")
122 folded_names[folded_name] = source_name
124 def resolve(self, uploaded_name: str) -> str:
125 """Return the source sequence-region name for an uploaded name."""
127 cached = self._resolved.get(uploaded_name)
128 if cached is not None:
129 return cached
131 resolved = self._resolve(uploaded_name)
132 self._resolved[uploaded_name] = resolved
133 return resolved
135 def _resolve(self, uploaded_name: str) -> str:
136 """Resolve one name without consulting the per-instance cache."""
138 if uploaded_name in self.source_names:
139 return uploaded_name
140 synonym = self._declared_synonym(self.synonyms.synonyms_of(uploaded_name))
141 if synonym is not None:
142 return synonym
143 chr_adjusted = self._chr_adjusted_name(uploaded_name)
144 if chr_adjusted is not None:
145 return chr_adjusted
146 return uploaded_name
148 def _declared_synonym(self, synonyms: Iterable[str]) -> str | None:
149 """Return the synonym this source declares, lowest name first when several do.
151 Perl walks an unordered hash here and takes whichever synonym comes out first. Sorting
152 makes the same input give the same answer on every run, which output diffs depend on.
153 """
155 for synonym in sorted(synonyms):
156 if synonym in self.source_names:
157 return synonym
158 return None
160 def _chr_adjusted_name(self, uploaded_name: str) -> str | None:
161 """Return a valid case-insensitive ``chr`` prefix adjustment."""
163 if uploaded_name[:3].lower() == "chr":
164 candidate = uploaded_name[3:]
165 return self._source_name(candidate)
166 return self._source_name(f"chr{uploaded_name}")
168 def _source_name(self, candidate: str) -> str | None:
169 """Return the valid source spelling of a candidate name."""
171 if candidate in self.source_names:
172 return candidate
173 candidate_folded = candidate.casefold()
174 for source_name in self.source_names:
175 if source_name.casefold() == candidate_folded:
176 return source_name
177 return None