Coverage for src/python/ensembl/vep/sources/file/file_feature_source.py: 98%
53 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"""The file-backed feature source contract."""
16from __future__ import annotations
18import logging
19from collections.abc import Iterator
20from typing import Generic, TypeVar
21from attrs import define, field
23from ensembl.vep.common import SourceType
24from ensembl.vep.common.methods import format_region_string
25from ensembl.vep.models import Feature
26from ensembl.vep.parsers import Parser
27from ensembl.vep.sources.feature_source import FeatureSource
29P = TypeVar("P", bound=Parser)
30R = TypeVar("R")
31F = TypeVar("F", bound=Feature)
32logger = logging.getLogger(__name__)
35@define(kw_only=True, auto_attribs=True)
36class FileFeatureSource(FeatureSource[R, F], Generic[P, R, F]):
37 """Feature source backed by a parser-readable file.
39 Attributes:
40 file_path (str): Path to the feature file.
41 adaptor (P): Parser for the file's record type.
42 source_type (SourceType): File source marker.
43 """
45 file_path: str
46 adaptor: P
47 source_type: SourceType = field(default=SourceType.FILE, init=False)
49 def get_all_records(self) -> list[R]:
50 """Return every unconverted record in the source file.
52 Returns:
53 list[R]: Every record in the file.
55 Raises:
56 NotImplementedError: If the adaptor cannot parse a whole file at once. Re-raised with
57 the adaptor named, which the bare error from the parser does not say.
58 FileNotFoundError: If the file does not exist. Allowed to propagate: its message
59 already names the path.
61 A library reports what went wrong and lets its caller decide what to do about it. These
62 both used to call ``sys.exit(1)``, which ended the process from underneath any caller --
63 including a test, and including a runner that had a better answer than dying.
64 """
66 try:
67 return self.adaptor.parse_file(self.file_path)
68 except NotImplementedError as unsupported:
69 raise NotImplementedError(
70 f"{type(self.adaptor).__name__} does not support parse_file"
71 ) from unsupported
73 def iter_all_records(self) -> Iterator[R]:
74 """Yield every unconverted record in the source file."""
76 with self.adaptor.open(self.file_path, mode="sequential") as adaptor:
77 while (record := adaptor.next()) is not None:
78 yield record
80 def get_records_by_region(
81 self,
82 region: str | None = None,
83 *,
84 seq_region_name: str | None = None,
85 start: int | None = None,
86 end: int | None = None,
87 **kwargs: object,
88 ) -> list[R]:
89 """Return unconverted records from an indexed region query.
91 Args:
92 region (str | None): The region (e.g., "chr1:1000-2000") to read.
93 seq_region_name (str | None): The name of the sequence region (e.g., "chr1").
94 start (int | None): The start position of the region.
95 end (int | None): The end position of the region.
96 **kwargs (object): Unused here; a format whose query takes more accepts it.
98 Returns:
99 list[R]: The records the query reads, empty when the region is unreadable.
100 """
102 del kwargs
103 try:
104 query_region = format_region_string(region, seq_region_name=seq_region_name, start=start, end=end)
105 except ValueError:
106 logger.debug("Cannot parse region: %s %s:%s-%s", region, seq_region_name, start, end)
107 return []
109 with self.adaptor.open(self.file_path, mode="query") as adaptor:
110 if not adaptor.seek(query_region):
111 return []
112 return adaptor.records(limit=None)
114 def iter_records_by_region(
115 self,
116 region: str | None = None,
117 *,
118 seq_region_name: str | None = None,
119 start: int | None = None,
120 end: int | None = None,
121 **kwargs: object,
122 ) -> Iterator[R]:
123 """Yield unconverted records from an indexed region query.
125 Args:
126 region (str | None): The region (e.g., "chr1:1000-2000") to read.
127 seq_region_name (str | None): The name of the sequence region (e.g., "chr1").
128 start (int | None): The start position of the region.
129 end (int | None): The end position of the region.
130 **kwargs (object): Unused here; a format whose query takes more accepts it.
132 Returns:
133 Iterator[R]: The records the query reads, in file order.
134 """
136 del kwargs
137 try:
138 query_region = format_region_string(region, seq_region_name=seq_region_name, start=start, end=end)
139 except ValueError:
140 logger.debug("Cannot parse region: %s %s:%s-%s", region, seq_region_name, start, end)
141 return
143 with self.adaptor.open(self.file_path, mode="query") as adaptor:
144 if not adaptor.seek(query_region):
145 return
146 while (record := adaptor.next()) is not None:
147 yield record
149 def close(self) -> None:
150 """Release the attached sequence source, if any.
152 ``FeatureSource`` owns the ``sequence_source`` field and ``__exit__`` calls ``close()``, but
153 nothing in the chain ever released it -- so a source opened as a context manager leaked its
154 sequence handle. Closing it here is what the field's ownership already implied.
155 """
157 if self.sequence_source is not None: 157 ↛ exitline 157 didn't return from function 'close' because the condition on line 157 was always true
158 self.sequence_source.close()