seqmat 1.1.1__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.1/seqmat.egg-info → seqmat-1.2.0}/PKG-INFO +1 -1
  2. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat/__init__.py +1 -1
  3. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat/seqmat.py +53 -8
  4. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat/transcript.py +29 -7
  5. {seqmat-1.1.1 → seqmat-1.2.0/seqmat.egg-info}/PKG-INFO +1 -1
  6. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat.egg-info/SOURCES.txt +1 -0
  7. {seqmat-1.1.1 → seqmat-1.2.0}/setup.py +1 -1
  8. seqmat-1.2.0/tests/bench_gene_creation.py +130 -0
  9. {seqmat-1.1.1 → seqmat-1.2.0}/LICENSE +0 -0
  10. {seqmat-1.1.1 → seqmat-1.2.0}/MANIFEST.in +0 -0
  11. {seqmat-1.1.1 → seqmat-1.2.0}/README.md +0 -0
  12. {seqmat-1.1.1 → seqmat-1.2.0}/examples/basic_usage.py +0 -0
  13. {seqmat-1.1.1 → seqmat-1.2.0}/examples/data_inspection.py +0 -0
  14. {seqmat-1.1.1 → seqmat-1.2.0}/requirements.txt +0 -0
  15. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat/cli.py +0 -0
  16. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat/config.py +0 -0
  17. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat/gene.py +0 -0
  18. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat/lmdb_store.py +0 -0
  19. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat/sqlite_store.py +0 -0
  20. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat/utils.py +0 -0
  21. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat.egg-info/dependency_links.txt +0 -0
  22. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat.egg-info/entry_points.txt +0 -0
  23. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat.egg-info/requires.txt +0 -0
  24. {seqmat-1.1.1 → seqmat-1.2.0}/seqmat.egg-info/top_level.txt +0 -0
  25. {seqmat-1.1.1 → seqmat-1.2.0}/setup.cfg +0 -0
  26. {seqmat-1.1.1 → seqmat-1.2.0}/tests/__init__.py +0 -0
  27. {seqmat-1.1.1 → seqmat-1.2.0}/tests/test_gene.py +0 -0
  28. {seqmat-1.1.1 → 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.1
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
@@ -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.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)
@@ -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()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: seqmat
3
- Version: 1.1.1
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
@@ -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.0",
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