Coverage for src/python/ensembl/vep/sources/build.py: 98%

80 statements  

« 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"""Source construction from run configuration. 

15 

16Two kinds of source, named apart on purpose: the **input source** holds the variants being 

17annotated, and the **annotation sources** hold what they are annotated against. Perl VEP draws the 

18same line -- its input is a Parser and its annotation sources come from 

19``AnnotationSourceAdaptor::get_all``, which reads the configuration and returns whichever set of 

20sources it names (a cache, a database, a GFF3/GTF file, custom files). 

21 

22These are functions rather than a class holding the set: a run's sources are built once, wired to 

23each other, and then used directly by whoever asked for them. The one thing they must share is the 

24reference sequence and the synonym map, which is why those are built first and passed in. 

25 

26There is one builder per kind of annotation source rather than one call returning the whole set. 

27Each annotation track builds the source it annotates against, so nothing has to pick its own source 

28out of a list of everything configured. 

29 

30Which input format to read is decided here, by name, against the closed set in 

31``common/constants.py``. One conditional in one place, rather than a registry each source 

32registers with: the configuration package offers the same names as ``--format`` choices and cannot 

33import the sources, which import it. 

34""" 

35 

36from __future__ import annotations 

37 

38import logging 

39from pathlib import Path 

40 

41from ensembl.vep.common.constants import COMPRESSION_SUFFIXES, INPUT_FORMAT_EXTENSIONS 

42from ensembl.vep.config.sections.common.source import SourceConfig 

43from ensembl.vep.sources.file.fasta.sequence import FastaSequenceSource 

44from ensembl.vep.sources.file.gff3.transcript import GFF3TranscriptSource 

45from ensembl.vep.sources.file.gtf.transcript import GTFTranscriptSource 

46from ensembl.vep.sources.file.vcf.variation import PicklableVCFVariationSource 

47from ensembl.vep.sources.sequence_source import SequenceSource 

48from ensembl.vep.sources.synonym import ChromosomeSynonyms, SequenceRegionResolver 

49 

50__all__ = [ 

51 "DEFAULT_INPUT_FORMAT", 

52 "InputSource", 

53 "TranscriptSource", 

54 "build_chromosome_synonyms", 

55 "build_input_source", 

56 "build_sequence_source", 

57 "build_transcript_source", 

58 "detect_input_format", 

59] 

60 

61logger = logging.getLogger(__name__) 

62 

63DEFAULT_INPUT_FORMAT = "vcf" 

64"""What an input file whose name names no format is read as.""" 

65 

66TranscriptSource = GFF3TranscriptSource | GTFTranscriptSource 

67"""The file-backed transcript annotation sources.""" 

68 

69InputSource = PicklableVCFVariationSource 

70"""The sources a run can read its variants from. 

71 

72What a run asks of one: ``iter_all_records`` and ``records_to_features`` either side of a process 

73boundary, ``region_of`` and ``record_columns`` to place and echo a record, and 

74``header_lines`` and ``record_count`` for what output and progress need before reading.""" 

75 

76 

77def build_chromosome_synonyms(config: SourceConfig) -> ChromosomeSynonyms: 

78 """Return the run's sequence-region synonyms. 

79 

80 Args: 

81 config (SourceConfig): The configured sources. 

82 

83 Returns: 

84 ChromosomeSynonyms: The map ``--synonyms`` names, or an empty one when it was not given. 

85 """ 

86 

87 if config.synonyms is None: 

88 return ChromosomeSynonyms() 

89 return ChromosomeSynonyms.from_file(config.synonyms) 

90 

91 

92def build_sequence_source(config: SourceConfig) -> FastaSequenceSource: 

93 """Return the reference sequence source every other source shares. 

94 

95 Args: 

96 config (SourceConfig): The configured sources. 

97 

98 Returns: 

99 FastaSequenceSource: The reference source. 

100 

101 Raises: 

102 ValueError: If no FASTA was configured. 

103 """ 

104 

105 if config.fasta is None: 

106 raise ValueError("annotating a variant file needs a reference: give --fasta") 

107 return FastaSequenceSource(file_path=config.fasta) 

108 

109 

110def _reference_names(sequence_source: SequenceSource | None) -> frozenset[str]: 

111 """Return the names the reference sequence declares, or none without one. 

112 

113 The reference and not the input, because this is the spelling every model slice is built in, 

114 and a slice is what sequence is fetched with: the sequence source is asked for a region by the 

115 name it declares, with nothing mapping the name on its way in. Every other side maps into or 

116 out of it -- a GXF record's own name is resolved in, a region query back out -- and the input's 

117 own spelling is kept on the variation's ``uploaded_locus``, which is what output reports. 

118 

119 Asked of the source rather than of a FASTA: which kind of reference a run has is 

120 ``build_sequence_source``'s business, and a cache or a database answers this as well as a 

121 file does. A source that lists no regions, and one whose index cannot be read, both leave 

122 every uploaded name resolving to itself. 

123 """ 

124 

125 if sequence_source is None: 

126 return frozenset() 

127 try: 

128 return sequence_source.sequence_region_names 

129 except OSError: 

130 return frozenset() 

131 

132 

133def _region_resolver( 

134 sequence_source: SequenceSource | None, 

135 synonyms: ChromosomeSynonyms, 

136 source_names: frozenset[str] | None = None, 

137) -> SequenceRegionResolver: 

138 """Return a resolver naming regions the way one side of a run spells them. 

139 

140 Args: 

141 sequence_source (SequenceSource | None): The shared reference source, or None for a 

142 caller that can work without reference sequence -- ``vep explain`` allows it, a run 

143 does not -- which leaves the resolver with no names. 

144 synonyms (ChromosomeSynonyms): The run's sequence-region synonyms. 

145 source_names (frozenset[str] | None): The names to resolve into. None asks for the 

146 reference's own names, which is what a record read from a file is given. 

147 

148 Returns: 

149 SequenceRegionResolver: The resolver for those names. 

150 """ 

151 

152 names = _reference_names(sequence_source) if source_names is None else source_names 

153 return SequenceRegionResolver(source_names=names, synonyms=synonyms) 

154 

155 

156def _format_for_path(input_file: Path | str) -> str | None: 

157 """Return the format owning an input path's extension, or None when no format claims it.""" 

158 

159 name = Path(input_file).name.lower() 

160 for suffix in COMPRESSION_SUFFIXES: 

161 if name.endswith(suffix): 

162 name = name[: -len(suffix)] 

163 break 

164 for format_name, extensions in sorted(INPUT_FORMAT_EXTENSIONS.items()): 

165 if any(name.endswith(extension) for extension in extensions): 

166 return format_name 

167 return None 

168 

169 

170def detect_input_format(input_file: Path | str, configured_format: str | None = None) -> str: 

171 """Return the format an input file is read as. 

172 

173 A configured format wins, since only the caller knows what an unqualified file holds. An 

174 unrecognised name is refused rather than guessed at, but an unrecognised *extension* falls 

175 back to ``DEFAULT_INPUT_FORMAT``: VEP has always read ``--input_file`` of any name as VCF, and 

176 ``--format`` is how another format is named. 

177 

178 Args: 

179 input_file (Path | str): The configured input file. 

180 configured_format (str | None): What ``--format`` named, or None. 

181 

182 Returns: 

183 str: A registered input format name. 

184 

185 Raises: 

186 ValueError: If a configured format names no registered input source. 

187 """ 

188 

189 if configured_format is not None: 

190 name = configured_format.strip().lower() 

191 if name not in INPUT_FORMAT_EXTENSIONS: 

192 supported = ", ".join(sorted(INPUT_FORMAT_EXTENSIONS)) or "<none>" 

193 raise ValueError(f"no reader for input format {configured_format!r} yet; supported: {supported}") 

194 return name 

195 

196 detected = _format_for_path(input_file) 

197 if detected is not None: 

198 return detected 

199 logger.debug("%s names no input format; reading it as %s", input_file, DEFAULT_INPUT_FORMAT) 

200 return DEFAULT_INPUT_FORMAT 

201 

202 

203def build_input_source( 

204 config: SourceConfig, 

205 *, 

206 sequence_source: SequenceSource | None, 

207 synonyms: ChromosomeSynonyms, 

208) -> InputSource: 

209 """Return the source holding the variants being annotated. 

210 

211 Args: 

212 config (SourceConfig): The configured sources. 

213 sequence_source (SequenceSource | None): The shared reference source, or None. 

214 synonyms (ChromosomeSynonyms): The run's sequence-region synonyms. 

215 

216 Returns: 

217 InputSource: The input source the configured format reads with. 

218 

219 Raises: 

220 ValueError: If no input file was configured, or its format has no reader. 

221 """ 

222 

223 if config.input_file is None: 

224 raise ValueError("annotating needs variants: give --input_file") 

225 

226 source_format = detect_input_format(config.input_file, config.format) 

227 # source_format can't be anything other than vcf at the moment 

228 # keep as a guard 

229 if source_format != "vcf": 229 ↛ 230line 229 didn't jump to line 230 because the condition on line 229 was never true

230 raise ValueError(f"no reader for input format {source_format!r} yet") 

231 return PicklableVCFVariationSource( 

232 file_path=str(config.input_file), 

233 sequence_source=sequence_source, 

234 sequence_region_resolver=_region_resolver(sequence_source, synonyms), 

235 ) 

236 

237 

238def build_transcript_source( 

239 config: SourceConfig, 

240 *, 

241 sequence_source: SequenceSource | None, 

242 synonyms: ChromosomeSynonyms, 

243) -> TranscriptSource: 

244 """Return the transcript source a run annotates against, wired to resolve names both ways. 

245 

246 Args: 

247 config (SourceConfig): The configured sources. 

248 sequence_source (SequenceSource | None): The shared reference source. None is for a 

249 caller that can work without reference sequence -- ``vep explain`` allows it, a run 

250 does not -- and leaves the source with no sequence and no reference names. 

251 synonyms (ChromosomeSynonyms): The run's sequence-region synonyms. 

252 

253 Returns: 

254 TranscriptSource: The transcript source. 

255 

256 Raises: 

257 ValueError: If the transcript files are ambiguous or absent. 

258 NotImplementedError: If the configured transcript provider has no reader yet. 

259 """ 

260 

261 if config.cache: 

262 raise NotImplementedError("annotating from a VEP cache (--cache, --dir_cache) is not implemented yet") 

263 if config.database: 

264 raise NotImplementedError("annotating from an Ensembl database is not implemented yet") 

265 if config.gff is not None and config.gtf is not None: 

266 raise ValueError("give --gff or --gtf, not both") 

267 if config.gff is None and config.gtf is None: 

268 raise ValueError("annotating a variant file needs transcripts: give --gff or --gtf") 

269 

270 # Two directions, one map: records read from the file get reference names, and a region query 

271 # built from a reference name goes out in the file's own spelling. 

272 reference_region_resolver = _region_resolver(sequence_source, synonyms) 

273 source: TranscriptSource 

274 if config.gff is not None: 

275 source = GFF3TranscriptSource( 

276 file_path=str(config.gff), 

277 sequence_source=sequence_source, 

278 reference_region_resolver=reference_region_resolver, 

279 ) 

280 else: 

281 assert config.gtf is not None 

282 source = GTFTranscriptSource( 

283 file_path=str(config.gtf), 

284 sequence_source=sequence_source, 

285 reference_region_resolver=reference_region_resolver, 

286 ) 

287 source.source_region_resolver = _region_resolver(sequence_source, synonyms, source.sequence_region_names) 

288 return source