Coverage for src/python/ensembl/vep/corpus/loaded/files.py: 91%

79 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"""Load a corpus from FASTA, GFF3 or GTF, and VCF files.""" 

15 

16from __future__ import annotations 

17 

18from pathlib import Path 

19 

20from ensembl.vep.caches import WeakSliceCache 

21from ensembl.vep.corpus.loaded.base import LoadedCorpus, collect_sequence_regions 

22from ensembl.vep.corpus.overlap import build_transcript_overlaps 

23from ensembl.vep.corpus.registry import register_corpus 

24from ensembl.vep.corpus.spec import CorpusSpec 

25from ensembl.vep.models.sequence import Slice 

26from ensembl.vep.models.variation import Variation, VariationAllele 

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

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

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

30from ensembl.vep.sources.file.vcf.variation import VCFVariationSource 

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

32 

33__all__ = ["load_file_corpus"] 

34 

35 

36def _required_path(specification: CorpusSpec, name: str) -> Path: 

37 """Return a required path parameter.""" 

38 value = specification.parameter(name) 

39 if not isinstance(value, str) or not value: 39 ↛ 40line 39 didn't jump to line 40 because the condition on line 39 was never true

40 raise ValueError(f"{specification.kind} requires a non-empty {name!r} path") 

41 path = Path(value) 

42 if not path.is_file(): 

43 raise FileNotFoundError(path) 

44 return path 

45 

46 

47def _named_variants(variations: list[Variation]) -> tuple[tuple[str, VariationAllele], ...]: 

48 """Name every loaded allele, by the rule every other reader of a file names them by. 

49 

50 Sharing the rule is the point: a name taken from a corpus has to select the same allele when 

51 ``vep explain`` reads the same VCF. All this adds is collisions, which a corpus cannot have -- 

52 it files its overlaps under ``(name, feature)`` -- and which a file produces by repeating an 

53 identifier across records. 

54 """ 

55 named_variants = [] 

56 used_names: set[str] = set() 

57 for variation in variations: 

58 for allele in variation.variation_alleles: 

59 name = allele.display_name 

60 candidate = name 

61 suffix = 2 

62 while candidate in used_names: 

63 candidate = f"{name}:{suffix}" 

64 suffix += 1 

65 name = candidate 

66 used_names.add(name) 

67 named_variants.append((name, allele)) 

68 return tuple(named_variants) 

69 

70 

71def _share_sequence_regions(variations: list[Variation], canonical_by_name: dict[str, Slice]) -> None: 

72 """Attach loaded variations to the transcript source's sequence-region objects.""" 

73 for variation in variations: 

74 sequence_region = variation.slice 

75 if sequence_region is None: 75 ↛ 76line 75 didn't jump to line 76 because the condition on line 75 was never true

76 continue 

77 canonical = canonical_by_name.setdefault(sequence_region.seq_region_name, sequence_region) 

78 variation.slice = canonical 

79 for allele in variation.variation_alleles: 

80 allele.slice = canonical 

81 

82 

83@register_corpus("loaded.files") 

84def load_file_corpus(specification: CorpusSpec) -> LoadedCorpus: 

85 """Load a corpus from FASTA, VCF, and GFF3 or GTF files. 

86 

87 ``specification`` must provide ``fasta`` and ``vcf`` parameters plus exactly one of ``gff3`` 

88 or ``gtf``. Its optional ``window`` parameter controls overlap construction. 

89 

90 Args: 

91 specification (CorpusSpec): File paths and loader parameters. 

92 

93 Returns: 

94 LoadedCorpus: Materialised corpus owning its sequence source. 

95 

96 Raises: 

97 FileNotFoundError: If a required input path does not exist. 

98 TypeError: If a path or overlap window has an invalid type. 

99 ValueError: If the transcript format selection or loaded memberships are invalid. 

100 """ 

101 fasta_path = _required_path(specification, "fasta") 

102 vcf_path = _required_path(specification, "vcf") 

103 gff3_value = specification.parameter("gff3") 

104 gtf_value = specification.parameter("gtf") 

105 if bool(gff3_value) == bool(gtf_value): 

106 raise ValueError("loaded.files requires exactly one of 'gff3' or 'gtf'") 

107 transcript_path = _required_path(specification, "gff3" if gff3_value else "gtf") 

108 

109 sequence_source = FastaSequenceSource(file_path=fasta_path) 

110 try: 

111 slice_cache = WeakSliceCache() 

112 synonyms = ChromosomeSynonyms() 

113 reference_names = sequence_source.sequence_region_names 

114 reference_region_resolver = SequenceRegionResolver( 

115 source_names=reference_names, 

116 synonyms=synonyms, 

117 ) 

118 transcript_source_class = GFF3TranscriptSource if gff3_value else GTFTranscriptSource 

119 transcript_source = transcript_source_class( 

120 file_path=str(transcript_path), 

121 sequence_source=sequence_source, 

122 slice_cache=slice_cache, 

123 reference_region_resolver=reference_region_resolver, 

124 ) 

125 variation_source = VCFVariationSource( 

126 file_path=str(vcf_path), 

127 sequence_source=sequence_source, 

128 slice_cache=slice_cache, 

129 sequence_region_resolver=reference_region_resolver, 

130 ) 

131 transcripts = tuple(transcript_source.iter_all_features()) 

132 variations = list(variation_source.iter_all_features()) 

133 canonical_by_name = { 

134 transcript.slice.seq_region_name: transcript.slice 

135 for transcript in transcripts 

136 if transcript.slice is not None 

137 } 

138 _share_sequence_regions(variations, canonical_by_name) 

139 named_variants = _named_variants(variations) 

140 window = specification.parameter("window", 5000) 

141 if not isinstance(window, int) or isinstance(window, bool): 141 ↛ 142line 141 didn't jump to line 142 because the condition on line 141 was never true

142 raise TypeError("loaded corpus overlap window must be an integer") 

143 named_overlaps = build_transcript_overlaps(named_variants, transcripts, window=window) 

144 sequence_regions = collect_sequence_regions( 

145 [*transcripts, *(allele for _name, allele in named_variants)] 

146 ) 

147 return LoadedCorpus( 

148 spec=specification, 

149 sequence_regions=sequence_regions, 

150 named_variants=named_variants, 

151 transcripts=transcripts, 

152 named_overlaps=named_overlaps, 

153 resources=(sequence_source,), 

154 ) 

155 except Exception: 

156 sequence_source.close() 

157 raise