Coverage for corgi/data.py: 99.27%
275 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-28 00:24 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-28 00:24 +0000
1"""Data loading for Corgi: sequence slicing, collation, datasets and dataloaders."""
3import os
4import gzip
5import random
6from dataclasses import dataclass
7from zlib import adler32
8import numpy as np
9from pathlib import Path
10from scipy.stats import rv_continuous, skewnorm
11import torch
12from Bio import SeqIO
13from torch import nn
14from torch.utils.data import DataLoader
15from torch.utils.data import Dataset
16import lightning as L
17from seqbank import SeqBank
18from seqbank.transform import seq_to_numpy
20from .seqtree import SeqTree
22from rich.console import Console
24console = Console()
27def generate_overlapping_intervals(
28 total: int, interval_size: int, min_overlap: int, check: bool = True, variable_size: bool = False
29) -> list[tuple[int, int]]:
30 """
31 Creates a list of overlapping intervals within a specified range, adjusting the interval size to ensure
32 that the overlap is approximately the same across all intervals.
34 Args:
35 total (int): The total range within which intervals are to be created.
36 max_interval_size (int): The maximum size of each interval.
37 min_overlap (int): The minimum number of units by which consecutive intervals overlap.
38 check (bool): If True, checks are performed to ensure that the intervals meet the specified conditions.
40 Returns:
41 list[tuple[int, int]]: A list of tuples where each tuple represents the start (inclusive)
42 and end (exclusive) of an interval.
44 Example:
45 >>> generate_overlapping_intervals(20, 5, 2)
46 [(0, 5), (3, 8), (6, 11), (9, 14), (12, 17), (15, 20)]
47 """
48 if total <= interval_size:
49 return [(0, total)]
51 intervals = []
52 start = 0
54 if total == 0:
55 return intervals
57 max_interval_size = interval_size
58 assert interval_size
59 assert min_overlap is not None
60 assert (
61 interval_size > min_overlap
62 ), f"Max interval size of {interval_size} must be greater than min overlap of {min_overlap}"
64 # Calculate the number of intervals needed to cover the range
65 num_intervals, remainder = divmod(total - min_overlap, interval_size - min_overlap)
66 if remainder > 0:
67 num_intervals += 1
69 # Calculate the exact interval size to ensure consistent overlap
70 overlap = min_overlap
71 if variable_size:
72 if num_intervals > 1:
73 interval_size, remainder = divmod(total + (num_intervals - 1) * overlap, num_intervals)
74 if remainder > 0:
75 interval_size += 1
76 else:
77 # If the size is fixed, then vary the overlap to keep it even
78 if num_intervals > 1:
79 overlap, remainder = divmod(num_intervals * interval_size - total, num_intervals - 1)
80 if overlap < min_overlap:
81 overlap = min_overlap
83 while True:
84 end = start + interval_size
85 if end > total:
86 end = total
87 start = max(end - interval_size, 0)
88 intervals.append((start, end))
89 start += interval_size - overlap
90 if end >= total:
91 break
93 if check:
94 assert intervals[0][0] == 0
95 assert intervals[-1][1] == total
96 assert len(intervals) == num_intervals, f"Expected {num_intervals} intervals, got {len(intervals)}"
98 assert (
99 interval_size <= max_interval_size
100 ), f"Interval size of {interval_size} exceeds max interval size of {max_interval_size}"
101 for interval in intervals:
102 assert (
103 interval[1] - interval[0] == interval_size
104 ), f"Interval size of {interval[1] - interval[0]} is not the expected size {interval_size}"
106 for i in range(1, len(intervals)):
107 overlap = intervals[i - 1][1] - intervals[i][0]
108 assert (
109 overlap >= min_overlap
110 ), f"Min overlap condition of {min_overlap} not met for intervals {intervals[i - 1]} and {intervals[i]} (overlap {overlap})"
112 return intervals
115def slice_tensor(tensor, size, start_index=None, pad: bool = True):
116 """Slices a 1D tensor to a given size.
118 Args:
119 tensor (Tensor): The tensor to slice.
120 size (int): The length of the slice.
121 start_index (int | None): Where the slice starts. If None, then it is chosen randomly (or 0 if the tensor
122 is no longer than `size`).
123 pad (bool): Whether or not to pad with zeros at the end if the slice extends beyond the tensor.
125 Returns:
126 Tensor: The slice.
127 """
128 original_length = tensor.shape[0]
129 if start_index is None:
130 if original_length <= size:
131 start_index = 0
132 else:
133 start_index = random.randrange(0, original_length - size)
134 end_index = start_index + size
135 if end_index > original_length and pad:
136 sliced = tensor[start_index:]
137 sliced = nn.ConstantPad1d((0, end_index - original_length), 0)(sliced)
138 else:
139 sliced = tensor[start_index:end_index]
140 return sliced
143@dataclass
144class Collate:
145 """Base class for collating a batch of variable length sequences into tensors of the same length."""
147 def get_length(self) -> int:
148 """Returns the length that the sequences in the next batch will be sliced or padded to."""
149 raise NotImplementedError
151 def __call__(self, batch):
152 """Collates a batch of (sequence, target) pairs.
154 Args:
155 batch: A list of (sequence tensor, target) pairs.
157 Returns:
158 tuple[Tensor, Tensor]: The stacked sequences, sliced or padded to the same length, and the targets.
159 """
160 x_batch, y_batch = zip(*batch)
161 length = self.get_length()
163 return torch.stack(tuple(slice_tensor(x, length) for x in x_batch)), torch.tensor(y_batch)
166@dataclass
167class CollateFixedLength(Collate):
168 """Collates batches so that every sequence has the same fixed length."""
170 length: int
172 def get_length(self):
173 """Returns the fixed length."""
174 return self.length
177@dataclass
178class CollateRandomLength(Collate):
179 """Collates batches to a random length for each batch.
181 The lengths are drawn from a skew-normal distribution, truncated to the minimum and maximum lengths.
182 """
184 minimum_length: int
185 maximum_length: int
186 skewness: float = 5
187 loc: float = 600
188 scale: float = 1000
189 seed: int = 42
191 def __post_init__(self):
192 """Checks the lengths and creates the random state and length distribution."""
193 assert self.minimum_length > 0
194 assert self.minimum_length <= self.maximum_length
195 self.random_state = np.random.default_rng(self.seed)
196 self.distribution = skewnorm(self.skewness, loc=self.loc, scale=self.scale)
198 def get_length(self) -> int:
199 """Draws a length from the distribution which is between the minimum and maximum lengths (inclusive)."""
200 while True:
201 seq_len = int(self.distribution.rvs(random_state=self.random_state))
202 if seq_len < self.minimum_length or seq_len > self.maximum_length:
203 continue
204 return seq_len
207@dataclass(kw_only=True)
208class CorgiTrainingDataset(Dataset):
209 """A dataset of sequences from a SeqBank, with the node in the classification tree as the target.
211 Args:
212 accessions (list[str]): The accessions in the dataset.
213 seqbank (SeqBank): The SeqBank which holds the sequences.
214 seqtree (SeqTree): The SeqTree which gives the node for each accession.
215 deterministic (bool): Whether or not truncation of long sequences always takes the same slice for an accession.
216 maximum (int): The maximum length of a sequence. Longer sequences are truncated. If zero, they are not truncated.
217 """
219 accessions: list[str]
220 seqbank: SeqBank
221 seqtree: SeqTree
222 deterministic: bool = False
223 maximum: int = 0
225 def __len__(self):
226 """Returns the number of accessions."""
227 return len(self.accessions)
229 def __getstate__(self):
230 # The SeqBank holds an open database handle and a lock which cannot be pickled
231 # (needed for DataLoader workers with the 'spawn' and 'forkserver' start methods).
232 # Send the path and engine instead and reopen it in the worker.
233 """Returns the state for pickling, replacing the SeqBank with its path and engine so it can be reopened in a worker."""
234 state = self.__dict__.copy()
235 seqbank = state.pop("seqbank")
236 state["_seqbank_args"] = (seqbank.path, seqbank.engine)
237 return state
239 def __setstate__(self, state):
240 """Restores the state after pickling and reopens the SeqBank."""
241 path, engine = state.pop("_seqbank_args")
242 self.__dict__.update(state)
243 self.seqbank = SeqBank(path, engine=engine)
245 def reopen_seqbank(self):
246 """
247 Closes the SeqBank and replaces it with a new one on the same path and engine.
249 Used in DataLoader workers so that each worker has its own database handle
250 rather than one inherited from the parent process by 'fork'.
251 """
252 seqbank = self.seqbank
253 seqbank.close()
254 self.seqbank = SeqBank(seqbank.path, engine=seqbank.engine)
256 def __getitem__(self, idx):
257 """Returns the sequence and target for an accession.
259 Sequences longer than `maximum` are truncated to a random slice (or a fixed one if `deterministic`).
261 Returns:
262 tuple[Tensor, int]: The sequence tensor and the ID of the node in the classification tree.
263 """
264 accession = self.accessions[idx]
265 data = self.seqbank[accession]
266 length = len(data)
268 # Truncate if necessary
269 if self.maximum and length > self.maximum:
270 rng = np.random.RandomState(adler32(accession.encode("ascii"))) if self.deterministic else np.random
271 start_index = rng.randint(0, length - self.maximum)
272 data = data[start_index : start_index + self.maximum]
274 array = torch.as_tensor(memoryview(data), dtype=torch.uint8)
276 return torch.Tensor(array), self.seqtree[accession].node_id
279def seqbank_worker_init(worker_id: int):
280 """Gives each DataLoader worker its own SeqBank handle (not shared with the parent process)."""
281 worker_info = torch.utils.data.get_worker_info()
282 worker_info.dataset.reopen_seqbank()
285@dataclass
286class CorgiDataModule(L.LightningDataModule):
287 """A Lightning data module which loads sequences from a SeqBank for the nodes in a SeqTree.
289 The accessions are split into training and validation sets using the partitions in the SeqTree.
290 """
292 seqtree: SeqTree
293 seqbank: SeqBank
294 batch_size: int
295 max_items: int = 0
296 minimum_length: int = 150
297 maximum_length: int = 3_000
298 validation_length: int = 1000
299 validation_partition: int = 1
300 test_partition: int = 0
301 skewness: float = 5
302 loc: float = 600
303 scale: float = 1000
304 num_workers: int | None = None
305 train_all: bool = False
307 def __post_init__(self):
308 """Initializes the Lightning data module."""
309 super().__init__()
311 def setup(self, stage=None):
312 """Creates the training and validation datasets from the partitions in the SeqTree.
314 The test partition is excluded. If there are no validation accessions, then the training set is used for validation.
315 """
316 if self.num_workers is None:
317 self.num_workers = min(os.cpu_count(), 8)
319 # Create list of accessions for training and validation depending on validation_partition and test_partition
320 training_accessions = []
321 validation_accessions = []
323 assert (
324 self.validation_partition != self.test_partition
325 ), f"Validation partition {self.validation_partition} the same as test partition {self.test_partition}"
327 for accession, details in self.seqtree.items():
328 # Ignore test partition so we do not validate or train on it
329 if details.partition == self.test_partition:
330 continue
332 accessions_list = (
333 validation_accessions if details.partition == self.validation_partition else training_accessions
334 )
335 accessions_list.append(accession)
337 if self.train_all:
338 training_accessions += validation_accessions
340 if len(validation_accessions) == 0:
341 console.print(
342 f"[bold red]WARNING: No validation accessions found. Check the validation partition {self.validation_partition}. Using all the training examples for validation."
343 )
344 validation_accessions = training_accessions
346 if self.max_items:
347 training_accessions = training_accessions[: self.max_items]
348 validation_accessions = validation_accessions[: self.max_items]
350 self.train_dataset = CorgiTrainingDataset(
351 accessions=training_accessions,
352 seqtree=self.seqtree,
353 seqbank=self.seqbank,
354 deterministic=False,
355 maximum=self.maximum_length,
356 )
357 self.val_dataset = CorgiTrainingDataset(
358 accessions=validation_accessions,
359 seqtree=self.seqtree,
360 seqbank=self.seqbank,
361 deterministic=True,
362 maximum=self.validation_length,
363 )
365 def train_dataloader(self):
366 """Returns the training dataloader, which shuffles the data and collates batches to random lengths."""
367 return DataLoader(
368 self.train_dataset,
369 batch_size=self.batch_size,
370 num_workers=self.num_workers,
371 worker_init_fn=seqbank_worker_init,
372 shuffle=True,
373 collate_fn=CollateRandomLength(
374 self.minimum_length, self.maximum_length, skewness=self.skewness, loc=self.loc, scale=self.scale
375 ),
376 )
378 def val_dataloader(self):
379 """Returns the validation dataloader, which collates batches to a fixed length."""
380 return DataLoader(
381 self.val_dataset,
382 batch_size=self.batch_size,
383 num_workers=self.num_workers,
384 worker_init_fn=seqbank_worker_init,
385 shuffle=False,
386 collate_fn=CollateFixedLength(self.validation_length),
387 )
390class SeqIODataloader:
391 """Iterates over sequence files, giving batches of chunks of sequences as tensors for prediction.
393 Sequences longer than `max_length` are split into overlapping chunks. Details of each chunk yielded are recorded
394 in `chunk_details`.
395 """
397 def __init__(
398 self,
399 files,
400 batch_size: int = 1,
401 min_length: int = 128,
402 max_length: int = 5_000,
403 max_seqs: int = None,
404 overlap: int = 256,
405 format: str = "",
406 ):
407 """Finds the sequence files and counts the chunks.
409 Args:
410 files: A path or list of paths to sequence files or directories (searched recursively).
411 batch_size (int): The number of chunks in each batch.
412 min_length (int): Sequences shorter than this are skipped.
413 max_length (int): The maximum length of a chunk.
414 max_seqs (int | None): The maximum number of sequences to use. If not set, then there is no limit.
415 overlap (int): The minimum overlap between consecutive chunks of a sequence.
416 format (str): The file format. If not given, then it is inferred from the file extension.
417 """
418 self.format = format
419 self.chunk_details = []
420 self.max_length = max_length
421 self.batch_size = batch_size
422 self.min_length = min_length
423 self.count = 0
424 self.max_seqs = max_seqs
425 self.overlap = overlap
426 seqs = 0
428 base_extensions = {".fa", ".fasta", ".fna", ".fas"}
430 # Function to check if a file matches allowed extensions (including .gz)
431 def matches_extensions(file: Path):
432 """Returns whether the file has a FASTA extension, with or without a '.gz' suffix."""
433 return file.suffix in base_extensions or (
434 file.suffix == ".gz" and any(file.stem.endswith(ext) for ext in base_extensions)
435 )
437 # Expand the list
438 self.files = []
440 # If 'files' is a string or Path, convert it to a list
441 if isinstance(files, (str, Path)):
442 files = [Path(files)]
444 for path in files:
445 path = Path(path)
446 if path.is_dir():
447 # If it's a directory, find all files with the specified extensions
448 self.files.extend([file for file in path.rglob("*") if matches_extensions(file)])
449 else:
450 # If it's not a directory, add the file to the list
451 if matches_extensions(path):
452 self.files.append(path)
454 for file in self.files:
455 for record in self.parse(file):
456 if len(record.seq) < self.min_length:
457 continue
459 if self.max_seqs and seqs >= self.max_seqs:
460 break
462 intervals = generate_overlapping_intervals(len(record.seq), self.max_length, self.overlap)
463 self.count += len(intervals)
464 seqs += 1
466 def get_file_format(self, file):
467 """Returns the Biopython format name of a file, inferred from its extension unless `format` was given.
469 Raises:
470 ValueError: If the format cannot be determined.
471 """
472 if self.format:
473 return self.format
475 file = Path(file)
476 suffixes = [suffix.lower() for suffix in file.suffixes]
478 # Check if the last suffix is '.gz' and adjust accordingly
479 if suffixes[-1] == '.gz' and len(suffixes) > 1:
480 suffix = suffixes[-2]
481 else:
482 suffix = suffixes[-1]
484 if suffix in [".fa", ".fna", ".fasta", ".fas", ".frn", ".ref"]:
485 return "fasta"
486 if suffix in [".genbank", ".gb", ".gbk"]:
487 return "genbank"
488 if suffix in [".tab", ".tsv"]:
489 return "tsv"
490 if suffix in [".fastq", ".fq"]:
491 return "fastq"
493 raise ValueError(f"Cannot determine file format of {file}.")
495 def __len__(self):
496 """Returns the total number of chunks."""
497 return self.count
499 def parse(self, file: Path):
500 """Yields the records in a file, which may be gzipped."""
501 file_format = self.get_file_format(file)
503 if file.name.endswith('.gz'):
504 with gzip.open(file, "rt") as f:
505 yield from SeqIO.parse(f, file_format)
506 else:
507 yield from SeqIO.parse(file, file_format)
509 def iter_records(self):
510 """Yields (file, record) pairs for every record in every file."""
511 for file in self.files:
512 for record in self.parse(file):
513 yield file, record
515 def __iter__(self):
516 """Yields batches of chunks as a one-element tuple of a padded tensor.
518 The details of each chunk are appended to `chunk_details`.
519 """
520 batch = []
521 seqs = 0
523 for file in self.files:
524 for record in self.parse(file):
525 if len(record.seq) < self.min_length:
526 continue
528 if self.max_seqs and seqs >= self.max_seqs:
529 break
531 seqs += 1
532 t = torch.tensor(seq_to_numpy(str(record.seq)))
534 intervals = generate_overlapping_intervals(len(t), self.max_length, self.overlap)
536 for chunk_index, interval in enumerate(intervals):
537 self.chunk_details.append((file, record.id, record.description, chunk_index))
538 batch.append(t[interval[0] : interval[1]])
539 if len(batch) >= self.batch_size:
540 batch = self.pad(batch)
541 yield batch
542 batch = []
544 if batch:
545 batch = self.pad(batch)
546 yield batch
548 def pad(self, batch):
549 """Pads the tensors in a batch to the same length and stacks them in a one-element tuple."""
550 max_len = 0
551 for item in batch:
552 max_len = max(item.shape[0], max_len)
554 def pad(tensor):
555 """Pads a tensor to the maximum length and adds a batch dimension."""
556 return slice_tensor(tensor, max_len).unsqueeze(dim=0)
558 return (torch.cat(list(map(pad, batch))),)