seqmat 1.1.1__tar.gz → 1.2.1__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.1/seqmat.egg-info → seqmat-1.2.1}/PKG-INFO +1 -1
  2. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat/__init__.py +1 -1
  3. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat/seqmat.py +97 -55
  4. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat/transcript.py +32 -23
  5. {seqmat-1.1.1 → seqmat-1.2.1/seqmat.egg-info}/PKG-INFO +1 -1
  6. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat.egg-info/SOURCES.txt +1 -0
  7. {seqmat-1.1.1 → seqmat-1.2.1}/setup.py +1 -1
  8. seqmat-1.2.1/tests/bench_gene_creation.py +130 -0
  9. {seqmat-1.1.1 → seqmat-1.2.1}/LICENSE +0 -0
  10. {seqmat-1.1.1 → seqmat-1.2.1}/MANIFEST.in +0 -0
  11. {seqmat-1.1.1 → seqmat-1.2.1}/README.md +0 -0
  12. {seqmat-1.1.1 → seqmat-1.2.1}/examples/basic_usage.py +0 -0
  13. {seqmat-1.1.1 → seqmat-1.2.1}/examples/data_inspection.py +0 -0
  14. {seqmat-1.1.1 → seqmat-1.2.1}/requirements.txt +0 -0
  15. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat/cli.py +0 -0
  16. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat/config.py +0 -0
  17. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat/gene.py +0 -0
  18. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat/lmdb_store.py +0 -0
  19. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat/sqlite_store.py +0 -0
  20. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat/utils.py +0 -0
  21. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat.egg-info/dependency_links.txt +0 -0
  22. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat.egg-info/entry_points.txt +0 -0
  23. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat.egg-info/requires.txt +0 -0
  24. {seqmat-1.1.1 → seqmat-1.2.1}/seqmat.egg-info/top_level.txt +0 -0
  25. {seqmat-1.1.1 → seqmat-1.2.1}/setup.cfg +0 -0
  26. {seqmat-1.1.1 → seqmat-1.2.1}/tests/__init__.py +0 -0
  27. {seqmat-1.1.1 → seqmat-1.2.1}/tests/test_gene.py +0 -0
  28. {seqmat-1.1.1 → seqmat-1.2.1}/tests/test_seqmat.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: seqmat
3
- Version: 1.1.1
3
+ Version: 1.2.1
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
@@ -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.1"
8
+ __version__ = "1.2.1"
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
@@ -17,6 +18,20 @@ from .config import get_organism_config
17
18
 
18
19
  Mutation = Tuple[int, str, str]
19
20
 
21
+ # Byte lookup table for complement: A<->T, C<->G, everything else identity
22
+ _COMPLEMENT_LUT = np.arange(256, dtype=np.uint8)
23
+ _COMPLEMENT_LUT[ord('A')] = ord('T')
24
+ _COMPLEMENT_LUT[ord('T')] = ord('A')
25
+ _COMPLEMENT_LUT[ord('C')] = ord('G')
26
+ _COMPLEMENT_LUT[ord('G')] = ord('C')
27
+
28
+
29
+ @lru_cache(maxsize=8)
30
+ def _fetch_fasta_region(fasta_path: str, chrom: str, start: int, end: int) -> str:
31
+ """Cached FASTA region fetch. start is 1-based, end is inclusive."""
32
+ fasta = pysam.FastaFile(fasta_path)
33
+ return fasta.fetch(chrom, start - 1, end).upper()
34
+
20
35
 
21
36
  def contains(array: Union[np.ndarray, List], value: Any) -> bool:
22
37
  """Return whether value is in array or list."""
@@ -40,6 +55,7 @@ class SeqMat:
40
55
  mutated_positions: set[int] = field(default_factory=set, init=False, repr=False)
41
56
  rev: bool = field(default=False, init=False, repr=False)
42
57
  predicted_splicing: Optional["pd.DataFrame"] = field(default=None, init=False, repr=False)
58
+ _cow: bool = field(default=False, init=False, repr=False)
43
59
 
44
60
  def __init__(
45
61
  self,
@@ -62,15 +78,16 @@ class SeqMat:
62
78
  self.notes = notes or {}
63
79
  self.rev = rev
64
80
  self.predicted_splicing = None
81
+ self._cow = False
65
82
  self.insertions = defaultdict(list)
66
83
  self.mutations = []
67
84
  self.mutated_positions = set()
68
85
 
69
86
  # Prepare sequence
70
87
  if isinstance(nucleotides, str):
71
- nts = np.array(list(nucleotides), dtype='S1')
88
+ nts = np.frombuffer(nucleotides.encode('ascii'), dtype='S1')
72
89
  else:
73
- nts = np.array(nucleotides, dtype='S1')
90
+ nts = np.asarray(nucleotides, dtype='S1')
74
91
  L = len(nts)
75
92
 
76
93
  # Indices default to 1-based
@@ -115,7 +132,6 @@ class SeqMat:
115
132
  arr['mut_type'] = b''
116
133
  arr['valid'] = arr['nt'] != b'-'
117
134
  self.seq_array = arr
118
- self._refresh_mutation_state()
119
135
 
120
136
  @classmethod
121
137
  def from_fasta(
@@ -159,16 +175,14 @@ class SeqMat:
159
175
  f"or provide per-chromosome files in CHROM_SOURCE. Run setup_genomics_data() or set_fasta_path()."
160
176
  )
161
177
 
162
- fasta = pysam.FastaFile(str(source_fasta))
163
- seq = fasta.fetch(f'{chrom}', start-1, end).upper()
178
+ seq = _fetch_fasta_region(str(source_fasta), chrom, start, end)
164
179
  indices = np.arange(start, end+1, dtype=np.int64)
165
180
  return cls(nucleotides=seq, indices=indices, name=f"{chrom}:{start}-{end}", source=genome, **kwargs)
166
181
 
167
182
  @classmethod
168
183
  def from_fasta_file(cls, fasta_path: Union[str, Path], chrom: str, start: int, end: int, **kwargs) -> SeqMat:
169
184
  """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()
185
+ seq = _fetch_fasta_region(str(fasta_path), chrom, start, end)
172
186
  indices = np.arange(start, end+1, dtype=np.int64)
173
187
  return cls(nucleotides=seq, indices=indices, name=f"{chrom}:{start}-{end}", **kwargs)
174
188
 
@@ -220,6 +234,7 @@ class SeqMat:
220
234
 
221
235
  def _refresh_mutation_state(self) -> None:
222
236
  """Update mutation tracking based on current state."""
237
+ self._ensure_writable()
223
238
  # Clear
224
239
  self.seq_array['mut_type'] = b''
225
240
  self.mutated_positions.clear()
@@ -231,14 +246,38 @@ class SeqMat:
231
246
  for pos in self.insertions:
232
247
  self.mutated_positions.add(pos)
233
248
 
249
+ def _ensure_writable(self) -> None:
250
+ """Copy seq_array if it is shared via copy-on-write."""
251
+ if self._cow:
252
+ self.seq_array = self.seq_array.copy()
253
+ self._cow = False
254
+
255
+ def __deepcopy__(self, memo: dict) -> SeqMat:
256
+ """COW-aware deep copy — shares seq_array, copies on first write."""
257
+ new = object.__new__(type(self))
258
+ new.name = self.name
259
+ new.version = self.version
260
+ new.source = self.source
261
+ new.notes = copy.deepcopy(self.notes, memo)
262
+ new.rev = self.rev
263
+ new.predicted_splicing = copy.deepcopy(self.predicted_splicing, memo)
264
+ new.insertions = copy.deepcopy(self.insertions, memo)
265
+ new.mutations = copy.deepcopy(self.mutations, memo)
266
+ new.mutated_positions = set(self.mutated_positions)
267
+ # COW: share seq_array
268
+ new.seq_array = self.seq_array
269
+ new._cow = True
270
+ self._cow = True
271
+ return new
272
+
234
273
  def clone(self, start: Optional[int] = None, end: Optional[int] = None) -> SeqMat:
235
274
  """
236
275
  Create a copy of this SeqMat, optionally sliced to a specific range.
237
-
276
+
238
277
  Args:
239
278
  start: Start position (genomic coordinate)
240
279
  end: End position (genomic coordinate)
241
-
280
+
242
281
  Returns:
243
282
  A new SeqMat object
244
283
  """
@@ -252,8 +291,12 @@ class SeqMat:
252
291
  hi = end or self.index.max()
253
292
  mask = (self.seq_array['index'] >= lo) & (self.seq_array['index'] <= hi)
254
293
  new.seq_array = self.seq_array[mask].copy()
294
+ new._cow = False
255
295
  else:
256
- new.seq_array = self.seq_array.copy()
296
+ # COW: share seq_array, copy on first write
297
+ new.seq_array = self.seq_array
298
+ new._cow = True
299
+ self._cow = True
257
300
  return new
258
301
 
259
302
  def __getitem__(
@@ -370,6 +413,8 @@ class SeqMat:
370
413
  if not self._validate_mutation_batch(mutations):
371
414
  return self
372
415
 
416
+ self._ensure_writable()
417
+
373
418
  # Track original strand state
374
419
  was_on_negative_strand = self.rev
375
420
 
@@ -450,73 +495,51 @@ class SeqMat:
450
495
  self.seq_array['valid'][mask] = False
451
496
  self.seq_array['mut_type'][mask] = b'del'
452
497
 
498
+ @staticmethod
499
+ def _complement_nt(nt_field: np.ndarray) -> np.ndarray:
500
+ """Complement nucleotide bytes via single-pass LUT (A<->T, C<->G)."""
501
+ return _COMPLEMENT_LUT[nt_field.view(np.uint8)].view('S1')
502
+
453
503
  def complement(self, copy: bool = False) -> SeqMat:
454
504
  """
455
505
  Complement the sequence (A<->T, C<->G) in-place or return a copy.
456
-
506
+
457
507
  Args:
458
508
  copy: If True, return a new SeqMat object instead of modifying in-place
459
-
509
+
460
510
  Returns:
461
511
  Self (for chaining) or new SeqMat if copy=True
462
512
  """
463
513
  if copy:
464
514
  new = self.clone()
465
- # Use a temporary placeholder to avoid double replacement
466
- temp_array = new.seq_array['nt'].copy()
467
- temp_array[new.seq_array['nt'] == b'A'] = b'T'
468
- temp_array[new.seq_array['nt'] == b'T'] = b'A'
469
- temp_array[new.seq_array['nt'] == b'C'] = b'G'
470
- temp_array[new.seq_array['nt'] == b'G'] = b'C'
471
- # N and - stay the same
472
- new.seq_array['nt'] = temp_array
515
+ new._ensure_writable()
516
+ new.seq_array['nt'] = self._complement_nt(new.seq_array['nt'])
473
517
  return new
474
518
  else:
475
- # In-place modification
476
- temp_array = self.seq_array['nt'].copy()
477
- temp_array[self.seq_array['nt'] == b'A'] = b'T'
478
- temp_array[self.seq_array['nt'] == b'T'] = b'A'
479
- temp_array[self.seq_array['nt'] == b'C'] = b'G'
480
- temp_array[self.seq_array['nt'] == b'G'] = b'C'
481
- # N and - stay the same
482
- self.seq_array['nt'] = temp_array
519
+ self._ensure_writable()
520
+ self.seq_array['nt'] = self._complement_nt(self.seq_array['nt'])
483
521
  return self
484
522
 
485
523
  def reverse_complement(self, copy: bool = False) -> SeqMat:
486
524
  """
487
525
  Reverse-complement the sequence in-place or return a copy.
488
-
526
+
489
527
  Args:
490
528
  copy: If True, return a new SeqMat object instead of modifying in-place
491
-
529
+
492
530
  Returns:
493
531
  Self (for chaining) or new SeqMat if copy=True
494
532
  """
495
533
  if copy:
496
534
  new = self.clone()
497
- # Apply complement mapping using temporary array
498
- temp_array = new.seq_array['nt'].copy()
499
- temp_array[new.seq_array['nt'] == b'A'] = b'T'
500
- temp_array[new.seq_array['nt'] == b'T'] = b'A'
501
- temp_array[new.seq_array['nt'] == b'C'] = b'G'
502
- temp_array[new.seq_array['nt'] == b'G'] = b'C'
503
- new.seq_array['nt'] = temp_array
504
-
505
- # Reverse the sequence
535
+ new._ensure_writable()
536
+ new.seq_array['nt'] = self._complement_nt(new.seq_array['nt'])
506
537
  new.seq_array = new.seq_array[::-1].copy()
507
538
  new.rev = not new.rev
508
539
  return new
509
540
  else:
510
- # In-place modification
511
- # Apply complement mapping in place using temporary array
512
- temp_array = self.seq_array['nt'].copy()
513
- temp_array[self.seq_array['nt'] == b'A'] = b'T'
514
- temp_array[self.seq_array['nt'] == b'T'] = b'A'
515
- temp_array[self.seq_array['nt'] == b'C'] = b'G'
516
- temp_array[self.seq_array['nt'] == b'G'] = b'C'
517
- self.seq_array['nt'] = temp_array
518
-
519
- # Reverse the sequence
541
+ self._ensure_writable()
542
+ self.seq_array['nt'] = self._complement_nt(self.seq_array['nt'])
520
543
  self.seq_array = self.seq_array[::-1].copy()
521
544
  self.rev = not self.rev
522
545
  return self
@@ -524,19 +547,36 @@ class SeqMat:
524
547
  def remove_regions(self, regions: List[Tuple[int, int]]) -> SeqMat:
525
548
  """
526
549
  Excise given genomic intervals (inclusive).
527
-
550
+
528
551
  Args:
529
552
  regions: List of (start, end) tuples to remove
530
-
553
+
531
554
  Returns:
532
555
  New SeqMat with regions removed
533
556
  """
534
557
  new = self.clone()
535
- mask = np.ones(len(new.seq_array), bool)
558
+ indices = new.seq_array['index']
559
+ n = len(indices)
560
+ remove = np.zeros(n, dtype=bool)
561
+
562
+ # Detect monotonic order for searchsorted fast path
563
+ ascending = n < 2 or indices[0] <= indices[-1]
564
+ if ascending:
565
+ sorted_idx = indices
566
+ else:
567
+ sorted_idx = indices[::-1] # view, no copy
568
+
536
569
  for lo, hi in regions:
537
- mask &= ~((new.seq_array['index'] >= min(lo, hi)) &
538
- (new.seq_array['index'] <= max(lo, hi)))
539
- new.seq_array = new.seq_array[mask].copy()
570
+ lo, hi = min(lo, hi), max(lo, hi)
571
+ i = np.searchsorted(sorted_idx, lo)
572
+ j = np.searchsorted(sorted_idx, hi, side='right')
573
+ if ascending:
574
+ remove[i:j] = True
575
+ else:
576
+ # Map back to original order
577
+ remove[n - j:n - i] = True
578
+
579
+ new.seq_array = new.seq_array[~remove].copy()
540
580
  return new
541
581
 
542
582
  def summary(self) -> str:
@@ -582,6 +622,7 @@ class SeqMat:
582
622
  the current nucleotides (nt) and reference info.
583
623
  This means the current sequence becomes the new baseline.
584
624
  """
625
+ self._ensure_writable()
585
626
  # Clear existing mutation annotations
586
627
  self.seq_array['ref'] = self.seq_array['nt'] # new reference = current nt
587
628
  self.seq_array['mut_type'] = b'' # clear mutation type
@@ -685,6 +726,7 @@ class SeqMat:
685
726
  obj.insertions = dl
686
727
  obj.mutations = list(mut_list) if isinstance(mut_list, (list, tuple)) else []
687
728
  obj.mutated_positions = mutated_positions
729
+ obj._cow = False
688
730
 
689
731
  # Keep slots that are not persisted explicitly in a clean state
690
732
  # (no additional refresh needed; seq_array already contains nt/ref/valid/mut_type)
@@ -216,6 +216,8 @@ class Transcript:
216
216
  fasta_path: Optional[Path] = None,
217
217
  upstream: int = 0,
218
218
  downstream: int = 0,
219
+ region_start: Optional[int] = None,
220
+ region_end: Optional[int] = None,
219
221
  ) -> Dict[str, Any]:
220
222
  """Pre-mRNA sequence from the single full-genome FASTA (e.g. hg38.fa). Optional upstream/downstream."""
221
223
  if fasta_path is None:
@@ -235,8 +237,12 @@ class Transcript:
235
237
  raw_chr = str(self.chrm).replace("chr", "") or "17"
236
238
  with_chr = f"chr{raw_chr}"
237
239
  contigs_to_try = [with_chr, raw_chr] if with_chr != raw_chr else [with_chr]
238
- start = max(1, self.transcript_lower - upstream)
239
- 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
240
246
  last_err = None
241
247
  for contig in contigs_to_try:
242
248
  try:
@@ -253,15 +259,31 @@ class Transcript:
253
259
  self,
254
260
  upstream: int = 0,
255
261
  downstream: int = 0,
262
+ region_start: Optional[int] = None,
263
+ region_end: Optional[int] = None,
256
264
  ) -> "Transcript":
257
- """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
+ """
258
272
  try:
259
- 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
+ )
260
277
  pre_mrna = SeqMat(**seq_data)
261
278
  except Exception:
262
- length = self.transcript_upper - self.transcript_lower + 1 + upstream + downstream
263
- start = max(1, self.transcript_lower - upstream)
264
- 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)
265
287
  pre_mrna = SeqMat("N" * length, indices=indices)
266
288
  if self.rev:
267
289
  pre_mrna.reverse_complement()
@@ -298,23 +320,10 @@ class Transcript:
298
320
  print("Cannot create protein without set TIS and TTS values.")
299
321
  return self
300
322
 
301
- # Extract ORF region from mature mRNA
323
+ # Extract ORF region from mature mRNA via clone (no string re-parse)
302
324
  if hasattr(self, 'mature_mrna') and self.mature_mrna is not None:
303
- # Find the positions in the mature mRNA
304
- orf_start_idx = np.where(self.mature_mrna.index == self.TIS)[0]
305
- orf_end_idx = np.where(self.mature_mrna.index == self.TTS)[0]
306
-
307
- if len(orf_start_idx) > 0 and len(orf_end_idx) > 0:
308
- # Extract the subsequence using the found indices
309
- start_idx = orf_start_idx[0]
310
- end_idx = orf_end_idx[0] + 1 # +1 for inclusive end
311
-
312
- # Create new SeqMat with the ORF sequence
313
- orf_seq = self.mature_mrna.seq[start_idx:end_idx]
314
- orf_indices = self.mature_mrna.index[start_idx:end_idx]
315
-
316
- return SeqMat(orf_seq, indices=orf_indices)
317
-
325
+ return self.mature_mrna.clone(self.TIS, self.TTS)
326
+
318
327
  return self
319
328
 
320
329
  def generate_protein(self, inplace: bool = True) -> Union['Transcript', str]:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: seqmat
3
- Version: 1.1.1
3
+ Version: 1.2.1
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
@@ -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
@@ -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.1",
11
+ version="1.2.1",
12
12
  author="Nicolas Lynn Vila",
13
13
  author_email="nicolasalynn@gmail.com",
14
14
  description="Lightning-fast gene manipulation and analysis library.",
@@ -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
File without changes
File without changes