seqmat 1.1.0__tar.gz → 1.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {seqmat-1.1.0/seqmat.egg-info → seqmat-1.2.0}/PKG-INFO +3 -17
  2. {seqmat-1.1.0 → seqmat-1.2.0}/README.md +2 -15
  3. {seqmat-1.1.0 → seqmat-1.2.0}/requirements.txt +0 -1
  4. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat/__init__.py +1 -1
  5. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat/seqmat.py +53 -8
  6. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat/transcript.py +56 -17
  7. {seqmat-1.1.0 → seqmat-1.2.0/seqmat.egg-info}/PKG-INFO +3 -17
  8. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat.egg-info/SOURCES.txt +1 -0
  9. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat.egg-info/requires.txt +0 -1
  10. {seqmat-1.1.0 → seqmat-1.2.0}/setup.py +1 -2
  11. seqmat-1.2.0/tests/bench_gene_creation.py +130 -0
  12. {seqmat-1.1.0 → seqmat-1.2.0}/LICENSE +0 -0
  13. {seqmat-1.1.0 → seqmat-1.2.0}/MANIFEST.in +0 -0
  14. {seqmat-1.1.0 → seqmat-1.2.0}/examples/basic_usage.py +0 -0
  15. {seqmat-1.1.0 → seqmat-1.2.0}/examples/data_inspection.py +0 -0
  16. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat/cli.py +0 -0
  17. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat/config.py +0 -0
  18. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat/gene.py +0 -0
  19. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat/lmdb_store.py +0 -0
  20. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat/sqlite_store.py +0 -0
  21. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat/utils.py +0 -0
  22. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat.egg-info/dependency_links.txt +0 -0
  23. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat.egg-info/entry_points.txt +0 -0
  24. {seqmat-1.1.0 → seqmat-1.2.0}/seqmat.egg-info/top_level.txt +0 -0
  25. {seqmat-1.1.0 → seqmat-1.2.0}/setup.cfg +0 -0
  26. {seqmat-1.1.0 → seqmat-1.2.0}/tests/__init__.py +0 -0
  27. {seqmat-1.1.0 → seqmat-1.2.0}/tests/test_gene.py +0 -0
  28. {seqmat-1.1.0 → seqmat-1.2.0}/tests/test_seqmat.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: seqmat
3
- Version: 1.1.0
3
+ Version: 1.2.0
4
4
  Summary: Lightning-fast gene manipulation and analysis library.
5
5
  Home-page: https://github.com/nicolasalynn/seqmat
6
6
  Author: Nicolas Lynn Vila
@@ -22,7 +22,6 @@ Requires-Dist: pyarrow>=15.0.0
22
22
  Requires-Dist: pysam>=0.19.0
23
23
  Requires-Dist: requests>=2.26.0
24
24
  Requires-Dist: tqdm>=4.62.0
25
- Requires-Dist: biopython>=1.79
26
25
  Requires-Dist: platformdirs>=3.0.0
27
26
  Provides-Extra: lmdb
28
27
  Requires-Dist: lmdb>=1.4.0; extra == "lmdb"
@@ -77,18 +76,6 @@ seqmat setup
77
76
 
78
77
  This downloads prebuilt data (genes.db + FASTA) from SeqMat's S3 bucket into a dedicated directory on your machine. No config file is required: the installer can add `SEQMAT_DATA_DIR` to your shell config so SeqMat finds the data in future sessions.
79
78
 
80
- ### With Bioinformatics Features
81
- ```bash
82
- # For protein translation
83
- pip install seqmat[bio]
84
-
85
- # For GTF parsing and genomics data setup
86
- pip install seqmat[genomics]
87
-
88
- # Install everything
89
- pip install seqmat[all]
90
- ```
91
-
92
79
  ### From Source
93
80
  ```bash
94
81
  git clone https://github.com/yourusername/seqmat.git
@@ -218,7 +205,7 @@ print(f"Introns: {len(transcript.introns)}")
218
205
  transcript.generate_mature_mrna()
219
206
  print(f"Mature mRNA length: {len(transcript.mature_mrna)} bp")
220
207
 
221
- # Generate protein (if protein-coding and BioPython available)
208
+ # Generate protein (if protein-coding)
222
209
  if transcript.protein_coding:
223
210
  protein = transcript.generate_protein()
224
211
  print(f"Protein length: {len(transcript.protein)} aa")
@@ -661,7 +648,7 @@ $ seqmat summary
661
648
 
662
649
  - `generate_pre_mrna()`: Create pre-mRNA sequence
663
650
  - `generate_mature_mrna()`: Create spliced mRNA
664
- - `generate_protein()`: Translate to protein (requires BioPython)
651
+ - `generate_protein()`: Translate to protein
665
652
  - `exons`/`introns`: Genomic coordinates
666
653
  - `protein_coding`: Boolean flag
667
654
 
@@ -747,7 +734,6 @@ SeqMat is optimized for performance:
747
734
  - tqdm >= 4.62.0
748
735
 
749
736
  **Optional:**
750
- - biopython >= 1.79 (for protein translation)
751
737
  - gtfparse >= 1.2.0 (for genomics data setup)
752
738
  - pyarrow >= 14 (included; used for parquet export in `save_seqmat`)
753
739
 
@@ -31,18 +31,6 @@ seqmat setup
31
31
 
32
32
  This downloads prebuilt data (genes.db + FASTA) from SeqMat's S3 bucket into a dedicated directory on your machine. No config file is required: the installer can add `SEQMAT_DATA_DIR` to your shell config so SeqMat finds the data in future sessions.
33
33
 
34
- ### With Bioinformatics Features
35
- ```bash
36
- # For protein translation
37
- pip install seqmat[bio]
38
-
39
- # For GTF parsing and genomics data setup
40
- pip install seqmat[genomics]
41
-
42
- # Install everything
43
- pip install seqmat[all]
44
- ```
45
-
46
34
  ### From Source
47
35
  ```bash
48
36
  git clone https://github.com/yourusername/seqmat.git
@@ -172,7 +160,7 @@ print(f"Introns: {len(transcript.introns)}")
172
160
  transcript.generate_mature_mrna()
173
161
  print(f"Mature mRNA length: {len(transcript.mature_mrna)} bp")
174
162
 
175
- # Generate protein (if protein-coding and BioPython available)
163
+ # Generate protein (if protein-coding)
176
164
  if transcript.protein_coding:
177
165
  protein = transcript.generate_protein()
178
166
  print(f"Protein length: {len(transcript.protein)} aa")
@@ -615,7 +603,7 @@ $ seqmat summary
615
603
 
616
604
  - `generate_pre_mrna()`: Create pre-mRNA sequence
617
605
  - `generate_mature_mrna()`: Create spliced mRNA
618
- - `generate_protein()`: Translate to protein (requires BioPython)
606
+ - `generate_protein()`: Translate to protein
619
607
  - `exons`/`introns`: Genomic coordinates
620
608
  - `protein_coding`: Boolean flag
621
609
 
@@ -701,7 +689,6 @@ SeqMat is optimized for performance:
701
689
  - tqdm >= 4.62.0
702
690
 
703
691
  **Optional:**
704
- - biopython >= 1.79 (for protein translation)
705
692
  - gtfparse >= 1.2.0 (for genomics data setup)
706
693
  - pyarrow >= 14 (included; used for parquet export in `save_seqmat`)
707
694
 
@@ -5,5 +5,4 @@ pyarrow>=15.0.0
5
5
  pysam>=0.19.0
6
6
  requests>=2.26.0
7
7
  tqdm>=4.62.0
8
- biopython>=1.79
9
8
  platformdirs>=3.0.0
@@ -5,7 +5,7 @@ A comprehensive Python library for genomic sequence analysis with full mutation
5
5
  splicing analysis, and sequence manipulation.
6
6
  """
7
7
 
8
- __version__ = "1.1.0"
8
+ __version__ = "1.2.0"
9
9
  __author__ = "Nicolas Lynn Vila"
10
10
  __email__ = "nicolasalynn@gmail.com"
11
11
 
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
9
9
 
10
10
  import numpy as np
11
11
  import pysam
12
+ from functools import lru_cache
12
13
 
13
14
  if TYPE_CHECKING:
14
15
  import pandas as pd
@@ -18,6 +19,13 @@ from .config import get_organism_config
18
19
  Mutation = Tuple[int, str, str]
19
20
 
20
21
 
22
+ @lru_cache(maxsize=8)
23
+ def _fetch_fasta_region(fasta_path: str, chrom: str, start: int, end: int) -> str:
24
+ """Cached FASTA region fetch. start is 1-based, end is inclusive."""
25
+ fasta = pysam.FastaFile(fasta_path)
26
+ return fasta.fetch(chrom, start - 1, end).upper()
27
+
28
+
21
29
  def contains(array: Union[np.ndarray, List], value: Any) -> bool:
22
30
  """Return whether value is in array or list."""
23
31
  if isinstance(array, np.ndarray):
@@ -40,6 +48,7 @@ class SeqMat:
40
48
  mutated_positions: set[int] = field(default_factory=set, init=False, repr=False)
41
49
  rev: bool = field(default=False, init=False, repr=False)
42
50
  predicted_splicing: Optional["pd.DataFrame"] = field(default=None, init=False, repr=False)
51
+ _cow: bool = field(default=False, init=False, repr=False)
43
52
 
44
53
  def __init__(
45
54
  self,
@@ -62,6 +71,7 @@ class SeqMat:
62
71
  self.notes = notes or {}
63
72
  self.rev = rev
64
73
  self.predicted_splicing = None
74
+ self._cow = False
65
75
  self.insertions = defaultdict(list)
66
76
  self.mutations = []
67
77
  self.mutated_positions = set()
@@ -159,16 +169,14 @@ class SeqMat:
159
169
  f"or provide per-chromosome files in CHROM_SOURCE. Run setup_genomics_data() or set_fasta_path()."
160
170
  )
161
171
 
162
- fasta = pysam.FastaFile(str(source_fasta))
163
- seq = fasta.fetch(f'{chrom}', start-1, end).upper()
172
+ seq = _fetch_fasta_region(str(source_fasta), chrom, start, end)
164
173
  indices = np.arange(start, end+1, dtype=np.int64)
165
174
  return cls(nucleotides=seq, indices=indices, name=f"{chrom}:{start}-{end}", source=genome, **kwargs)
166
175
 
167
176
  @classmethod
168
177
  def from_fasta_file(cls, fasta_path: Union[str, Path], chrom: str, start: int, end: int, **kwargs) -> SeqMat:
169
178
  """Load a genomic interval directly from a FASTA file path"""
170
- fasta = pysam.FastaFile(str(fasta_path))
171
- seq = fasta.fetch(chrom, start-1, end).upper()
179
+ seq = _fetch_fasta_region(str(fasta_path), chrom, start, end)
172
180
  indices = np.arange(start, end+1, dtype=np.int64)
173
181
  return cls(nucleotides=seq, indices=indices, name=f"{chrom}:{start}-{end}", **kwargs)
174
182
 
@@ -220,6 +228,7 @@ class SeqMat:
220
228
 
221
229
  def _refresh_mutation_state(self) -> None:
222
230
  """Update mutation tracking based on current state."""
231
+ self._ensure_writable()
223
232
  # Clear
224
233
  self.seq_array['mut_type'] = b''
225
234
  self.mutated_positions.clear()
@@ -231,14 +240,38 @@ class SeqMat:
231
240
  for pos in self.insertions:
232
241
  self.mutated_positions.add(pos)
233
242
 
243
+ def _ensure_writable(self) -> None:
244
+ """Copy seq_array if it is shared via copy-on-write."""
245
+ if self._cow:
246
+ self.seq_array = self.seq_array.copy()
247
+ self._cow = False
248
+
249
+ def __deepcopy__(self, memo: dict) -> SeqMat:
250
+ """COW-aware deep copy — shares seq_array, copies on first write."""
251
+ new = object.__new__(type(self))
252
+ new.name = self.name
253
+ new.version = self.version
254
+ new.source = self.source
255
+ new.notes = copy.deepcopy(self.notes, memo)
256
+ new.rev = self.rev
257
+ new.predicted_splicing = copy.deepcopy(self.predicted_splicing, memo)
258
+ new.insertions = copy.deepcopy(self.insertions, memo)
259
+ new.mutations = copy.deepcopy(self.mutations, memo)
260
+ new.mutated_positions = set(self.mutated_positions)
261
+ # COW: share seq_array
262
+ new.seq_array = self.seq_array
263
+ new._cow = True
264
+ self._cow = True
265
+ return new
266
+
234
267
  def clone(self, start: Optional[int] = None, end: Optional[int] = None) -> SeqMat:
235
268
  """
236
269
  Create a copy of this SeqMat, optionally sliced to a specific range.
237
-
270
+
238
271
  Args:
239
272
  start: Start position (genomic coordinate)
240
273
  end: End position (genomic coordinate)
241
-
274
+
242
275
  Returns:
243
276
  A new SeqMat object
244
277
  """
@@ -252,8 +285,12 @@ class SeqMat:
252
285
  hi = end or self.index.max()
253
286
  mask = (self.seq_array['index'] >= lo) & (self.seq_array['index'] <= hi)
254
287
  new.seq_array = self.seq_array[mask].copy()
288
+ new._cow = False
255
289
  else:
256
- new.seq_array = self.seq_array.copy()
290
+ # COW: share seq_array, copy on first write
291
+ new.seq_array = self.seq_array
292
+ new._cow = True
293
+ self._cow = True
257
294
  return new
258
295
 
259
296
  def __getitem__(
@@ -370,6 +407,8 @@ class SeqMat:
370
407
  if not self._validate_mutation_batch(mutations):
371
408
  return self
372
409
 
410
+ self._ensure_writable()
411
+
373
412
  # Track original strand state
374
413
  was_on_negative_strand = self.rev
375
414
 
@@ -462,6 +501,7 @@ class SeqMat:
462
501
  """
463
502
  if copy:
464
503
  new = self.clone()
504
+ new._ensure_writable()
465
505
  # Use a temporary placeholder to avoid double replacement
466
506
  temp_array = new.seq_array['nt'].copy()
467
507
  temp_array[new.seq_array['nt'] == b'A'] = b'T'
@@ -473,6 +513,7 @@ class SeqMat:
473
513
  return new
474
514
  else:
475
515
  # In-place modification
516
+ self._ensure_writable()
476
517
  temp_array = self.seq_array['nt'].copy()
477
518
  temp_array[self.seq_array['nt'] == b'A'] = b'T'
478
519
  temp_array[self.seq_array['nt'] == b'T'] = b'A'
@@ -494,6 +535,7 @@ class SeqMat:
494
535
  """
495
536
  if copy:
496
537
  new = self.clone()
538
+ new._ensure_writable()
497
539
  # Apply complement mapping using temporary array
498
540
  temp_array = new.seq_array['nt'].copy()
499
541
  temp_array[new.seq_array['nt'] == b'A'] = b'T'
@@ -501,13 +543,14 @@ class SeqMat:
501
543
  temp_array[new.seq_array['nt'] == b'C'] = b'G'
502
544
  temp_array[new.seq_array['nt'] == b'G'] = b'C'
503
545
  new.seq_array['nt'] = temp_array
504
-
546
+
505
547
  # Reverse the sequence
506
548
  new.seq_array = new.seq_array[::-1].copy()
507
549
  new.rev = not new.rev
508
550
  return new
509
551
  else:
510
552
  # In-place modification
553
+ self._ensure_writable()
511
554
  # Apply complement mapping in place using temporary array
512
555
  temp_array = self.seq_array['nt'].copy()
513
556
  temp_array[self.seq_array['nt'] == b'A'] = b'T'
@@ -582,6 +625,7 @@ class SeqMat:
582
625
  the current nucleotides (nt) and reference info.
583
626
  This means the current sequence becomes the new baseline.
584
627
  """
628
+ self._ensure_writable()
585
629
  # Clear existing mutation annotations
586
630
  self.seq_array['ref'] = self.seq_array['nt'] # new reference = current nt
587
631
  self.seq_array['mut_type'] = b'' # clear mutation type
@@ -685,6 +729,7 @@ class SeqMat:
685
729
  obj.insertions = dl
686
730
  obj.mutations = list(mut_list) if isinstance(mut_list, (list, tuple)) else []
687
731
  obj.mutated_positions = mutated_positions
732
+ obj._cow = False
688
733
 
689
734
  # Keep slots that are not persisted explicitly in a clean state
690
735
  # (no additional refresh needed; seq_array already contains nt/ref/valid/mut_type)
@@ -7,11 +7,32 @@ from typing import Any, Dict, List, Optional, Tuple, Union
7
7
 
8
8
  import numpy as np
9
9
 
10
- try:
11
- from Bio.Seq import Seq
12
- BIOPYTHON_AVAILABLE = True
13
- except ImportError:
14
- BIOPYTHON_AVAILABLE = False
10
+ _CODON_TABLE = {
11
+ 'TTT': 'F', 'TTC': 'F', 'TTA': 'L', 'TTG': 'L',
12
+ 'CTT': 'L', 'CTC': 'L', 'CTA': 'L', 'CTG': 'L',
13
+ 'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'ATG': 'M',
14
+ 'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V',
15
+ 'TCT': 'S', 'TCC': 'S', 'TCA': 'S', 'TCG': 'S',
16
+ 'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P',
17
+ 'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T',
18
+ 'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A',
19
+ 'TAT': 'Y', 'TAC': 'Y', 'TAA': '*', 'TAG': '*',
20
+ 'CAT': 'H', 'CAC': 'H', 'CAA': 'Q', 'CAG': 'Q',
21
+ 'AAT': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K',
22
+ 'GAT': 'D', 'GAC': 'D', 'GAA': 'E', 'GAG': 'E',
23
+ 'TGT': 'C', 'TGC': 'C', 'TGA': '*', 'TGG': 'W',
24
+ 'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R',
25
+ 'AGT': 'S', 'AGC': 'S', 'AGA': 'R', 'AGG': 'R',
26
+ 'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G',
27
+ }
28
+
29
+
30
+ def _translate(seq: str) -> str:
31
+ """Translate a nucleotide sequence to protein using the standard codon table."""
32
+ seq = seq.upper()
33
+ # Trim to multiple of 3 (avoids partial-codon warnings)
34
+ trimmed = seq[:len(seq) - len(seq) % 3] if len(seq) % 3 else seq
35
+ return ''.join(_CODON_TABLE.get(trimmed[i:i+3], 'X') for i in range(0, len(trimmed), 3))
15
36
 
16
37
  from .seqmat import SeqMat
17
38
  from .config import get_organism_config, get_default_organism
@@ -195,6 +216,8 @@ class Transcript:
195
216
  fasta_path: Optional[Path] = None,
196
217
  upstream: int = 0,
197
218
  downstream: int = 0,
219
+ region_start: Optional[int] = None,
220
+ region_end: Optional[int] = None,
198
221
  ) -> Dict[str, Any]:
199
222
  """Pre-mRNA sequence from the single full-genome FASTA (e.g. hg38.fa). Optional upstream/downstream."""
200
223
  if fasta_path is None:
@@ -214,8 +237,12 @@ class Transcript:
214
237
  raw_chr = str(self.chrm).replace("chr", "") or "17"
215
238
  with_chr = f"chr{raw_chr}"
216
239
  contigs_to_try = [with_chr, raw_chr] if with_chr != raw_chr else [with_chr]
217
- start = max(1, self.transcript_lower - upstream)
218
- end = self.transcript_upper + downstream
240
+ if region_start is not None or region_end is not None:
241
+ start = region_start if region_start is not None else max(1, self.transcript_lower - upstream)
242
+ end = region_end if region_end is not None else (self.transcript_upper + downstream)
243
+ else:
244
+ start = max(1, self.transcript_lower - upstream)
245
+ end = self.transcript_upper + downstream
219
246
  last_err = None
220
247
  for contig in contigs_to_try:
221
248
  try:
@@ -232,15 +259,31 @@ class Transcript:
232
259
  self,
233
260
  upstream: int = 0,
234
261
  downstream: int = 0,
262
+ region_start: Optional[int] = None,
263
+ region_end: Optional[int] = None,
235
264
  ) -> "Transcript":
236
- """Load pre-mRNA and set self.pre_mrna. Use upstream/downstream to add flanking (bp)."""
265
+ """Load pre-mRNA and set self.pre_mrna. Use upstream/downstream to add flanking (bp).
266
+
267
+ Optional region_start/region_end restrict the FASTA read to a genomic
268
+ sub-interval (e.g. ±7500 bp around a mutation site) instead of fetching
269
+ the entire transcript, which can be orders of magnitude faster for large
270
+ genes.
271
+ """
237
272
  try:
238
- seq_data = self.pull_pre_mrna_from_fasta(upstream=upstream, downstream=downstream)
273
+ seq_data = self.pull_pre_mrna_from_fasta(
274
+ upstream=upstream, downstream=downstream,
275
+ region_start=region_start, region_end=region_end,
276
+ )
239
277
  pre_mrna = SeqMat(**seq_data)
240
278
  except Exception:
241
- length = self.transcript_upper - self.transcript_lower + 1 + upstream + downstream
242
- start = max(1, self.transcript_lower - upstream)
243
- indices = np.arange(start, start + length)
279
+ if region_start is not None or region_end is not None:
280
+ lo = region_start if region_start is not None else max(1, self.transcript_lower - upstream)
281
+ hi = region_end if region_end is not None else (self.transcript_upper + downstream)
282
+ else:
283
+ lo = max(1, self.transcript_lower - upstream)
284
+ hi = self.transcript_upper + downstream
285
+ length = hi - lo + 1
286
+ indices = np.arange(lo, lo + length)
244
287
  pre_mrna = SeqMat("N" * length, indices=indices)
245
288
  if self.rev:
246
289
  pre_mrna.reverse_complement()
@@ -309,14 +352,10 @@ class Transcript:
309
352
  if not self.protein_coding:
310
353
  return self if inplace else ""
311
354
 
312
- if not BIOPYTHON_AVAILABLE:
313
- print("BioPython not available. Cannot translate to protein.")
314
- return self if inplace else ""
315
-
316
355
  # Translate the ORF to protein
317
356
  orf_seq = self.orf
318
357
  if isinstance(orf_seq, SeqMat):
319
- protein = str(Seq(orf_seq.seq).translate()).strip('*')
358
+ protein = _translate(orf_seq.seq).strip('*')
320
359
  else:
321
360
  protein = ""
322
361
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: seqmat
3
- Version: 1.1.0
3
+ Version: 1.2.0
4
4
  Summary: Lightning-fast gene manipulation and analysis library.
5
5
  Home-page: https://github.com/nicolasalynn/seqmat
6
6
  Author: Nicolas Lynn Vila
@@ -22,7 +22,6 @@ Requires-Dist: pyarrow>=15.0.0
22
22
  Requires-Dist: pysam>=0.19.0
23
23
  Requires-Dist: requests>=2.26.0
24
24
  Requires-Dist: tqdm>=4.62.0
25
- Requires-Dist: biopython>=1.79
26
25
  Requires-Dist: platformdirs>=3.0.0
27
26
  Provides-Extra: lmdb
28
27
  Requires-Dist: lmdb>=1.4.0; extra == "lmdb"
@@ -77,18 +76,6 @@ seqmat setup
77
76
 
78
77
  This downloads prebuilt data (genes.db + FASTA) from SeqMat's S3 bucket into a dedicated directory on your machine. No config file is required: the installer can add `SEQMAT_DATA_DIR` to your shell config so SeqMat finds the data in future sessions.
79
78
 
80
- ### With Bioinformatics Features
81
- ```bash
82
- # For protein translation
83
- pip install seqmat[bio]
84
-
85
- # For GTF parsing and genomics data setup
86
- pip install seqmat[genomics]
87
-
88
- # Install everything
89
- pip install seqmat[all]
90
- ```
91
-
92
79
  ### From Source
93
80
  ```bash
94
81
  git clone https://github.com/yourusername/seqmat.git
@@ -218,7 +205,7 @@ print(f"Introns: {len(transcript.introns)}")
218
205
  transcript.generate_mature_mrna()
219
206
  print(f"Mature mRNA length: {len(transcript.mature_mrna)} bp")
220
207
 
221
- # Generate protein (if protein-coding and BioPython available)
208
+ # Generate protein (if protein-coding)
222
209
  if transcript.protein_coding:
223
210
  protein = transcript.generate_protein()
224
211
  print(f"Protein length: {len(transcript.protein)} aa")
@@ -661,7 +648,7 @@ $ seqmat summary
661
648
 
662
649
  - `generate_pre_mrna()`: Create pre-mRNA sequence
663
650
  - `generate_mature_mrna()`: Create spliced mRNA
664
- - `generate_protein()`: Translate to protein (requires BioPython)
651
+ - `generate_protein()`: Translate to protein
665
652
  - `exons`/`introns`: Genomic coordinates
666
653
  - `protein_coding`: Boolean flag
667
654
 
@@ -747,7 +734,6 @@ SeqMat is optimized for performance:
747
734
  - tqdm >= 4.62.0
748
735
 
749
736
  **Optional:**
750
- - biopython >= 1.79 (for protein translation)
751
737
  - gtfparse >= 1.2.0 (for genomics data setup)
752
738
  - pyarrow >= 14 (included; used for parquet export in `save_seqmat`)
753
739
 
@@ -21,5 +21,6 @@ seqmat.egg-info/entry_points.txt
21
21
  seqmat.egg-info/requires.txt
22
22
  seqmat.egg-info/top_level.txt
23
23
  tests/__init__.py
24
+ tests/bench_gene_creation.py
24
25
  tests/test_gene.py
25
26
  tests/test_seqmat.py
@@ -4,7 +4,6 @@ pyarrow>=15.0.0
4
4
  pysam>=0.19.0
5
5
  requests>=2.26.0
6
6
  tqdm>=4.62.0
7
- biopython>=1.79
8
7
  platformdirs>=3.0.0
9
8
 
10
9
  [dev]
@@ -8,7 +8,7 @@ long_description = (this_directory / "README.md").read_text()
8
8
 
9
9
  setup(
10
10
  name="seqmat",
11
- version="1.1.0",
11
+ version="1.2.0",
12
12
  author="Nicolas Lynn Vila",
13
13
  author_email="nicolasalynn@gmail.com",
14
14
  description="Lightning-fast gene manipulation and analysis library.",
@@ -34,7 +34,6 @@ setup(
34
34
  "pysam>=0.19.0",
35
35
  "requests>=2.26.0",
36
36
  "tqdm>=4.62.0",
37
- "biopython>=1.79",
38
37
  "platformdirs>=3.0.0",
39
38
  ],
40
39
  extras_require={
@@ -0,0 +1,130 @@
1
+ """Benchmark: Gene + Transcript creation throughput.
2
+
3
+ Measures the time to load a gene, pull pre-mRNA, generate mature mRNA,
4
+ and translate to protein for clinically important genes.
5
+
6
+ Usage:
7
+ python tests/bench_gene_creation.py
8
+ python tests/bench_gene_creation.py --genes TP53 BRCA1 --iterations 50
9
+ """
10
+ import argparse
11
+ import statistics
12
+ import time
13
+ from typing import Dict, List, Tuple
14
+
15
+ from seqmat import Gene
16
+
17
+ DEFAULT_GENES = ["TP53", "BRCA1", "BRCA2", "EGFR", "KRAS", "BRAF", "PIK3CA", "APC", "PTEN", "MYC"]
18
+ DEFAULT_ITERATIONS = 100
19
+
20
+
21
+ def bench_full_pipeline(gene_name: str, iterations: int) -> Dict[str, List[float]]:
22
+ """Time each stage of the gene→transcript→protein pipeline."""
23
+ timings: Dict[str, List[float]] = {
24
+ "from_file": [],
25
+ "generate_pre_mrna": [],
26
+ "generate_mature_mrna": [],
27
+ "generate_protein": [],
28
+ "total": [],
29
+ }
30
+
31
+ # Warm-up (1 call to prime caches / FASTA index)
32
+ g = Gene.from_file(gene_name)
33
+ if g is None:
34
+ print(f" SKIP {gene_name}: not found in data")
35
+ return timings
36
+ t = g.transcript()
37
+ if t is None:
38
+ print(f" SKIP {gene_name}: no primary transcript")
39
+ return timings
40
+ t.generate_mature_mrna()
41
+ t.generate_protein()
42
+
43
+ for _ in range(iterations):
44
+ t0 = time.perf_counter()
45
+
46
+ t1 = time.perf_counter()
47
+ g = Gene.from_file(gene_name)
48
+ t2 = time.perf_counter()
49
+ timings["from_file"].append(t2 - t1)
50
+
51
+ # Transcript.__init__ already calls generate_pre_mrna
52
+ t3 = time.perf_counter()
53
+ tx = g.transcript()
54
+ t4 = time.perf_counter()
55
+ timings["generate_pre_mrna"].append(t4 - t3)
56
+
57
+ t5 = time.perf_counter()
58
+ tx.generate_mature_mrna()
59
+ t6 = time.perf_counter()
60
+ timings["generate_mature_mrna"].append(t6 - t5)
61
+
62
+ t7 = time.perf_counter()
63
+ tx.generate_protein()
64
+ t8 = time.perf_counter()
65
+ timings["generate_protein"].append(t8 - t7)
66
+
67
+ timings["total"].append(t8 - t0)
68
+
69
+ return timings
70
+
71
+
72
+ def fmt_ms(values: List[float]) -> Tuple[str, str, str]:
73
+ """Return (mean, median, stdev) formatted in ms."""
74
+ if not values:
75
+ return ("N/A", "N/A", "N/A")
76
+ ms = [v * 1000 for v in values]
77
+ mean = statistics.mean(ms)
78
+ med = statistics.median(ms)
79
+ sd = statistics.stdev(ms) if len(ms) > 1 else 0.0
80
+ return (f"{mean:.2f}", f"{med:.2f}", f"{sd:.2f}")
81
+
82
+
83
+ def main():
84
+ parser = argparse.ArgumentParser(description="Benchmark seqmat gene creation pipeline")
85
+ parser.add_argument("--genes", nargs="+", default=DEFAULT_GENES, help="Gene names to benchmark")
86
+ parser.add_argument("--iterations", "-n", type=int, default=DEFAULT_ITERATIONS, help="Iterations per gene")
87
+ args = parser.parse_args()
88
+
89
+ col_w = 14
90
+ stages = ["from_file", "generate_pre_mrna", "generate_mature_mrna", "generate_protein", "total"]
91
+ header_stages = ["load", "pre_mrna", "mature_mrna", "protein", "TOTAL"]
92
+
93
+ # Header
94
+ print(f"\nBenchmark: {args.iterations} iterations per gene\n")
95
+ print(f"{'Gene':<10}", end="")
96
+ for h in header_stages:
97
+ print(f" {h + ' (ms)':>{col_w}}", end="")
98
+ print()
99
+ print("-" * (10 + (col_w + 2) * len(stages)))
100
+
101
+ all_totals: List[float] = []
102
+
103
+ for gene_name in args.genes:
104
+ timings = bench_full_pipeline(gene_name, args.iterations)
105
+ if not timings["total"]:
106
+ continue
107
+ all_totals.extend(timings["total"])
108
+ print(f"{gene_name:<10}", end="")
109
+ for stage in stages:
110
+ mean, _, _ = fmt_ms(timings[stage])
111
+ print(f" {mean:>{col_w}}", end="")
112
+ print()
113
+
114
+ # Summary
115
+ if all_totals:
116
+ print("-" * (10 + (col_w + 2) * len(stages)))
117
+ ms_totals = [v * 1000 for v in all_totals]
118
+ n_genes = len([g for g in args.genes if any(True for _ in [])] or args.genes)
119
+ total_genes = len(args.genes)
120
+ print(f"\nOverall across {total_genes} genes x {args.iterations} iterations:")
121
+ print(f" Mean total: {statistics.mean(ms_totals):.2f} ms")
122
+ print(f" Median total: {statistics.median(ms_totals):.2f} ms")
123
+ print(f" Stdev: {statistics.stdev(ms_totals):.2f} ms")
124
+ print(f" Min: {min(ms_totals):.2f} ms")
125
+ print(f" Max: {max(ms_totals):.2f} ms")
126
+ print(f" Throughput: {1000 / statistics.mean(ms_totals):.1f} genes/sec")
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes