Coverage for src/python/ensembl/vep/sources/file/fasta/sequence.py: 98%

71 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"""FASTA-backed sequence source.""" 

15 

16from __future__ import annotations 

17 

18import logging 

19import os 

20from pathlib import Path 

21 

22from attrs import define, field 

23from attrs.setters import frozen 

24 

25from ensembl.vep.parsers.fasta import FastaParser 

26from ensembl.vep.sources.sequence_source import SequenceSource 

27 

28logger = logging.getLogger(__name__) 

29 

30UNKNOWN_REGION_LENGTH = 2**31 - 1 

31"""Length reported for a sequence region the FASTA does not carry. 

32 

33Its value does not matter: nothing annotates against these regions, it exists only so a slice can 

34be built at all. 

35""" 

36 

37 

38@define(kw_only=True, auto_attribs=True) 

39class FastaSequenceSource(SequenceSource): 

40 """Sequence source backed by a FASTA file. 

41 

42 A region the FASTA does not carry gets ``UNKNOWN_REGION_LENGTH`` rather than no length. A slice 

43 cannot be built without a sequence-region length, and the reader raises when one cannot be 

44 resolved -- so a single contig missing from the FASTA would abort the entire run. Reporting a 

45 placeholder lets those variants be read; they pair with nothing -- the transcript file has no 

46 such contig either -- and the runner writes them through unannotated. 

47 

48 Attributes: 

49 file_path (str | Path | None): FASTA file path. 

50 unknown_regions (set[str]): Regions asked for that the FASTA does not carry. 

51 """ 

52 

53 file_path: str | Path | None = field(default=None, on_setattr=frozen) 

54 adaptor: FastaParser = field(factory=FastaParser) 

55 unknown_regions: set[str] = field(factory=set, init=False) 

56 _metadata_lengths: dict[str, int] | None = field(default=None, init=False, repr=False) 

57 _warned_sequential: bool = field(default=False, init=False, repr=False) 

58 _adaptor_pid: int | None = field(default=None, init=False, repr=False) 

59 

60 def close(self) -> None: 

61 """Release FASTA metadata and derived sequence caches.""" 

62 

63 self._close_adaptor() 

64 self._metadata_lengths = None 

65 self.clear_cache() 

66 

67 def _close_adaptor(self) -> None: 

68 """Close the parser and forget that it is open for span fetches.""" 

69 

70 self.adaptor.close() 

71 self._adaptor_pid = None 

72 

73 def _fetch_sequence_chunk(self, seq_region_name: str, start: int, end: int) -> str: 

74 """Returns a FASTA sequence chunk. 

75 

76 Args: 

77 seq_region_name (str): The sequence region name. 

78 start (int): 1-based inclusive start coordinate. 

79 end (int): 1-based inclusive end coordinate. 

80 

81 Returns: 

82 str: The requested chunk or Ns if unavailable. 

83 """ 

84 

85 if self.file_path is None: 

86 return "N" * (end - start + 1) 

87 

88 # Features fetch many short spans, so the reader stays open between them rather than 

89 # re-reading the index for every exon. A handle inherited through fork shares its file 

90 # offset with the parent, so a forked worker opens its own. 

91 if self._adaptor_pid != os.getpid(): 

92 self.adaptor.open(self.file_path, mode="auto") 

93 self._adaptor_pid = os.getpid() 

94 

95 if self.adaptor.reader_mode == "sequential": 

96 self._warn_about_sequential_access() 

97 

98 if not self.adaptor.seek(seq_region_name=seq_region_name, start=start, end=end): 

99 return "N" * (end - start + 1) 

100 

101 record = self.adaptor.next() 

102 if record is None: 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true

103 return "N" * (end - start + 1) 

104 

105 return record.sequence 

106 

107 def _get_seq_region_length(self, seq_region_name: str) -> int | None: 

108 """Returns the FASTA sequence length for a region. 

109 

110 Args: 

111 seq_region_name (str): The sequence region name. 

112 

113 Query-mode metadata comes from the Rust reader's ``.fai`` index. Without an index, the 

114 Rust reader derives the same lengths from one scan that retains no sequence. 

115 

116 Returns: 

117 int | None: The sequence length, or ``UNKNOWN_REGION_LENGTH`` where the FASTA does not 

118 carry the region. 

119 """ 

120 

121 self._load_metadata_lengths() 

122 

123 assert self._metadata_lengths is not None 

124 length = self._metadata_lengths.get(seq_region_name) 

125 if length is not None: 

126 return int(length) 

127 

128 if seq_region_name not in self.unknown_regions: 

129 # Once per region, not once per variant: ClinVar has 51 such variants and would 

130 # otherwise emit 51 warnings saying the same seven things. 

131 self.unknown_regions.add(seq_region_name) 

132 logger.warning( 

133 "%s sequence region not found, variants on it will be reported unannotated", 

134 seq_region_name, 

135 ) 

136 return UNKNOWN_REGION_LENGTH 

137 

138 @property 

139 def sequence_region_names(self) -> frozenset[str]: 

140 """Return names advertised by the FASTA metadata index.""" 

141 

142 self._load_metadata_lengths() 

143 assert self._metadata_lengths is not None 

144 return frozenset(self._metadata_lengths) 

145 

146 def _load_metadata_lengths(self) -> None: 

147 """Load FASTA metadata lengths once.""" 

148 

149 if self._metadata_lengths is not None: 

150 return 

151 if self.file_path is None: 

152 metadata = self.adaptor.metadata 

153 else: 

154 with self.adaptor.open(self.file_path, mode="auto"): 

155 metadata = self.adaptor.metadata 

156 if self.adaptor.reader_mode == "sequential": 

157 self._warn_about_sequential_access() 

158 self._adaptor_pid = None 

159 self._metadata_lengths = { 

160 str(name): int(length) for name, length in metadata.get("sequence_lengths", {}).items() 

161 } 

162 

163 def _warn_about_sequential_access(self) -> None: 

164 """Warn once that an index is required for scalable random access.""" 

165 

166 if self._warned_sequential: 

167 return 

168 logger.warning( 

169 "%s has no usable FASTA index; sequential fallback is bounded but may be slow", 

170 self.file_path, 

171 ) 

172 self._warned_sequential = True