Coverage for src/python/ensembl/vep/sources/file/gxf/transcript.py: 98%

376 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"""Shared GXF-based transcript source. 

15 

16This module contains the common transcript-building workflow used by both file 

17formats: 

18 

19* buffer records from the parser in streaming order, 

20* group the buffered records into transcript-sized blocks, 

21* build Transcript, Gene, Exon, and Translation objects (introns are derived lazily by 

22 ``Transcript`` itself), and 

23* reuse Slice and Gene instances across records that share the same region. 

24 

25Only the parser-specific record identity and parent resolution rules are left 

26to the concrete GFF3 and GTF adapters. 

27""" 

28 

29from __future__ import annotations 

30 

31import logging 

32import os 

33from abc import ABC, abstractmethod 

34from collections import defaultdict 

35from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence 

36from typing import ClassVar, Generic, Protocol, TypeVar, cast 

37 

38from attrs import define, evolve, field 

39 

40from ensembl.vep.caches.feature_pool import FeaturePool 

41from ensembl.vep.common import ( 

42 CoordSystemLevel, 

43 ExonPhase, 

44 STRAND_SYMBOL_TO_ENUM, 

45 GFF_TO_ENSEMBL_PHASE, 

46 Strand, 

47 format_region_string, 

48 parse_region_string, 

49) 

50from ensembl.vep.models.genic import Exon, Gene, Transcript, Translation 

51from ensembl.vep.models.sequence import CoordSystem, Slice 

52from ensembl.vep.parsers import Parser 

53from ensembl.vep.sources.file.file_feature_source import FileFeatureSource 

54from ensembl.vep.sources.synonym import SequenceRegionResolver 

55 

56logger = logging.getLogger(__name__) 

57 

58_CHROMOSOME_COORD_SYSTEM = CoordSystem(name="chromosome", level=CoordSystemLevel.CHROMOSOME, default=True) 

59_PLACEHOLDER_SEQ_REGION_END = 2**31 - 1 

60_ORDERED_FILE_ASSUMPTION_MESSAGE = ( 

61 "GFF3/GTF streaming iteration assumes records are grouped by gene. A gene record may precede " 

62 "several transcript records and their exon/CDS children. Files that revisit a gene after " 

63 "starting another gene require an index for complete assembly." 

64) 

65 

66P = TypeVar("P", bound=Parser) 

67 

68 

69class GXFRecord(Protocol): 

70 """Minimal parser record interface shared by GFF3 and GTF records. 

71 

72 Attributes: 

73 feature_type (str): Raw feature type reported by the parser. 

74 seqid (str): Sequence-region name for the record. 

75 start (int): Genomic start position, 1-based inclusive. 

76 end (int): Genomic end position, 1-based inclusive. 

77 strand_symbol (str): Strand symbol from the parser record. 

78 phase_value (str | None): Phase string for coding features, if present. 

79 attributes (dict[str, tuple[str, ...]]): Parsed key/value attributes from the record. 

80 """ 

81 

82 feature_type: str 

83 seqid: str 

84 start: int 

85 end: int 

86 strand_symbol: str 

87 phase_value: int | None 

88 attributes: dict[str, tuple[str, ...]] 

89 

90 def first_attribute(self, key: str) -> str | None: 

91 """Return the first attribute value for a key, or None when absent.""" 

92 

93 def attribute_values(self, key: str) -> list[str]: 

94 """Return every attribute value for a key, empty when absent.""" 

95 

96 

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

98class _GXFTranscriptGroup: 

99 """Grouped parser records describing one transcript. 

100 

101 ``transcript_id`` and ``gene_id`` are resolved once, while grouping, from the same 

102 ``get_record_id``/``get_parent_ids`` calls that route records into this group in the first 

103 place. Carrying them here is what lets the builder stop recomputing them per transcript. 

104 

105 Attributes: 

106 transcript_id (str): Stable identifier of the transcript record. 

107 gene_id (str | None): Parent gene identifier declared by the transcript record, if any -- 

108 not necessarily the id of ``gene_record``, which may be absent even when this is set. 

109 transcript_record (GXFRecord): Primary transcript record for the group. 

110 gene_record (GXFRecord | None): Associated gene record, if one was present in the input. 

111 exon_records (list[GXFRecord]): Exon records attached to the transcript. 

112 cds_records (list[GXFRecord]): Coding records attached to the transcript. 

113 """ 

114 

115 transcript_id: str 

116 gene_id: str | None 

117 transcript_record: GXFRecord 

118 gene_record: GXFRecord | None 

119 exon_records: list[GXFRecord] 

120 cds_records: list[GXFRecord] 

121 

122 

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

124class GXFTranscriptSource(FileFeatureSource[P, GXFRecord, Transcript], ABC, Generic[P]): 

125 """Transcript source backed by GFF3 or GTF file. 

126 

127 Attributes: 

128 gene_feature_types (frozenset[str]): Lower-cased feature types that identify a gene record. 

129 transcript_feature_types (frozenset[str]): Lower-cased feature types that identify a 

130 transcript record. 

131 exon_feature_types (frozenset[str]): Lower-cased feature types that identify an exon record. 

132 coding_feature_types (frozenset[str]): Lower-cased feature types that contribute to the 

133 transcript translation. 

134 reference_region_resolver (SequenceRegionResolver | None): Resolve raw GXF names to the 

135 shared reference names used by model slices. 

136 source_region_resolver (SequenceRegionResolver | None): Resolve model slice names to names 

137 accepted by indexed GXF queries. 

138 transcript_pool (FeaturePool[Transcript] | None): Cross-payload cache of built transcripts, 

139 assigned by the owning worker; ``None`` disables reuse. 

140 """ 

141 

142 gene_feature_types: ClassVar[frozenset[str]] = frozenset({"gene"}) 

143 transcript_feature_types: ClassVar[frozenset[str]] = frozenset({"transcript"}) 

144 exon_feature_types: ClassVar[frozenset[str]] = frozenset({"exon"}) 

145 coding_feature_types: ClassVar[frozenset[str]] = frozenset({"cds"}) 

146 adaptor: P 

147 reference_region_resolver: SequenceRegionResolver | None = field(default=None) 

148 source_region_resolver: SequenceRegionResolver | None = field(default=None) 

149 transcript_pool: FeaturePool[Transcript] | None = field(default=None) 

150 _query_parser: P | None = field(default=None, init=False, repr=False) 

151 _query_parser_pid: int | None = field(default=None, init=False, repr=False) 

152 _pool_poisoned: bool = field(default=False, init=False, repr=False) 

153 

154 @property 

155 def transcript_pool_poisoned(self) -> bool: 

156 """Return whether a repeated transcript id has disabled pooling for this source.""" 

157 return self._pool_poisoned 

158 

159 @property 

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

161 """Return the tabix index's reference names together with ``##sequence-region`` names. 

162 

163 A header can declare a contig that has no rows, and so no index entry. 

164 """ 

165 try: 

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

167 index_names = frozenset(adaptor.index_sequence_names) 

168 headers = adaptor.metadata.get("header", ()) 

169 except OSError: 

170 return frozenset() 

171 

172 header_names: set[str] = set() 

173 if isinstance(headers, (list, tuple)): 173 ↛ 178line 173 didn't jump to line 178 because the condition on line 173 was always true

174 for header in headers: 

175 fields = str(header).split() 

176 if len(fields) >= 4 and fields[0] == "##sequence-region": 

177 header_names.add(fields[1]) 

178 return index_names | header_names 

179 

180 def get_records_by_region( 

181 self, 

182 region: str | None = None, 

183 *, 

184 seq_region_name: str | None = None, 

185 start: int | None = None, 

186 end: int | None = None, 

187 **kwargs: object, 

188 ) -> list[GXFRecord]: 

189 """Return the records an indexed query over one region reads, assembling nothing. 

190 

191 Unlike the file-backed default this resolves the region into the file's own spelling, and 

192 falls back to ``chr`` prefix variants when the name the index declares finds nothing -- 

193 which happens for an unindexed GXF with no ``##sequence-region`` directive. 

194 

195 Args: 

196 region (str | None): The region (e.g., "chr1:1000-2000") to read. 

197 seq_region_name (str | None): The name of the sequence region, in reference spelling. 

198 start (int | None): Inclusive query start. 

199 end (int | None): Inclusive query end. 

200 **kwargs (object): ``feature_types``, a frozenset of record types to keep. Matching 

201 happens on the Rust side, before a non-matching line is parsed into a record. 

202 

203 Returns: 

204 list[GXFRecord]: The records the query read, empty when the region is unreadable. 

205 """ 

206 feature_types = cast("frozenset[str] | None", kwargs.pop("feature_types", None)) 

207 if kwargs: 

208 raise TypeError(f"unexpected query options: {', '.join(sorted(kwargs))}") 

209 try: 

210 query_region = format_region_string(region, seq_region_name=seq_region_name, start=start, end=end) 

211 region_name, region_start, region_end = parse_region_string(query_region) 

212 except ValueError: 

213 logger.debug("Cannot parse region: %s %s:%s-%s", region, seq_region_name, start, end) 

214 return [] 

215 return self._records_for_region(region_name, region_start, region_end, feature_types=feature_types) 

216 

217 def get_features_by_region( 

218 self, 

219 region: str | None = None, 

220 *, 

221 seq_region_name: str | None = None, 

222 start: int | None = None, 

223 end: int | None = None, 

224 ) -> list[Transcript]: 

225 """Return complete transcripts whose spans meet one query region. 

226 

227 Two queries, because one is not enough: stage 1 finds the transcript rows overlapping the 

228 region, stage 2 queries the full span of each candidate not already pooled, so exons and 

229 coding records outside the region are kept. Results are in stage-1 (file) order whether a 

230 transcript came from the pool or was just built, which is what fixes CSQ order. 

231 

232 A region without coordinates queries the whole sequence region, and so assembles every 

233 transcript on it. 

234 """ 

235 try: 

236 query_region = format_region_string(region, seq_region_name=seq_region_name, start=start, end=end) 

237 region_name, region_start, region_end = parse_region_string(query_region) 

238 except ValueError: 

239 logger.debug("Cannot parse region: %s %s:%s-%s", region, seq_region_name, start, end) 

240 return [] 

241 

242 records = self._records_for_region( 

243 region_name, region_start, region_end, feature_types=self.transcript_feature_types 

244 ) # stage 1: the transcript rows meeting the region, before their spans are known 

245 candidates: dict[str, tuple[int, int]] = {} 

246 has_duplicate_candidate = False 

247 for record in records: 

248 transcript_id = self.get_record_id(record) 

249 if transcript_id is None: 

250 continue 

251 previous_span = candidates.get(transcript_id) 

252 span = (record.start, record.end) 

253 if previous_span is not None and previous_span != span: 

254 has_duplicate_candidate = True 

255 self._disable_pool_for_duplicate_id(transcript_id) 

256 candidates[transcript_id] = span 

257 if not candidates: 

258 return [] 

259 

260 pool = None if self._pool_poisoned else self.transcript_pool 

261 if pool is None or pool.max_bytes <= 0 or has_duplicate_candidate: 

262 return self._build_candidates(region_name, candidates) 

263 return self._build_candidates_with_pool(region_name, candidates, pool) 

264 

265 def iter_all_features(self) -> Iterator[Transcript]: 

266 """Yield transcripts by streaming the file sequentially. 

267 

268 Returns: 

269 Iterator[Transcript]: Transcripts built from the entire file. 

270 """ 

271 

272 logger.info(_ORDERED_FILE_ASSUMPTION_MESSAGE) 

273 

274 yield from self._iter_features_from_records(self.iter_all_records()) 

275 

276 def iter_features_by_region( 

277 self, 

278 region: str | None = None, 

279 *, 

280 seq_region_name: str | None = None, 

281 start: int | None = None, 

282 end: int | None = None, 

283 ) -> Iterator[Transcript]: 

284 """Yield complete transcripts intersecting one query region. 

285 

286 One region is the batch of one: an indexed query cannot serve this, because a transcript's 

287 exons reach outside the queried region, so the answer is the same sequential pass 

288 ``iter_features_by_regions`` makes. Callers with an index want ``get_features_by_region``, 

289 which queries each candidate's full span instead. 

290 

291 Args: 

292 region (str | None): The region (e.g., "chr1:1000-2000") to get transcripts from. 

293 seq_region_name (str | None): The name of the sequence region (e.g., "chr1"). 

294 start (int | None): The start position of the region. 

295 end (int | None): The end position of the region. 

296 

297 Returns: 

298 Iterator[Transcript]: Transcripts intersecting the region. 

299 """ 

300 

301 try: 

302 query_region = format_region_string(region, seq_region_name=seq_region_name, start=start, end=end) 

303 region_name, region_start, region_end = parse_region_string(query_region) 

304 except ValueError: 

305 logger.debug("Cannot parse region: %s %s:%s-%s", region, seq_region_name, start, end) 

306 return 

307 

308 interval = (region_start or 1, region_end or _PLACEHOLDER_SEQ_REGION_END) 

309 yield from self.iter_features_by_regions({region_name: [interval]}) 

310 

311 def iter_features_by_regions( 

312 self, 

313 intervals_by_region: Mapping[str, Sequence[tuple[int, int]]], 

314 ) -> Iterator[Transcript]: 

315 """Yield only transcripts intersecting reference-space query intervals. 

316 

317 This source's own method, not part of the ``FeatureSource`` contract: a format whose record 

318 already carries a whole feature answers each region on its own, and gains nothing from the 

319 batch. Here one pass serves every requested interval, so a whole input buffer costs one 

320 read of the file rather than one per region. 

321 

322 The record predicate runs before transcript, exon, CDS, and gene models are built, which 

323 keeps the unindexed fallback bounded by the current payload rather than the source size. 

324 

325 Args: 

326 intervals_by_region (Mapping[str, Sequence[tuple[int, int]]]): 1-based inclusive 

327 ``(start, end)`` intervals, keyed by sequence-region name. 

328 

329 Returns: 

330 Iterator[Transcript]: Transcripts intersecting any requested interval. 

331 """ 

332 

333 logger.info(_ORDERED_FILE_ASSUMPTION_MESSAGE) 

334 

335 def overlaps_requested_interval(record: GXFRecord) -> bool: 

336 sequence_region = record.seqid 

337 if self.reference_region_resolver is not None: 

338 sequence_region = self.reference_region_resolver.resolve(sequence_region) 

339 intervals = intervals_by_region.get(sequence_region, ()) 

340 return any(record.start <= end and record.end >= start for start, end in intervals) 

341 

342 yield from self._iter_features_from_records( 

343 self.iter_all_records(), 

344 transcript_predicate=overlaps_requested_interval, 

345 ) 

346 

347 def records_to_features(self, records: list[GXFRecord]) -> list[Transcript]: 

348 """Convert a batch of records into transcripts, with a fresh gene and slice context. 

349 

350 The records must be **complete and contiguous**: every exon, CDS and gene row of each 

351 transcript present, in file order. One transcript is many records, so a partial set builds 

352 partial models rather than failing -- which is why the region and streaming getters are 

353 overridden instead of composing this one record at a time. 

354 

355 Fresh dictionaries are passed every time: ``_build_transcripts`` defaults to shared 

356 mutable dictionaries, which would carry genes and slices over from one call to the next. 

357 

358 Args: 

359 records (list[GXFRecord]): The records to convert, in file order. 

360 

361 Returns: 

362 list[Transcript]: The transcripts they describe. 

363 """ 

364 return self._build_transcripts(records, gene_records={}, gene_cache={}) 

365 

366 def _build_candidates( 

367 self, 

368 seq_region_name: str, 

369 candidates: Mapping[str, tuple[int, int]], 

370 ) -> list[Transcript]: 

371 """Query every candidate's span and build all of them, without the pool.""" 

372 

373 complete_records: list[GXFRecord] = [] 

374 for span_start, span_end in self._merged_spans(candidates.values()): 

375 # stage 2: the transcript rows that overlap the merged spans 

376 complete_records.extend(self._records_for_region(seq_region_name, span_start, span_end)) 

377 return self._build_transcripts( 

378 complete_records, gene_records={}, gene_cache={}, candidate_ids=candidates 

379 ) 

380 

381 def _build_candidates_with_pool( 

382 self, 

383 seq_region_name: str, 

384 candidates: Mapping[str, tuple[int, int]], 

385 pool: FeaturePool[Transcript], 

386 ) -> list[Transcript]: 

387 """Reuse pooled transcripts, query and build only the missing ones, in candidate order. 

388 

389 A pool hit skips its own span, so stage-2 rows are also checked for a pooled id at a 

390 different span. 

391 """ 

392 

393 pooled: dict[str, Transcript] = {} 

394 missing: dict[str, tuple[int, int]] = {} 

395 for transcript_id, span in candidates.items(): 

396 start, end = span 

397 cached = pool.get((seq_region_name, transcript_id, start, end)) 

398 if cached is None: 

399 missing[transcript_id] = span 

400 else: 

401 pooled[transcript_id] = cached 

402 

403 if not missing: 

404 return [pooled[transcript_id] for transcript_id in candidates if transcript_id in pooled] 

405 

406 complete_records: list[GXFRecord] = [] 

407 for span_start, span_end in self._merged_spans(missing.values()): 

408 # stage 2: the transcript rows not in the pool that overlap the merged spans 

409 complete_records.extend(self._records_for_region(seq_region_name, span_start, span_end)) 

410 

411 resurfaced_id = self._first_pooled_id_in_records(complete_records, pooled) 

412 if resurfaced_id is not None: 

413 self._disable_pool_for_duplicate_id(resurfaced_id) 

414 return self._build_candidates(seq_region_name, candidates) 

415 

416 built = self._build_transcripts( 

417 complete_records, gene_records={}, gene_cache={}, candidate_ids=missing 

418 ) 

419 built_by_id: dict[str, Transcript] = {} 

420 for transcript in built: 

421 built_by_id[transcript.stable_id] = transcript 

422 pool.put( 

423 (seq_region_name, transcript.stable_id, transcript.start, transcript.end), 

424 transcript, 

425 ) 

426 

427 combined = {**pooled, **built_by_id} 

428 return [combined[transcript_id] for transcript_id in candidates if transcript_id in combined] 

429 

430 def _first_pooled_id_in_records( 

431 self, records: Iterable[GXFRecord], pooled: Mapping[str, Transcript] 

432 ) -> str | None: 

433 """Return the first transcript id in ``records`` whose span differs from its pooled model.""" 

434 for record in records: 

435 if record.feature_type.lower() not in self.transcript_feature_types: 

436 continue 

437 record_id = self.get_record_id(record) 

438 if record_id is None: 

439 continue 

440 cached = pooled.get(record_id) 

441 if cached is not None and (record.start != cached.start or record.end != cached.end): 

442 return record_id 

443 return None 

444 

445 def _disable_pool_for_duplicate_id(self, transcript_id: str) -> None: 

446 """Clear and permanently disable the pool once a transcript id names two rows.""" 

447 if self._pool_poisoned: 447 ↛ 448line 447 didn't jump to line 448 because the condition on line 447 was never true

448 return 

449 self._pool_poisoned = True 

450 if self.transcript_pool is not None: 450 ↛ 452line 450 didn't jump to line 452 because the condition on line 450 was always true

451 self.transcript_pool.clear() 

452 logger.warning( 

453 "%s has a repeated transcript id %r; disabling the transcript pool for this source", 

454 self.file_path, 

455 transcript_id, 

456 ) 

457 

458 def _records_for_region( 

459 self, 

460 seq_region_name: str, 

461 start: int | None = None, 

462 end: int | None = None, 

463 *, 

464 feature_types: frozenset[str] | None = None, 

465 ) -> list[GXFRecord]: 

466 """Return raw records for one already-parsed region, resolving its name as the file spells it.""" 

467 source_name = seq_region_name 

468 if self.source_region_resolver is not None: 

469 source_name = self.source_region_resolver.resolve(seq_region_name) 

470 records = self._query_records(source_name, start, end, feature_types=feature_types) 

471 source_name_is_declared = ( 

472 self.source_region_resolver is not None 

473 and source_name in self.source_region_resolver.source_names 

474 ) 

475 if records or source_name_is_declared: 

476 return records 

477 

478 # If no records were found using the source name declared in index file or header, 

479 # try common fallback names (chr prefix variations). It can happen for an un-indexed 

480 # GFF/GTF file not having the ##sequence-region directive. 

481 fallback_names = [seq_region_name] 

482 fallback_names.append( 

483 seq_region_name[3:] if seq_region_name[:3].lower() == "chr" else f"chr{seq_region_name}" 

484 ) 

485 for fallback_name in fallback_names: 

486 if fallback_name == source_name: 

487 continue 

488 records = self._query_records(fallback_name, start, end, feature_types=feature_types) 

489 if records: 

490 return records 

491 return [] 

492 

493 def _query_records( 

494 self, 

495 seq_region_name: str, 

496 start: int | None = None, 

497 end: int | None = None, 

498 *, 

499 feature_types: frozenset[str] | None = None, 

500 ) -> list[GXFRecord]: 

501 """Read raw records using one source-specific sequence-region name. 

502 

503 Args: 

504 seq_region_name: The source-spelling sequence-region name to query. 

505 start: Inclusive query start. 

506 end: Inclusive query end. 

507 feature_types: When given, only rows whose column 3 matches one of these values 

508 (case-insensitively) are returned. Applied on the Rust side before a non-matching 

509 line is parsed into a record. 

510 """ 

511 region = format_region_string(seq_region_name=seq_region_name, start=start, end=end) 

512 return self._query_typed_records(region, feature_types=feature_types) 

513 

514 @abstractmethod 

515 def _query_typed_records( 

516 self, 

517 region: str, 

518 *, 

519 feature_types: frozenset[str] | None = None, 

520 ) -> list[GXFRecord]: 

521 """Seek the persistent query parser to a region and read its records. 

522 

523 Implemented per format because only the GFF3 and GTF parsers accept ``feature_types``; 

524 ``Parser``, which bounds ``P``, does not. A subclass binds ``P`` to its own parser type, so 

525 the call type-checks there without narrowing ``self.adaptor`` here. 

526 

527 Returns: 

528 list[GXFRecord]: The records the query returned, empty when it matched nothing. 

529 """ 

530 

531 raise NotImplementedError 

532 

533 def close(self) -> None: 

534 """Close the region-query parser and the attached sequence source.""" 

535 

536 if self._query_parser is not None: 

537 self._query_parser.close() 

538 self._query_parser = None 

539 self._query_parser_pid = None 

540 super().close() 

541 

542 def _open_query_parser(self) -> P: 

543 """Return a query-mode parser kept open for this process's region queries. 

544 

545 Annotation issues thousands of region queries; re-opening the file and its index for each 

546 dominated the run time. The parser is separate from ``adaptor``, which other methods open 

547 and close in other modes, and a process reached through fork opens its own so it never 

548 shares a file offset with its parent. 

549 """ 

550 if self._query_parser is None or self._query_parser_pid != os.getpid(): 

551 query_parser = evolve(self.adaptor) 

552 query_parser.open(self.file_path, mode="query") 

553 self._query_parser = query_parser 

554 self._query_parser_pid = os.getpid() 

555 return self._query_parser 

556 

557 @staticmethod 

558 def _merged_spans(spans: Iterable[tuple[int, int]]) -> list[tuple[int, int]]: 

559 """Return overlapping transcript spans as minimal query ranges.""" 

560 ordered = sorted(spans) 

561 merged: list[tuple[int, int]] = [] 

562 for start, end in ordered: 

563 if not merged or start > merged[-1][1] + 1: 

564 merged.append((start, end)) 

565 continue 

566 previous_start, previous_end = merged[-1] 

567 merged[-1] = (previous_start, max(previous_end, end)) 

568 return merged 

569 

570 def _iter_features_from_records( 

571 self, 

572 records: Iterator[GXFRecord], 

573 *, 

574 transcript_predicate: Callable[[GXFRecord], bool] | None = None, 

575 ) -> Iterator[Transcript]: 

576 """Yield transcripts from an ordered record stream, buffering it into blocks. 

577 

578 Buffers one contiguous gene block, then converts its grouped records into Transcript 

579 objects. One record is never enough, which is why this exists rather than the per-record 

580 conversion ``FeatureSource`` composes by default. 

581 

582 Args: 

583 records (Iterator[GXFRecord]): The records to stream, in file order. 

584 transcript_predicate (Callable[[GXFRecord], bool] | None): Keeps only the transcripts 

585 whose own record matches, applied before any model is built. 

586 

587 Returns: 

588 Iterator[Transcript]: Transcripts built from buffered GXF records. 

589 """ 

590 

591 gene_cache: dict[str, Gene] = {} 

592 buffer: list[GXFRecord] = [] 

593 current_gene_key: str | None = None 

594 

595 for record in records: 

596 gene_key = self._stream_gene_key(record) 

597 if gene_key is not None and current_gene_key not in (None, gene_key): 

598 yield from self._stream_buffer_features( 

599 buffer, 

600 gene_cache=gene_cache, 

601 transcript_predicate=transcript_predicate, 

602 ) 

603 buffer = [] 

604 gene_cache.clear() 

605 if gene_key is not None: 

606 current_gene_key = gene_key 

607 buffer.append(record) 

608 

609 if buffer: 609 ↛ exitline 609 didn't return from function '_iter_features_from_records' because the condition on line 609 was always true

610 yield from self._stream_buffer_features( 

611 buffer, 

612 gene_cache=gene_cache, 

613 transcript_predicate=transcript_predicate, 

614 ) 

615 

616 def _stream_buffer_features( 

617 self, 

618 records: list[GXFRecord], 

619 *, 

620 gene_cache: dict[str, Gene], 

621 transcript_predicate: Callable[[GXFRecord], bool] | None, 

622 ) -> list[Transcript]: 

623 """Build requested transcripts from one gene-sized streamed record block.""" 

624 

625 groups = self._group_records(records) 

626 if transcript_predicate is not None: 

627 groups = [group for group in groups if transcript_predicate(group.transcript_record)] 

628 return self._groups_to_features_with_context( 

629 groups, 

630 gene_cache=gene_cache, 

631 ) 

632 

633 def _stream_gene_key(self, record: GXFRecord) -> str | None: 

634 """Return the gene-sized streaming block key for one ordered record.""" 

635 

636 explicit_gene_id = self._first_attr(record, "gene_id") 

637 if explicit_gene_id is not None: 

638 return explicit_gene_id 

639 feature_type = record.feature_type.lower() 

640 if feature_type in self.gene_feature_types: 

641 return self.get_record_id(record) 

642 if feature_type in self.transcript_feature_types: 

643 parent_ids = self.get_parent_ids(record) 

644 if parent_ids: 

645 return parent_ids[0] 

646 return f"transcript:{self.get_record_id(record)}" 

647 return None 

648 

649 @abstractmethod 

650 def get_record_id(self, record: GXFRecord) -> str | None: 

651 """Return the stable identifier for a GFF3/GTF record. 

652 

653 Args: 

654 record: The record to inspect. 

655 

656 Returns: 

657 str | None: The record identifier, or None when the record is not 

658 identified. 

659 """ 

660 

661 raise NotImplementedError 

662 

663 @abstractmethod 

664 def get_parent_ids(self, record: GXFRecord) -> tuple[str, ...]: 

665 """Return the parent identifiers for a GFF3/GTF record, if they exist. 

666 

667 Plural because one GFF3 row may name several parents: an exon shared by two transcripts 

668 arrives as a single record with ``Parent=transcript:1,transcript:2``, and taking only the 

669 first would drop it from every transcript but one. 

670 

671 Args: 

672 record: The record to inspect. 

673 

674 Returns: 

675 tuple[str, ...]: A tuple of parent identifiers, or an empty tuple when the record has 

676 no parent. 

677 """ 

678 

679 raise NotImplementedError 

680 

681 def _build_transcripts( 

682 self, 

683 records: list[GXFRecord], 

684 *, 

685 gene_records: dict[str, GXFRecord] | None = None, 

686 gene_cache: dict[str, Gene] | None = None, 

687 candidate_ids: Mapping[str, tuple[int, int]] | None = None, 

688 ) -> list[Transcript]: 

689 """Convert buffered records into Transcript objects while reusing caches. 

690 

691 Args: 

692 records (list[GXFRecord]): Buffered records that belong to one streaming chunk. 

693 gene_records (dict[str, GXFRecord]): Previously seen gene records keyed by gene id. 

694 gene_cache (dict[str, Gene]): Previously built Gene objects keyed by gene id. 

695 candidate_ids (Mapping[str, tuple[int, int]] | None): When given, only transcripts 

696 whose id is a key of this mapping are built; every other transcript is dropped 

697 while grouping, before any model is constructed for it. 

698 

699 Returns: 

700 list[Transcript]: Transcript objects assembled from the buffered records. 

701 """ 

702 

703 gene_records = {} if gene_records is None else gene_records 

704 gene_cache = {} if gene_cache is None else gene_cache 

705 groups = self._group_records(records, candidate_ids=candidate_ids) 

706 return self._groups_to_features_with_context( 

707 groups, 

708 gene_records=gene_records, 

709 gene_cache=gene_cache, 

710 ) 

711 

712 def _groups_to_features_with_context( 

713 self, 

714 groups: list[_GXFTranscriptGroup], 

715 *, 

716 gene_records: dict[str, GXFRecord] | None = None, 

717 gene_cache: dict[str, Gene] | None = None, 

718 ) -> list[Transcript]: 

719 """Build already-grouped transcripts while reusing gene and slice models.""" 

720 

721 gene_records = {} if gene_records is None else gene_records 

722 gene_cache = {} if gene_cache is None else gene_cache 

723 transcripts = [self._build_transcript_from_record_group(group) for group in groups] 

724 

725 for group, transcript in zip(groups, transcripts, strict=True): 

726 gene_record = self._resolve_gene_record(group, gene_records) 

727 self._resolve_gene(gene_record, group.gene_id, transcript, gene_cache) 

728 

729 return transcripts 

730 

731 def _group_records( 

732 self, 

733 records: Iterable[GXFRecord], 

734 *, 

735 candidate_ids: Mapping[str, tuple[int, int]] | None = None, 

736 ) -> list[_GXFTranscriptGroup]: 

737 """Group parser records into per-transcript blocks. 

738 

739 ``record_id`` is computed only for gene and transcript rows, and ``parent_id`` only for 

740 transcript, exon and coding rows -- the ids each routing decision below actually needs. An 

741 exon or CDS record's own id is still resolved later, per exon, when the transcript itself 

742 is built. 

743 

744 Args: 

745 records (Iterable[GXFRecord]): The buffered records to group. 

746 candidate_ids (Mapping[str, tuple[int, int]] | None): When given, only transcripts 

747 whose id is a key of this mapping are grouped; every other transcript's records are 

748 still scanned (a record's transcript is not known until the whole pass completes), 

749 but no group, and therefore no model, is built for it. Relative order among the 

750 kept transcripts is unchanged. 

751 

752 Returns: 

753 list[_GXFTranscriptGroup]: One grouped transcript block per (candidate) transcript 

754 record, in the order transcripts were first seen. 

755 """ 

756 

757 gene_map: dict[str, GXFRecord] = {} 

758 transcript_map: dict[str, tuple[GXFRecord, str | None]] = {} 

759 exon_map: dict[str, list[GXFRecord]] = defaultdict(list) 

760 cds_map: dict[str, list[GXFRecord]] = defaultdict(list) 

761 

762 for record in records: 

763 feature_type = record.feature_type.lower() 

764 

765 if feature_type in self.gene_feature_types: 

766 record_id = self.get_record_id(record) 

767 if record_id: 767 ↛ 762line 767 didn't jump to line 762 because the condition on line 767 was always true

768 gene_map[record_id] = record 

769 elif feature_type in self.transcript_feature_types: 

770 record_id = self.get_record_id(record) 

771 if record_id: 771 ↛ 762line 771 didn't jump to line 762 because the condition on line 771 was always true

772 previous = transcript_map.get(record_id) 

773 if previous is not None and (previous[0].start, previous[0].end) != ( 773 ↛ 778line 773 didn't jump to line 778 because the condition on line 773 was never true

774 record.start, 

775 record.end, 

776 ): 

777 # One row can arrive once per merged span; a different span is a real duplicate. 

778 self._disable_pool_for_duplicate_id(record_id) 

779 # A later duplicate without a Parent keeps the earlier gene id. 

780 parent_ids = self.get_parent_ids(record) 

781 parent_id = parent_ids[0] if parent_ids else None 

782 previous_gene_id = previous[1] if previous is not None else None 

783 transcript_map[record_id] = (record, parent_id or previous_gene_id) 

784 elif feature_type in self.exon_feature_types: 

785 for parent_id in self.get_parent_ids(record): 

786 exon_map[parent_id].append(record) 

787 elif feature_type in self.coding_feature_types: 

788 for parent_id in self.get_parent_ids(record): 

789 cds_map[parent_id].append(record) 

790 

791 return [ 

792 _GXFTranscriptGroup( 

793 transcript_id=transcript_id, 

794 gene_id=gene_id, 

795 transcript_record=transcript_record, 

796 gene_record=gene_map.get(gene_id) if gene_id else None, 

797 exon_records=exon_map.get(transcript_id, []), 

798 cds_records=cds_map.get(transcript_id, []), 

799 ) 

800 for transcript_id, (transcript_record, gene_id) in transcript_map.items() 

801 if candidate_ids is None or transcript_id in candidate_ids 

802 ] 

803 

804 def _resolve_gene_record( 

805 self, 

806 group: _GXFTranscriptGroup, 

807 gene_records: dict[str, GXFRecord] | None = None, 

808 ) -> GXFRecord | None: 

809 """Return the gene record for a grouped transcript, if one exists. 

810 

811 Args: 

812 group (_GXFTranscriptGroup): The grouped transcript records. 

813 gene_records (dict[str, GXFRecord]): Previously seen gene records keyed by gene id. 

814 

815 Returns: 

816 GXFRecord | None: The gene record for the grouped transcript, or None if not found. 

817 """ 

818 

819 gene_records = {} if gene_records is None else gene_records 

820 if group.gene_record is not None: 

821 return group.gene_record 

822 

823 if group.gene_id: 

824 return gene_records.get(group.gene_id) 

825 return None 

826 

827 def _resolve_gene( 

828 self, 

829 gene_record: GXFRecord | None, 

830 gene_id: str | None, 

831 transcript: Transcript, 

832 gene_cache: dict[str, Gene] | None = None, 

833 ) -> None: 

834 """Attach a Gene to a Transcript, reusing cached Gene objects when possible. 

835 

836 Args: 

837 gene_record (GXFRecord | None): The gene record to convert, if present. 

838 gene_id (str | None): The gene's own identifier, already resolved by the caller 

839 (``_GXFTranscriptGroup.gene_id`` for the common in-group case) rather than 

840 recomputed from ``gene_record``. 

841 transcript (Transcript): The transcript to attach the gene to. 

842 gene_cache (dict[str, Gene]): Previously built Gene objects keyed by gene id. 

843 """ 

844 

845 if gene_record is None: 

846 return 

847 

848 gene_cache = {} if gene_cache is None else gene_cache 

849 gene_key = gene_id or "" 

850 gene = gene_cache.get(gene_key) 

851 if gene is None: 

852 gene = self._build_gene(gene_record) 

853 gene_cache[gene_key] = gene 

854 

855 assert gene.transcripts is not None 

856 gene.transcripts.append(transcript) 

857 transcript.gene = gene 

858 

859 def _build_transcript_from_record_group( 

860 self, 

861 group: _GXFTranscriptGroup, 

862 ) -> Transcript: 

863 """Construct a Transcript from one grouped record block. 

864 

865 Args: 

866 group: The grouped records to convert. 

867 

868 Returns: 

869 Transcript: The assembled transcript object. 

870 """ 

871 

872 transcript_record = group.transcript_record 

873 strand = STRAND_SYMBOL_TO_ENUM.get(transcript_record.strand_symbol, Strand.UNKNOWN) 

874 seq_region_name = transcript_record.seqid 

875 if self.reference_region_resolver is not None: 

876 seq_region_name = self.reference_region_resolver.resolve(seq_region_name) 

877 genomic_slice = self.slice_cache.get_slice(seq_region_name, self.sequence_source) 

878 

879 transcript = Transcript( 

880 stable_id=group.transcript_id, 

881 start=transcript_record.start, 

882 end=transcript_record.end, 

883 strand=strand, 

884 slice=genomic_slice, 

885 ) 

886 # Both spellings appear in the wild: GFF3 writes "biotype", GTF "transcript_biotype". It was 

887 # read for the gene but never for the transcript, so a protein_coding transcript read from a 

888 # file came back with no biotype at all. 

889 biotype = self._first_attr(transcript_record, "biotype") or self._first_attr( 

890 transcript_record, "transcript_biotype" 

891 ) 

892 exons = self._build_exons(group.exon_records, group.cds_records, strand, genomic_slice) 

893 # Brand-new transcript: nothing is cached yet, so the on_setattr hook has nothing to 

894 # invalidate -- skip straight to the fields it would leave set. 

895 transcript.assign_without_hooks(biotype=biotype, spliced_exons=exons) 

896 

897 if group.cds_records: 

898 translation = self._build_translation(group.cds_records, transcript) 

899 if translation is not None: 899 ↛ 905line 899 didn't jump to line 905 because the condition on line 899 was always true

900 translation.transcript = transcript 

901 # translation is derived and read-only, so it is seeded rather than assigned. 

902 # seed_attrs, not seed_and_invalidate_attrs: nothing downstream is resolved yet. 

903 transcript.seed_attrs(translation=translation) 

904 

905 return transcript 

906 

907 def _build_exons( 

908 self, 

909 exon_records: list[GXFRecord], 

910 cds_records: list[GXFRecord], 

911 strand: Strand, 

912 genomic_slice: Slice, 

913 ) -> list[Exon]: 

914 """Construct exon objects from grouped records. 

915 

916 An exon's phase is read from the first CDS row, in transcript order, that starts inside it, 

917 as VEP reads it (``BaseGXF::_create_transcript``); an exon no CDS row starts in has an 

918 unknown phase. A transcript with no CDS rows leaves every phase unset. 

919 

920 Args: 

921 exon_records: Exon records attached to one transcript. 

922 cds_records: Coding records attached to the same transcript. 

923 strand: The transcript strand. 

924 genomic_slice: The transcript's own Slice, reused for every exon -- an exon is always 

925 on the same sequence region as its transcript. 

926 

927 Returns: 

928 list[Exon]: The exon objects for the transcript, ordered 5' to 3' along the transcript 

929 (descending genomic start for a reverse-strand transcript). 

930 """ 

931 

932 reverse = strand == Strand.REVERSE 

933 ordered_cds_records = sorted(cds_records, key=lambda record: record.start, reverse=reverse) 

934 exons: list[Exon] = [] 

935 for exon_record in sorted(exon_records, key=lambda record: record.start, reverse=reverse): 

936 stable_id = self.get_record_id(exon_record) or "" 

937 exon = Exon( 

938 stable_id=stable_id, 

939 start=exon_record.start, 

940 end=exon_record.end, 

941 strand=strand, 

942 slice=genomic_slice, 

943 ) 

944 if ordered_cds_records: 

945 # Brand-new exon: nothing cached yet, same reasoning as spliced_exons above. 

946 exon.assign_without_hooks(phase=self._exon_phase(exon_record, ordered_cds_records)) 

947 exons.append(exon) 

948 return exons 

949 

950 @staticmethod 

951 def _exon_phase(exon_record: GXFRecord, ordered_cds_records: list[GXFRecord]) -> ExonPhase: 

952 """Return the Ensembl phase of the first CDS row starting inside an exon, else unknown.""" 

953 for cds_record in ordered_cds_records: 

954 if exon_record.start <= cds_record.start <= exon_record.end: 

955 if cds_record.phase_value is None: 

956 return ExonPhase.UNKNOWN 

957 return GFF_TO_ENSEMBL_PHASE.get(cds_record.phase_value, ExonPhase.UNKNOWN) 

958 return ExonPhase.UNKNOWN 

959 

960 def _build_translation(self, cds_records: list[GXFRecord], transcript: Transcript) -> Translation | None: 

961 """Construct a Translation from CDS records. 

962 

963 ``Translation.start`` and ``end`` are offsets from the start of the transcript, not genomic 

964 coordinates -- ``Transcript._coding_start`` re-maps them with ``self.start + start - 1``. 

965 Seeding them with the raw genomic span therefore double-counts the transcript's own start, 

966 putting the coding boundaries outside the transcript: ``cds`` resolves to None, and every 

967 coding consequence silently disappears while positional ones survive. 

968 

969 Args: 

970 cds_records: Coding records attached to the transcript. 

971 transcript: The transcript the offsets are relative to, which also gives the strand: 

972 on the reverse strand the translation starts at the highest genomic coordinate. 

973 

974 Returns: 

975 Translation | None: The translation object, or None when no coding 

976 records are present. 

977 """ 

978 

979 if not cds_records: 

980 return None 

981 

982 cds_start = min(record.start for record in cds_records) 

983 cds_end = max(record.end for record in cds_records) 

984 if transcript.strand == Strand.FORWARD: 

985 start = cds_start - transcript.start + 1 

986 end = cds_end - transcript.start + 1 

987 else: 

988 start = transcript.end - cds_end + 1 

989 end = transcript.end - cds_start + 1 

990 stable_id = ( 

991 self._first_attr(cds_records[0], "protein_id") or self._first_attr(cds_records[0], "ID") or "" 

992 ) 

993 return Translation(start=start, end=end, stable_id=stable_id) 

994 

995 def _build_gene(self, gene_record: GXFRecord) -> Gene: 

996 """Construct a Gene object from a grouped gene record. 

997 

998 Args: 

999 gene_record: The gene record to convert. 

1000 

1001 Returns: 

1002 Gene: The assembled gene object. 

1003 """ 

1004 

1005 strand = STRAND_SYMBOL_TO_ENUM.get(gene_record.strand_symbol, Strand.UNKNOWN) 

1006 stable_id = self.get_record_id(gene_record) or "" 

1007 seq_region_name = gene_record.seqid 

1008 if self.reference_region_resolver is not None: 

1009 seq_region_name = self.reference_region_resolver.resolve(seq_region_name) 

1010 

1011 gene = Gene( 

1012 stable_id=stable_id, 

1013 start=gene_record.start, 

1014 end=gene_record.end, 

1015 strand=strand, 

1016 slice=self.slice_cache.get_slice(seq_region_name, self.sequence_source), 

1017 ) 

1018 name = self._first_attr(gene_record, "Name") or self._first_attr(gene_record, "gene_name") 

1019 biotype = self._first_attr(gene_record, "biotype") or self._first_attr(gene_record, "gene_biotype") 

1020 # Brand-new gene: nothing cached yet, same reasoning as the transcript and exon paths above. 

1021 gene.assign_without_hooks(name=name, biotype=biotype, transcripts=[]) 

1022 return gene 

1023 

1024 @staticmethod 

1025 def _first_attr(record: GXFRecord, key: str) -> str | None: 

1026 """Return the first attribute value for a key, if present. 

1027 

1028 Uses the ``first_attribute`` pymethod -- a linear scan of the stored attribute pairs -- 

1029 rather than the ``attributes`` getter, which builds a whole dict per call. 

1030 

1031 Args: 

1032 record: The record to inspect. 

1033 key: The attribute key to look up. 

1034 

1035 Returns: 

1036 str | None: The first attribute value for the key, if present. 

1037 """ 

1038 

1039 return record.first_attribute(key)