Coverage for seqbank/seqbank.py: 100.00%

234 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-27 04:47 +0000

1import numpy as np 

2from pathlib import Path 

3from joblib import Parallel, delayed 

4import plotly.express as px 

5import plotly.graph_objs as go 

6from Bio.Seq import Seq 

7from Bio.SeqRecord import SeqRecord 

8from Bio import SeqIO 

9from attrs import define 

10from rich.progress import track 

11import pyfastx 

12from rich.progress import Progress, TaskID, TimeElapsedColumn, MofNCompleteColumn 

13from datetime import datetime 

14from .storage import Engine, Storage, open_storage 

15from threading import RLock 

16import atexit 

17from typing import Iterator, Sequence 

18 

19from .transform import seq_to_bytes, bytes_to_str 

20from .io import get_file_format, open_path, download_file, seq_count, TemporaryDirectory 

21from .exceptions import SeqBankError 

22from .utils import parse_filter, format_fig 

23 

24 

25@define(slots=False) 

26class SeqBank: 

27 """Store encoded DNA sequences in an engine-backed database directory. 

28 

29 Args: 

30 path: Directory containing the bank and its engine metadata. 

31 write: Allow creating or modifying the bank. Defaults to read-only. 

32 engine: ``rocksdict``, ``lmdb``, or ``speedict``. When omitted, existing 

33 banks are detected automatically and new banks use RocksDict if it is 

34 installed, otherwise LMDB. Banks without metadata are treated as legacy 

35 Speedict banks. LMDB is always available; RocksDict requires 

36 ``seqbank[rocksdict]`` and Speedict requires ``seqbank[speedict]``. 

37 

38 File imports and copies use bounded batches. Individual :meth:`add` calls 

39 commit separately; prefer :meth:`add_file` for bulk LMDB imports. 

40 """ 

41 

42 path: Path 

43 write: bool = False 

44 engine: Engine | str | None = None 

45 

46 def __attrs_post_init__(self) -> None: 

47 """Initializes the SeqBank object after attributes are set. 

48 

49 Expands the user path for the SeqBank file and checks if it exists when not in write mode. 

50 

51 Raises: 

52 FileNotFoundError: If the SeqBank file is not found at the given path when write mode is disabled. 

53 """ 

54 self.path = Path(self.path).expanduser() 

55 self._open_lock = RLock() 

56 if not self.write and not self.path.exists(): 

57 raise FileNotFoundError(f"Cannot find SeqBank file at path: {self.path}") 

58 

59 def key(self, accession: str) -> bytes: 

60 """Generates a key for a given accession. 

61 

62 Args: 

63 accession (str): Accession string used to generate the key. 

64 

65 Returns: 

66 str: A byte-encoded key as a string. 

67 """ 

68 return bytes(accession, "ascii") 

69 

70 def key_url(self, url: str) -> bytes: 

71 """Generates a key for a given URL. 

72 

73 Args: 

74 url (str): The URL for which the key is generated. 

75 

76 Returns: 

77 str: A byte-encoded key string prefixed with '/seqbank/url/'. 

78 """ 

79 return self.key("/seqbank/url/" + url) 

80 

81 def close(self) -> None: 

82 """Closes the SeqBank database connection. 

83 

84 Attempts to close the database connection, if it's open, and silently handles any exceptions. 

85 """ 

86 try: 

87 self._db.close() 

88 except Exception: 

89 pass 

90 

91 @property 

92 def file(self) -> Storage: 

93 """Open the selected storage engine lazily, safely across import threads.""" 

94 if "_db" in self.__dict__: 

95 return self.__dict__["_db"] 

96 with self._open_lock: 

97 if "_db" not in self.__dict__: 

98 self._db, self.engine = open_storage(self.path, self.write, self.engine) 

99 atexit.register(self.close) 

100 return self._db 

101 

102 @file.setter 

103 def file(self, storage: Storage) -> None: 

104 self._db = storage 

105 

106 def __len__(self) -> int: 

107 """Calculates the total number of items in the SeqBank. 

108 

109 Iterates over all the keys in the database and counts them. 

110 

111 Returns: 

112 int: The number of entries in the SeqBank. 

113 """ 

114 count = 0 

115 for _ in track(self.file.keys()): 

116 count += 1 

117 return count 

118 

119 def __getitem__(self, accession: str) -> bytes: 

120 """Retrieves the sequence data associated with a given accession. 

121 

122 Args: 

123 accession (str): The accession key to look up in the SeqBank. 

124 

125 Returns: 

126 bytes: The encoded sequence data stored in the SeqBank for the given accession. 

127 

128 Raises: 

129 SeqBankError: If the accession cannot be read or an error occurs during retrieval. 

130 """ 

131 try: 

132 key = self.key(accession) 

133 file = self.file 

134 return file[key] 

135 except Exception as err: 

136 raise SeqBankError(f"Failed to read {accession} in SeqBank {self.path}:\n{err}") 

137 

138 def items(self) -> Iterator[tuple[bytes, np.ndarray]]: 

139 """Yields all key-value pairs from the SeqBank. 

140 

141 The key is the accession, and the value is the sequence data in NumPy array format. 

142 

143 Yields: 

144 tuple: A tuple containing the accession (key) and the sequence data (value) as a NumPy array. 

145 """ 

146 for k, v in self.file.items(): 

147 yield k, np.frombuffer(v, dtype="u1") 

148 

149 def __contains__(self, accession: str) -> bool: 

150 """Checks if a given accession exists in the SeqBank. 

151 

152 Args: 

153 accession (str): The accession to check for existence. 

154 

155 Returns: 

156 bool: True if the accession exists in the SeqBank, otherwise False. 

157 """ 

158 try: 

159 return self.key(accession) in self.file 

160 except Exception: 

161 return False 

162 

163 def delete(self, accession: str) -> None: 

164 """Deletes a sequence entry from the SeqBank by its accession. 

165 

166 Args: 

167 accession (str): The accession of the sequence to delete. 

168 

169 Returns: 

170 None 

171 """ 

172 key = self.key(accession) 

173 f = self.file 

174 if key in f: 

175 del f[key] 

176 

177 def add(self, seq: str | Seq | SeqRecord | np.ndarray, accession: str) -> None: 

178 """Adds a sequence to the SeqBank with a given accession. 

179 

180 This method accepts a sequence in various formats (string, Seq, SeqRecord, or NumPy array) 

181 and stores it in the SeqBank after appropriate conversion to byte format. 

182 

183 Args: 

184 seq (str | Seq | SeqRecord | np.ndarray): The sequence to add to the SeqBank. 

185 It can be a string, Bio.Seq object, SeqRecord, or a NumPy array. 

186 accession (str): The accession key for the sequence to be stored under. 

187 

188 Returns: 

189 None 

190 """ 

191 key = self.key(accession) 

192 

193 if isinstance(seq, SeqRecord): 

194 seq = str(seq.seq) 

195 if isinstance(seq, Seq): 

196 seq = str(seq) 

197 value = seq_to_bytes(seq) if isinstance(seq, str) else bytes(seq) 

198 

199 self.file[key] = value 

200 

201 def add_file( 

202 self, 

203 path: Path, 

204 format: str = "", 

205 progress: Progress | None = None, 

206 overall_task: TaskID | None = None, 

207 filter: Path | list | set | None = None, 

208 ) -> None: 

209 """Adds sequences from a file to the SeqBank. 

210 

211 This method processes a sequence file in various formats (e.g., FASTA, FASTQ), optionally filtering specific accessions, 

212 and adds the sequences to the SeqBank. Progress tracking is available for large file imports. 

213 

214 Args: 

215 path (Path): The path to the sequence file. 

216 format (str, optional): The format of the sequence file (e.g., "fasta", "fastq"). If not provided, it will be auto-detected. 

217 progress (Progress, optional): A rich progress bar to display the import progress. Defaults to None. 

218 overall_task (int | None, optional): An optional task ID for tracking the overall progress. Defaults to None. 

219 filter (Path | list | set | None, optional): A filter for selecting specific accessions. Defaults to None. 

220 

221 Returns: 

222 None 

223 """ 

224 batch, batch_size = [], 0 

225 

226 def add_record(seq: str | Seq | SeqRecord, accession: str) -> None: 

227 nonlocal batch, batch_size 

228 value = seq_to_bytes(str(seq.seq if isinstance(seq, SeqRecord) else seq)) 

229 key = self.key(accession) 

230 batch.append((key, value)) 

231 batch_size += len(key) + len(value) 

232 if len(batch) >= 1000 or batch_size >= 8 * 1024 * 1024: 

233 self.file.put_many(batch) 

234 batch, batch_size = [], 0 

235 

236 filter = parse_filter(filter) 

237 format = format or get_file_format(path) 

238 progress = progress or Progress() 

239 

240 # If fasta or fastq use pyfastx for speed 

241 if format in ["fasta", "fastq"]: 

242 total = sum(1 for _ in pyfastx.Fasta(str(path), build_index=False)) 

243 task = progress.add_task(f"[magenta]{path.name}", total=total) 

244 

245 for accession, seq in pyfastx.Fasta(str(path), build_index=False): 

246 if filter and accession not in filter: 

247 continue 

248 add_record(seq, accession) 

249 progress.update(task, advance=1) 

250 else: 

251 total = seq_count(path) 

252 

253 with open_path(path) as f: 

254 task = progress.add_task(f"[magenta]{path.name}", total=total) 

255 for record in SeqIO.parse(f, format): 

256 if filter and record.id not in filter: 

257 continue 

258 

259 add_record(record, record.id) 

260 progress.update(task, advance=1) 

261 

262 if batch: 

263 self.file.put_many(batch) 

264 

265 progress.update(task, visible=False) 

266 if overall_task is not None: 

267 progress.update(overall_task, advance=1) 

268 

269 print("Added", path.name) 

270 

271 def add_sequence_from_file( 

272 self, 

273 accession: str, 

274 path: Path, 

275 format: str = "", 

276 ) -> None: 

277 """ 

278 Adds a single sequence from a file to the SeqBank. 

279 

280 This method processes a single sequence from a file in various formats (e.g., FASTA, FASTQ). 

281 The accession for this sequence is provided as an argument. 

282 

283 Args: 

284 accession (str): The accession key for the sequence to be stored under. 

285 path (Path): The path to the sequence file. 

286 format (str, optional): The format of the sequence file (e.g., "fasta", "fastq"). If not provided, it will be auto-detected. 

287 

288 Returns: 

289 None 

290 """ 

291 format = format or get_file_format(path) 

292 

293 def check_total(total: int, path: Path) -> None: 

294 if total > 1: 

295 raise SeqBankError(f"Multiple sequences found in {path}, found {total}") 

296 

297 # If fasta or fastq use pyfastx for speed 

298 if format in ["fasta", "fastq"]: 

299 total = sum(1 for _ in pyfastx.Fasta(str(path), build_index=False)) 

300 check_total(total, path) 

301 

302 for _, seq in pyfastx.Fasta(str(path), build_index=False): 

303 self.add(seq, accession) 

304 else: 

305 total = seq_count(path) 

306 check_total(total, path) 

307 

308 with open_path(path) as f: 

309 for record in SeqIO.parse(f, format): 

310 self.add(record, accession) 

311 

312 def seen_url(self, url: str) -> bool: 

313 """Checks if a given URL has been seen (i.e., processed) before and present in the SeqBank. 

314 

315 Args: 

316 url (str): The URL to check. 

317 

318 Returns: 

319 bool: True if the URL has been seen (i.e., exists in the SeqBank), otherwise False. 

320 """ 

321 return self.key_url(url) in self.file 

322 

323 def save_seen_url(self, url: str) -> None: 

324 """Saves a URL as 'seen' by adding it to the SeqBank with a timestamp. 

325 

326 Args: 

327 url (str): The URL to save as seen. 

328 

329 Returns: 

330 None 

331 """ 

332 url_key = self.key_url(url) 

333 self.file[url_key] = bytes(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "ascii") 

334 

335 def add_url( 

336 self, 

337 url: str, 

338 progress: Progress | None = None, 

339 format: str = "", 

340 force: bool = False, 

341 overall_task: TaskID | None = None, 

342 tmp_dir: str | Path | None = None, 

343 ) -> bool: 

344 """Downloads and adds sequences from a URL to the SeqBank. 

345 

346 This method downloads a file from a given URL, processes it to extract sequences, and adds them to the SeqBank. 

347 If the URL has already been processed, it can be skipped unless `force=True` is provided. 

348 

349 Args: 

350 url (str): The URL to download the sequence file from. 

351 progress (Progress, optional): A rich progress bar to display progress of the download and file processing. Defaults to None. 

352 format (str, optional): The format of the sequence file (e.g., "fasta", "fastq"). If not provided, it will be auto-detected. Defaults to "". 

353 force (bool, optional): Whether to force downloading and processing the URL even if it has been seen before. Defaults to False. 

354 overall_task (int | None, optional): An optional task ID for tracking overall progress. Defaults to None. 

355 tmp_dir (str | Path | None, optional): A temporary directory to store the downloaded file. Defaults to None. 

356 

357 Returns: 

358 bool: True if the URL was successfully processed and added, False otherwise. 

359 """ 

360 url_key = self.key_url(url) 

361 if url_key in self.file and not force: 

362 return False 

363 

364 with TemporaryDirectory(prefix=tmp_dir) as tmpdirname: 

365 local_path = tmpdirname / Path(url).name 

366 try: 

367 download_file(url, local_path) 

368 self.add_file(local_path, format=format, progress=progress, overall_task=overall_task) 

369 self.save_seen_url(url) 

370 except Exception as err: 

371 print(f"Failed to add URL: {url}: {err}") 

372 return False 

373 

374 return True 

375 

376 def get_accessions(self) -> set[str]: 

377 """Retrieves all accessions stored in the SeqBank. 

378 

379 This method iterates through the SeqBank database keys and collects all accessions that do not belong 

380 to the internal '/seqbank/' namespace. 

381 

382 Returns: 

383 set[str]: A set of all accessions present in the SeqBank. 

384 """ 

385 accessions = set() 

386 file = self.file 

387 

388 for key in file.keys(): 

389 accession = key.decode("ascii") 

390 if not accession.startswith("/seqbank/"): 

391 accessions.update([accession]) 

392 

393 return accessions 

394 

395 def missing(self, accessions: list[str] | set[str]) -> set[str]: 

396 """Finds accessions that are not present in the SeqBank. 

397 

398 This method checks a list or set of accessions and returns those that are missing from the SeqBank. 

399 

400 Args: 

401 accessions (list[str] | set[str]): A list or set of accessions to check for presence in the SeqBank. 

402 

403 Returns: 

404 set[str]: A set of accessions that are missing from the SeqBank. 

405 """ 

406 missing = set() 

407 

408 for accession in track(accessions): 

409 if accession not in self: 

410 missing.add(accession) 

411 

412 return missing 

413 

414 def add_urls( 

415 self, 

416 urls: list[str], 

417 max: int = 0, 

418 format: str = "", 

419 force: bool = False, 

420 workers: int = -1, 

421 tmp_dir: str | Path | None = None, 

422 ) -> None: 

423 """Downloads and adds sequences from a list of URLs to the SeqBank. 

424 

425 This method processes a list of URLs, downloads the corresponding sequence files, and adds them to the SeqBank. 

426 It filters out URLs that have already been processed unless `force=True` is specified, and it can limit the number 

427 of URLs processed based on the `max` argument. The processing can be parallelized using the `workers` argument. 

428 

429 Args: 

430 urls (list[str]): A list of URLs to download and process. 

431 max (int, optional): Maximum number of URLs to process. If set to 0, all URLs will be processed. Defaults to 0. 

432 format (str, optional): The format of the sequence files (e.g., "fasta", "fastq"). If not provided, it will be auto-detected. Defaults to "". 

433 force (bool, optional): Whether to force re-processing of URLs even if they were processed before. Defaults to False. 

434 workers (int, optional): Number of workers to use for parallel processing. If set to -1, all available CPU cores will be used. Defaults to -1. 

435 tmp_dir (str | Path | None, optional): A temporary directory to store downloaded files. Defaults to None. 

436 

437 Returns: 

438 None 

439 """ 

440 # only add the URLs that haven't been seen before 

441 urls_to_add = [] 

442 for url in urls: 

443 if not self.seen_url(url): 

444 urls_to_add.append(url) 

445 

446 # truncate URLs list to `max` if requested 

447 if max and len(urls_to_add) >= max: 

448 break 

449 

450 with Progress(*Progress.get_default_columns(), TimeElapsedColumn(), MofNCompleteColumn()) as progress: 

451 parallel = Parallel(n_jobs=workers, prefer="threads") 

452 add_url = delayed(self.add_url) 

453 overall_task = progress.add_task(f"[bold red]Adding URLs", total=len(urls_to_add)) 

454 parallel( 

455 add_url(url, progress=progress, format=format, force=force, overall_task=overall_task, tmp_dir=tmp_dir) 

456 for url in urls_to_add 

457 ) 

458 

459 def ls(self) -> None: 

460 """ 

461 Lists all accessions in the SeqBank. 

462 

463 Iterates through the keys in the SeqBank and prints each one, decoded from bytes to ASCII. 

464 

465 Returns: 

466 None 

467 """ 

468 for k in self.file.keys(): 

469 print(k.decode("ascii")) 

470 

471 def add_files( 

472 self, 

473 files: Sequence[Path | str], 

474 format: str = "", 

475 workers: int = 1, 

476 filter: Path | list[str] | set[str] | None = None, 

477 ) -> None: 

478 """ 

479 Adds sequences from multiple files to the SeqBank. 

480 

481 This method processes a list of file paths, downloading and adding sequences from each file to the SeqBank. 

482 It supports parallel processing and optional filtering of specific accessions. The `max` argument limits the number of files to process. 

483 

484 Args: 

485 files (list[str]): A list of file paths to process. 

486 max (int, optional): Maximum number of files to process. If set to 0, all files will be processed. Defaults to 0. 

487 format (str, optional): The format of the sequence files (e.g., "fasta", "fastq"). If not provided, it will be auto-detected. Defaults to "". 

488 workers (int, optional): Number of workers to use for parallel processing. Defaults to 1. 

489 filter (Path | list[str] | set[str] | None, None], optional): A filter for selecting specific accessions. Defaults to None. 

490 

491 Returns: 

492 None 

493 """ 

494 filter = parse_filter(filter) 

495 

496 with Progress(*Progress.get_default_columns(), TimeElapsedColumn(), MofNCompleteColumn()) as progress: 

497 parallel = Parallel(n_jobs=workers, prefer="threads") 

498 add_file = delayed(self.add_file) 

499 overall_task = progress.add_task(f"[bold red]Adding files", total=len(files)) 

500 parallel( 

501 add_file(file, progress=progress, format=format, overall_task=overall_task, filter=filter) 

502 for file in files 

503 ) 

504 

505 def copy(self, other: "SeqBank") -> None: 

506 """ 

507 Copies all entries from the current SeqBank to another SeqBank instance. 

508 

509 This method iterates over all key-value pairs in the current SeqBank and adds them to the `other` SeqBank instance. 

510 The `other` SeqBank must be writable. 

511 

512 Args: 

513 other (SeqBank): The target SeqBank instance where entries will be copied. 

514 

515 Returns: 

516 None 

517 """ 

518 # Bound batches by payload size as sequence lengths vary considerably. 

519 batch, size = [], 0 

520 for k, v in track(self.file.items()): 

521 batch.append((k, v)) 

522 size += len(k) + len(v) 

523 if size >= 8 * 1024 * 1024 or len(batch) >= 1000: 

524 other.file.put_many(batch) 

525 batch, size = [], 0 

526 if batch: 

527 other.file.put_many(batch) 

528 else: 

529 # Create even an empty destination bank. 

530 other.file 

531 

532 def numpy(self, accession: str) -> np.ndarray: 

533 """ 

534 Retrieves the sequence data for a given accession and returns it as an unsigned char NumPy array. 

535 

536 Args: 

537 accession (str): The accession key for which the sequence data is retrieved. 

538 

539 Returns: 

540 np.ndarray: The sequence data associated with the given accession, represented as an unsigned char NumPy array. 

541 """ 

542 return np.frombuffer(self[accession], dtype="u1") 

543 

544 def string(self, accession: str) -> str: 

545 """ 

546 Retrieves the sequence data for a given accession and returns it as a string. 

547 

548 Args: 

549 accession (str): The accession key for which the sequence data is retrieved. 

550 

551 Returns: 

552 str: The sequence data associated with the given accession, represented as a string. 

553 """ 

554 data = self[accession] 

555 return bytes_to_str(data) 

556 

557 def record(self, accession: str) -> SeqRecord: 

558 """ 

559 Retrieves the sequence data for a given accession and returns it as a BioPython SeqRecord object. 

560 

561 Args: 

562 accession (str): The accession key for which the sequence data is retrieved. 

563 

564 Returns: 

565 SeqRecord: A BioPython SeqRecord object containing the sequence data, with the given accession as its ID and an empty description. 

566 """ 

567 record = SeqRecord( 

568 Seq(self.string(accession)), 

569 id=accession, 

570 description="", 

571 ) 

572 return record 

573 

574 def export(self, output: Path | str, format: str = "", accessions: list[str] | str | Path | None = None) -> None: 

575 """ 

576 Exports the data from the SeqBank to a file using BioPython's SeqIO. 

577 

578 Args: 

579 output (Path | str): The path or filename where the data should be exported. 

580 format (str, optional): The file format for exporting. If not specified, it will be inferred from the file extension. 

581 accessions (list[str] | str | Path | None, optional): A list of accessions to export. If a file path or string is provided, it will be read to obtain the list of accessions. If None, all accessions in the SeqBank are exported. 

582 

583 Returns: 

584 None 

585 """ 

586 selected = accessions or self.get_accessions() 

587 

588 # Read list of accessions if given file 

589 if isinstance(selected, (str, Path)): 

590 selected = Path(selected).read_text().strip().split("\n") 

591 

592 format = format or get_file_format(output) 

593 with open(output, "w") as f: 

594 for accession in selected: 

595 SeqIO.write(self.record(accession), f, format) 

596 

597 def lengths_dict(self) -> dict[str, int]: 

598 """ 

599 Returns a dictionary where the keys are the accessions and the values 

600 are the corresponding lengths of each sequence. 

601 

602 Returns: 

603 dict[str, int]: A dictionary mapping each accession to the length of its corresponding sequence. 

604 """ 

605 accession_lengths = {} 

606 

607 for accession in self.get_accessions(): 

608 # Retrieve the sequence 

609 sequence = self[accession] 

610 # Store the length of the sequence in the dictionary 

611 accession_lengths[accession] = len(sequence) 

612 

613 return accession_lengths 

614 

615 def histogram(self, nbins: int = 30, max: int = 0, min: int = 0) -> go.Figure: 

616 """ 

617 Creates a histogram of the lengths of all sequences and returns the Plotly figure object. 

618 

619 Args: 

620 nbins (int): The number of bins for the histogram. Default is 30. 

621 max (int): The maximum length of the sequence to include in the histogram. Default is all. 

622 min (int): The minimum length of the sequence to include in the histogram. Default is 0. 

623 

624 Returns: 

625 go.Figure: A Plotly figure object representing the histogram of sequence lengths. 

626 """ 

627 # Get the dictionary of accession lengths 

628 accession_lengths = self.lengths_dict() 

629 

630 # Extract the lengths from the dictionary 

631 lengths = np.array(list(accession_lengths.values())) 

632 

633 if max: 

634 lengths = lengths[lengths <= max] 

635 if min: 

636 lengths = lengths[lengths >= min] 

637 

638 # Create the histogram using Plotly Express 

639 fig = px.histogram(lengths, nbins=nbins, title="Histogram of Sequence Lengths") 

640 

641 # Add labels and customize the layout, removing the legend 

642 fig.update_layout(xaxis_title="Sequence Length", yaxis_title="Count", showlegend=False) # Remove the legend 

643 

644 format_fig(fig) 

645 

646 return fig