seqmat 1.2.2__tar.gz → 1.3.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.2.2/seqmat.egg-info → seqmat-1.3.1}/PKG-INFO +1 -1
  2. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat/__init__.py +1 -1
  3. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat/gene.py +0 -9
  4. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat/seqmat.py +2 -4
  5. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat/transcript.py +71 -18
  6. {seqmat-1.2.2 → seqmat-1.3.1/seqmat.egg-info}/PKG-INFO +1 -1
  7. {seqmat-1.2.2 → seqmat-1.3.1}/setup.py +1 -1
  8. {seqmat-1.2.2 → seqmat-1.3.1}/LICENSE +0 -0
  9. {seqmat-1.2.2 → seqmat-1.3.1}/MANIFEST.in +0 -0
  10. {seqmat-1.2.2 → seqmat-1.3.1}/README.md +0 -0
  11. {seqmat-1.2.2 → seqmat-1.3.1}/examples/basic_usage.py +0 -0
  12. {seqmat-1.2.2 → seqmat-1.3.1}/examples/data_inspection.py +0 -0
  13. {seqmat-1.2.2 → seqmat-1.3.1}/requirements.txt +0 -0
  14. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat/cli.py +0 -0
  15. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat/config.py +0 -0
  16. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat/lmdb_store.py +0 -0
  17. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat/sqlite_store.py +0 -0
  18. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat/utils.py +0 -0
  19. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat.egg-info/SOURCES.txt +0 -0
  20. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat.egg-info/dependency_links.txt +0 -0
  21. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat.egg-info/entry_points.txt +0 -0
  22. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat.egg-info/requires.txt +0 -0
  23. {seqmat-1.2.2 → seqmat-1.3.1}/seqmat.egg-info/top_level.txt +0 -0
  24. {seqmat-1.2.2 → seqmat-1.3.1}/setup.cfg +0 -0
  25. {seqmat-1.2.2 → seqmat-1.3.1}/tests/__init__.py +0 -0
  26. {seqmat-1.2.2 → seqmat-1.3.1}/tests/bench_gene_creation.py +0 -0
  27. {seqmat-1.2.2 → seqmat-1.3.1}/tests/test_gene.py +0 -0
  28. {seqmat-1.2.2 → seqmat-1.3.1}/tests/test_seqmat.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: seqmat
3
- Version: 1.2.2
3
+ Version: 1.3.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.2.2"
8
+ __version__ = "1.3.1"
9
9
  __author__ = "Nicolas Lynn Vila"
10
10
  __email__ = "nicolasalynn@gmail.com"
11
11
 
@@ -1,5 +1,4 @@
1
1
  """Gene class for representing genomic genes with associated transcripts"""
2
- import copy
3
2
  from typing import Any, Dict, List, Tuple, Optional, Iterator, Union
4
3
  from collections import Counter
5
4
  from pathlib import Path
@@ -54,14 +53,6 @@ class Gene:
54
53
  """Returns the number of transcripts associated with this gene."""
55
54
  return len(self.transcripts)
56
55
 
57
- def __copy__(self):
58
- """Returns a shallow copy of the Gene object."""
59
- return copy.copy(self)
60
-
61
- def __deepcopy__(self, memo):
62
- """Returns a deep copy of the Gene object."""
63
- return copy.deepcopy(self, memo)
64
-
65
56
  def __iter__(self) -> Iterator[Transcript]:
66
57
  """Allow iteration over the gene's transcripts, yielding Transcript objects."""
67
58
  for tid, annotations in self.transcripts.items():
@@ -29,14 +29,12 @@ _COMPLEMENT_LUT[ord('G')] = ord('C')
29
29
  @lru_cache(maxsize=8)
30
30
  def _fetch_fasta_region(fasta_path: str, chrom: str, start: int, end: int) -> str:
31
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()
32
+ with pysam.FastaFile(fasta_path) as fasta:
33
+ return fasta.fetch(chrom, start - 1, end).upper()
34
34
 
35
35
 
36
36
  def contains(array: Union[np.ndarray, List], value: Any) -> bool:
37
37
  """Return whether value is in array or list."""
38
- if isinstance(array, np.ndarray):
39
- return value in array
40
38
  return value in array
41
39
 
42
40
 
@@ -34,7 +34,7 @@ def _translate(seq: str) -> str:
34
34
  trimmed = seq[:len(seq) - len(seq) % 3] if len(seq) % 3 else seq
35
35
  return ''.join(_CODON_TABLE.get(trimmed[i:i+3], 'X') for i in range(0, len(trimmed), 3))
36
36
 
37
- from .seqmat import SeqMat
37
+ from .seqmat import SeqMat, _fetch_fasta_region
38
38
  from .config import get_organism_config, get_default_organism
39
39
 
40
40
 
@@ -67,7 +67,7 @@ class Transcript:
67
67
  self.protein_coding = hasattr(self, "TIS") and hasattr(self, "TTS")
68
68
  self.transcript_upper = max(self.transcript_start, self.transcript_end)
69
69
  self.transcript_lower = min(self.transcript_start, self.transcript_end)
70
- self.generate_pre_mrna()
70
+ self._pre_mrna = None
71
71
  if self.cons_available and hasattr(self, "cons_seq") and self._cons_vector is not None:
72
72
  if self.cons_seq.endswith("*") and len(self.cons_seq) == len(self._cons_vector):
73
73
  self._cons_vector = self._cons_vector[:-1]
@@ -104,6 +104,17 @@ class Transcript:
104
104
  """Returns a deep copy of this Transcript instance."""
105
105
  return copy.deepcopy(self)
106
106
 
107
+ @property
108
+ def pre_mrna(self) -> SeqMat:
109
+ """Pre-mRNA sequence. Lazy-loaded from FASTA on first access."""
110
+ if self._pre_mrna is None:
111
+ self.generate_pre_mrna()
112
+ return self._pre_mrna
113
+
114
+ @pre_mrna.setter
115
+ def pre_mrna(self, value: Optional[SeqMat]) -> None:
116
+ self._pre_mrna = value
117
+
107
118
  @property
108
119
  def cons_vector(self) -> np.ndarray:
109
120
  """Per-residue conservation scores; ones vector when conservation data not loaded."""
@@ -211,21 +222,12 @@ class Transcript:
211
222
  """Return the indices covering exons in the transcript."""
212
223
  return np.concatenate([np.arange(a, b + 1) for a, b in self.exons_pos])
213
224
 
214
- def pull_pre_mrna_from_fasta(
215
- self,
216
- fasta_path: Optional[Path] = None,
217
- upstream: int = 0,
218
- downstream: int = 0,
219
- region_start: Optional[int] = None,
220
- region_end: Optional[int] = None,
221
- ) -> Dict[str, Any]:
222
- """Pre-mRNA sequence from the single full-genome FASTA (e.g. hg38.fa). Optional upstream/downstream."""
225
+ def _resolve_fasta_path(self, fasta_path: Optional[Path] = None) -> Tuple[Path, List[str]]:
226
+ """Resolve FASTA file path and contig names for this transcript."""
223
227
  if fasta_path is None:
224
228
  config = get_organism_config(self.organism)
225
- # Single full-genome FASTA only (no per-chromosome files in current setup)
226
229
  fasta_path = config.get("fasta_full_genome") or config.get("fasta")
227
230
  if fasta_path is None:
228
- # Legacy: per-chromosome files under CHROM_SOURCE
229
231
  fasta_path = config.get("CHROM_SOURCE") and (Path(config["CHROM_SOURCE"]) / f"chr{self.chrm}.fasta")
230
232
  fasta_path = Path(fasta_path) if fasta_path else None
231
233
  if not fasta_path or not fasta_path.exists():
@@ -233,10 +235,48 @@ class Transcript:
233
235
  "No FASTA path in config (fasta_full_genome or fasta). "
234
236
  "Run setup_genomics_data() to install the full-genome FASTA (e.g. hg38.fa)."
235
237
  )
236
- # Full-genome FASTA: UCSC uses chr17, Ensembl sometimes 17 — try both
237
238
  raw_chr = str(self.chrm).replace("chr", "") or "17"
238
239
  with_chr = f"chr{raw_chr}"
239
- contigs_to_try = [with_chr, raw_chr] if with_chr != raw_chr else [with_chr]
240
+ contigs = [with_chr, raw_chr] if with_chr != raw_chr else [with_chr]
241
+ return Path(fasta_path), contigs
242
+
243
+ def _assemble_mature_from_fasta(self) -> SeqMat:
244
+ """Fetch exons directly from FASTA and assemble mature mRNA (skips pre-mRNA)."""
245
+ fasta_path, contigs = self._resolve_fasta_path()
246
+
247
+ # Sort exons by ascending genomic position
248
+ exon_intervals = sorted((min(a, b), max(a, b)) for a, b in self.exons)
249
+
250
+ last_err = None
251
+ for contig in contigs:
252
+ try:
253
+ seqs = []
254
+ all_indices = []
255
+ for lo, hi in exon_intervals:
256
+ seq_str = _fetch_fasta_region(str(fasta_path), contig, lo, hi)
257
+ seqs.append(seq_str)
258
+ all_indices.append(np.arange(lo, hi + 1, dtype=np.int64))
259
+
260
+ mature = SeqMat(''.join(seqs), indices=np.concatenate(all_indices))
261
+ if self.rev:
262
+ mature.reverse_complement()
263
+ return mature
264
+ except Exception as e:
265
+ last_err = e
266
+ if last_err is not None:
267
+ raise last_err
268
+ raise ValueError(f"Could not fetch exons from FASTA for {self.chrm}")
269
+
270
+ def pull_pre_mrna_from_fasta(
271
+ self,
272
+ fasta_path: Optional[Path] = None,
273
+ upstream: int = 0,
274
+ downstream: int = 0,
275
+ region_start: Optional[int] = None,
276
+ region_end: Optional[int] = None,
277
+ ) -> Dict[str, Any]:
278
+ """Pre-mRNA sequence from the single full-genome FASTA (e.g. hg38.fa). Optional upstream/downstream."""
279
+ fasta_path, contigs_to_try = self._resolve_fasta_path(fasta_path)
240
280
  if region_start is not None or region_end is not None:
241
281
  start = region_start if region_start is not None else max(1, self.transcript_lower - upstream)
242
282
  end = region_end if region_end is not None else (self.transcript_upper + downstream)
@@ -294,6 +334,9 @@ class Transcript:
294
334
  """
295
335
  Generate the mature mRNA by concatenating exon regions from pre_mRNA.
296
336
 
337
+ When pre-mRNA has not been loaded yet, exons are fetched directly from
338
+ the indexed FASTA — skipping the full-gene read entirely.
339
+
297
340
  Args:
298
341
  inplace: If True, set self.mature_mrna, else return a new SeqMat
299
342
 
@@ -302,11 +345,21 @@ class Transcript:
302
345
  """
303
346
  self._fix_and_check_introns()
304
347
 
348
+ if self._pre_mrna is not None:
349
+ # Pre-mRNA loaded (possibly mutated): splice from it
350
+ result = self.pre_mrna.remove_regions(self.introns)
351
+ else:
352
+ # Fast path: fetch exons directly, skip full-gene read
353
+ try:
354
+ result = self._assemble_mature_from_fasta()
355
+ except Exception:
356
+ # Fall back to full pre-mRNA load + splice
357
+ result = self.pre_mrna.remove_regions(self.introns)
358
+
305
359
  if inplace:
306
- self.mature_mrna = self.pre_mrna.remove_regions(self.introns)
360
+ self.mature_mrna = result
307
361
  return self
308
-
309
- return self.pre_mrna.remove_regions(self.introns)
362
+ return result
310
363
 
311
364
  @property
312
365
  def orf(self) -> Union[SeqMat, 'Transcript']:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: seqmat
3
- Version: 1.2.2
3
+ Version: 1.3.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
@@ -8,7 +8,7 @@ long_description = (this_directory / "README.md").read_text()
8
8
 
9
9
  setup(
10
10
  name="seqmat",
11
- version="1.2.2",
11
+ version="1.3.1",
12
12
  author="Nicolas Lynn Vila",
13
13
  author_email="nicolasalynn@gmail.com",
14
14
  description="Lightning-fast gene manipulation and analysis library.",
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