seqmat 0.1.52__tar.gz → 0.1.54__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-0.1.52/seqmat.egg-info → seqmat-0.1.54}/PKG-INFO +3 -4
  2. seqmat-0.1.54/requirements.txt +9 -0
  3. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat/__init__.py +1 -1
  4. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat/config.py +7 -1
  5. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat/gene.py +6 -2
  6. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat/seqmat.py +5 -3
  7. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat/utils.py +98 -14
  8. {seqmat-0.1.52 → seqmat-0.1.54/seqmat.egg-info}/PKG-INFO +3 -4
  9. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat.egg-info/requires.txt +2 -3
  10. {seqmat-0.1.52 → seqmat-0.1.54}/setup.py +3 -4
  11. seqmat-0.1.52/requirements.txt +0 -9
  12. {seqmat-0.1.52 → seqmat-0.1.54}/LICENSE +0 -0
  13. {seqmat-0.1.52 → seqmat-0.1.54}/MANIFEST.in +0 -0
  14. {seqmat-0.1.52 → seqmat-0.1.54}/README.md +0 -0
  15. {seqmat-0.1.52 → seqmat-0.1.54}/examples/basic_usage.py +0 -0
  16. {seqmat-0.1.52 → seqmat-0.1.54}/examples/data_inspection.py +0 -0
  17. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat/cli.py +0 -0
  18. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat/lmdb_store.py +0 -0
  19. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat/sqlite_store.py +0 -0
  20. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat/transcript.py +0 -0
  21. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat.egg-info/SOURCES.txt +0 -0
  22. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat.egg-info/dependency_links.txt +0 -0
  23. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat.egg-info/entry_points.txt +0 -0
  24. {seqmat-0.1.52 → seqmat-0.1.54}/seqmat.egg-info/top_level.txt +0 -0
  25. {seqmat-0.1.52 → seqmat-0.1.54}/setup.cfg +0 -0
  26. {seqmat-0.1.52 → seqmat-0.1.54}/tests/__init__.py +0 -0
  27. {seqmat-0.1.52 → seqmat-0.1.54}/tests/test_gene.py +0 -0
  28. {seqmat-0.1.52 → seqmat-0.1.54}/tests/test_seqmat.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: seqmat
3
- Version: 0.1.52
3
+ Version: 0.1.54
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
@@ -16,14 +16,13 @@ Classifier: Programming Language :: Python :: 3.12
16
16
  Requires-Python: >=3.10
17
17
  Description-Content-Type: text/markdown
18
18
  License-File: LICENSE
19
- Requires-Dist: numpy<2,>=1.20.0
19
+ Requires-Dist: numpy<3,>=1.20.0
20
20
  Requires-Dist: pandas<3,>=2.2.0
21
- Requires-Dist: pyarrow>=14.0.0
21
+ 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
25
  Requires-Dist: biopython>=1.79
26
- Requires-Dist: gtfparse>=1.2.0
27
26
  Requires-Dist: platformdirs>=3.0.0
28
27
  Provides-Extra: lmdb
29
28
  Requires-Dist: lmdb>=1.4.0; extra == "lmdb"
@@ -0,0 +1,9 @@
1
+ # NumPy 2 and pandas 2.x supported; pyarrow>=15 works with NumPy 2 (gtfparse removed)
2
+ numpy>=1.20.0,<3
3
+ pandas>=2.2.0,<3
4
+ pyarrow>=15.0.0
5
+ pysam>=0.19.0
6
+ requests>=2.26.0
7
+ tqdm>=4.62.0
8
+ biopython>=1.79
9
+ 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__ = "0.1.52"
8
+ __version__ = "0.1.54"
9
9
  __author__ = "Nicolas Lynn Vila"
10
10
  __email__ = "nicolasalynn@gmail.com"
11
11
 
@@ -165,7 +165,13 @@ def get_organism_config(organism: Optional[str] = None) -> Dict[str, Path]:
165
165
  raise ValueError(f"Invalid configuration for organism '{organism}'. Expected dictionary.")
166
166
  if not isinstance(org_config, dict):
167
167
  raise ValueError(f"Invalid configuration for organism '{organism}'.")
168
- return {k: Path(v) for k, v in org_config.items() if isinstance(v, str)}
168
+ out = {k: Path(v) for k, v in org_config.items() if isinstance(v, str)}
169
+ # Prefer genes.db when it exists: if not in config, infer from BASE or MRNA_PATH (same dir as setup)
170
+ if "genes_db" not in out:
171
+ base_or_mrna = out.get("BASE") or out.get("MRNA_PATH")
172
+ if base_or_mrna is not None:
173
+ out["genes_db"] = Path(base_or_mrna) / "genes.db"
174
+ return out
169
175
 
170
176
  def get_directory_config() -> Dict[str, str]:
171
177
  """Return directory_structure (e.g. chromosomes, annotations folder names)."""
@@ -78,11 +78,15 @@ class Gene:
78
78
  def from_file(cls, gene_name: str, organism: Optional[str] = None) -> Optional['Gene']:
79
79
  """
80
80
  Load gene data from file.
81
-
81
+
82
+ Load order: LMDB (if installed) → SQLite (genes.db) → per-gene pickle files.
83
+ To use the DB, ensure genes.db exists in your organism data dir (run setup_genomics_data,
84
+ or set SEQMAT_DATA_DIR to a path whose organism subdirs contain genes.db).
85
+
82
86
  Args:
83
87
  gene_name: Name of the gene to load
84
88
  organism: Organism reference build
85
-
89
+
86
90
  Returns:
87
91
  Gene object or None if not found
88
92
  """
@@ -5,12 +5,14 @@ import copy
5
5
  from collections import defaultdict
6
6
  from dataclasses import dataclass, field
7
7
  from pathlib import Path
8
- from typing import Any, Dict, List, Optional, Tuple, Union
8
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
9
9
 
10
10
  import numpy as np
11
- import pandas as pd
12
11
  import pysam
13
12
 
13
+ if TYPE_CHECKING:
14
+ import pandas as pd
15
+
14
16
  from .config import get_organism_config
15
17
 
16
18
  Mutation = Tuple[int, str, str]
@@ -37,7 +39,7 @@ class SeqMat:
37
39
  mutations: List[Dict[str, Any]] = field(default_factory=list, init=False, repr=False)
38
40
  mutated_positions: set[int] = field(default_factory=set, init=False, repr=False)
39
41
  rev: bool = field(default=False, init=False, repr=False)
40
- predicted_splicing: Optional[pd.DataFrame] = field(default=None, init=False, repr=False)
42
+ predicted_splicing: Optional["pd.DataFrame"] = field(default=None, init=False, repr=False)
41
43
 
42
44
  def __init__(
43
45
  self,
@@ -1,23 +1,30 @@
1
1
  """Utility functions for SeqMat package"""
2
+ from __future__ import annotations
3
+
4
+ import os
2
5
  import pickle
3
6
  import json
7
+ import re
4
8
  import sqlite3
5
9
  from concurrent.futures import ProcessPoolExecutor, as_completed
6
10
  from multiprocessing import cpu_count
7
11
  import numpy as np
8
12
  from pathlib import Path
9
- from typing import Any, Union, List, Optional, Dict, Tuple
10
- import pandas as pd
13
+ from typing import TYPE_CHECKING, Any, Union, List, Optional, Dict, Tuple
11
14
  from tqdm import tqdm
15
+
16
+ if TYPE_CHECKING:
17
+ import pandas as pd
18
+ else:
19
+ def _get_pd():
20
+ import pandas as pd
21
+ return pd
12
22
  import requests
13
23
  import gzip
14
24
  import shutil
15
25
 
16
- try:
17
- from gtfparse import read_gtf
18
- GTFPARSE_AVAILABLE = True
19
- except ImportError:
20
- GTFPARSE_AVAILABLE = False
26
+ # GTF reading: we use a pandas-based reader so we don't depend on gtfparse (which pins pyarrow<14.1).
27
+ # That allows seqmat to require pyarrow>=15 and NumPy 2.
21
28
 
22
29
  try:
23
30
  import polars as pl
@@ -34,9 +41,48 @@ _GTF_COLS = [
34
41
  ]
35
42
  _FEATURE_FILTER = {'gene', 'transcript', 'exon', 'CDS'}
36
43
 
44
+ _GTF_FIXED_COLS = ['seqname', 'source', 'feature', 'start', 'end', 'score', 'strand', 'frame', 'attributes']
45
+ _GTF_ATTR_KEYS = ['gene_id', 'transcript_id', 'gene_name', 'gene_biotype', 'transcript_biotype', 'tag', 'protein_id']
46
+
47
+
48
+ def _parse_gtf_attributes(attr_str: str) -> Dict[str, str]:
49
+ """Parse GTF attributes column (key "value"; key2 "value2"; ...) into a dict."""
50
+ out: Dict[str, str] = {}
51
+ if not isinstance(attr_str, str) or not attr_str.strip():
52
+ return out
53
+ for m in re.finditer(r'(\w+)\s+"([^"]*)"', attr_str):
54
+ out[m.group(1)] = m.group(2)
55
+ return out
56
+
57
+
58
+ def _read_gtf_pandas(annotations_file: Union[Path, str]) -> "pd.DataFrame":
59
+ """Read a GTF file into a pandas DataFrame with columns needed for annotation processing.
60
+ Does not require gtfparse, so we can use pyarrow>=15 and NumPy 2.
61
+ """
62
+ pd = _get_pd()
63
+ path = Path(annotations_file)
64
+ df = pd.read_csv(
65
+ path,
66
+ sep='\t',
67
+ comment='#',
68
+ header=None,
69
+ names=_GTF_FIXED_COLS,
70
+ dtype={'seqname': str, 'source': str, 'feature': str, 'strand': str, 'frame': str, 'attributes': str},
71
+ on_bad_lines='warn',
72
+ )
73
+ # Parse attributes into columns
74
+ attr_rows = df['attributes'].map(_parse_gtf_attributes)
75
+ for key in _GTF_ATTR_KEYS:
76
+ df[key] = attr_rows.map(lambda d, k=key: d.get(k, ''))
77
+ df = df.drop(columns=['attributes'])
78
+ df['start'] = pd.to_numeric(df['start'], errors='coerce').astype('Int64')
79
+ df['end'] = pd.to_numeric(df['end'], errors='coerce').astype('Int64')
80
+ return df
81
+
37
82
 
38
83
  def _process_gene_chunk(args: Tuple[Any, Optional[Dict], Any]) -> List[Tuple[str, str, str, bytes]]:
39
84
  """Process a subset of annotations (one chunk by gene_id). Returns list of (gene_name, gene_id, biotype, blob)."""
85
+ pd = _get_pd()
40
86
  chunk_df, cons_data, gtex_df = args
41
87
  if chunk_df.empty:
42
88
  return []
@@ -165,9 +211,10 @@ def download_and_ungzip(external_url: str, local_path: Path, skip_existing: bool
165
211
  return output_file
166
212
 
167
213
 
168
- def process_transcript(transcript_df: pd.DataFrame, rev: bool, chrm: str,
214
+ def process_transcript(transcript_df: "pd.DataFrame", rev: bool, chrm: str,
169
215
  cons_data: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
170
216
  """Process transcript data from GTF dataframe."""
217
+ pd = _get_pd()
171
218
  if transcript_df.empty:
172
219
  return None
173
220
 
@@ -244,8 +291,7 @@ def retrieve_and_parse_ensembl_annotations(
244
291
  n_jobs: int = 1,
245
292
  ) -> None:
246
293
  """Parse Ensembl GTF annotations and create genes.db. Use n_jobs > 1 to parallelize (faster)."""
247
- if not GTFPARSE_AVAILABLE:
248
- raise ImportError("gtfparse is required for genomics data setup. Install with: pip install seqmat[genomics]")
294
+ pd = _get_pd()
249
295
 
250
296
  # Load GTEx expression data if available
251
297
  if gtex_file and gtex_file.exists():
@@ -257,10 +303,7 @@ def retrieve_and_parse_ensembl_annotations(
257
303
  gtex_df = pd.DataFrame()
258
304
 
259
305
  print("Reading GTF annotations...")
260
- annotations = read_gtf(annotations_file)
261
-
262
- if POLARS_AVAILABLE and hasattr(annotations, '__module__') and 'polars' in annotations.__module__:
263
- annotations = annotations.to_pandas()
306
+ annotations = _read_gtf_pandas(annotations_file)
264
307
 
265
308
  required_columns = ['gene_id', 'gene_biotype', 'seqname', 'strand', 'feature']
266
309
  missing_columns = [col for col in required_columns if col not in annotations.columns]
@@ -478,6 +521,45 @@ def download_genome_data(organism: str, base_path: Path, skip_existing: bool = F
478
521
  return files
479
522
 
480
523
 
524
+ def _shell_config_path() -> Optional[Path]:
525
+ """Path to the user's shell config file (~/.zshrc or ~/.bashrc). Prefer zsh if SHELL contains zsh."""
526
+ home = Path.home()
527
+ shell = os.environ.get("SHELL", "")
528
+ if "zsh" in shell:
529
+ rc = home / ".zshrc"
530
+ else:
531
+ rc = home / ".bashrc"
532
+ if rc.exists():
533
+ return rc
534
+ # If preferred rc doesn't exist, try the other
535
+ other = home / ".zshrc" if rc.name == ".bashrc" else home / ".bashrc"
536
+ return other if other.exists() else rc
537
+
538
+
539
+ def _append_seqmat_env_to_shell(data_root: Path, organism: str) -> None:
540
+ """Append SEQMAT_DATA_DIR and SEQMAT_DEFAULT_ORGANISM to the user's shell config if not already set."""
541
+ rc = _shell_config_path()
542
+ if not rc or not rc.is_file():
543
+ return
544
+ try:
545
+ text = rc.read_text()
546
+ except OSError:
547
+ return
548
+ if "SEQMAT_DATA_DIR" in text:
549
+ return
550
+ block = (
551
+ "\n# SeqMat config-less data root (added by seqmat setup)\n"
552
+ f"export SEQMAT_DATA_DIR=\"{data_root}\"\n"
553
+ f"export SEQMAT_DEFAULT_ORGANISM=\"{organism}\"\n"
554
+ )
555
+ try:
556
+ with open(rc, "a") as f:
557
+ f.write(block)
558
+ print(f"Added SEQMAT_DATA_DIR and SEQMAT_DEFAULT_ORGANISM to {rc}. Restart your shell or run: source {rc}")
559
+ except OSError:
560
+ pass
561
+
562
+
481
563
  def setup_genomics_data(
482
564
  basepath: str,
483
565
  organism: Optional[str] = None,
@@ -573,6 +655,8 @@ def setup_genomics_data(
573
655
  print(f"Configuration saved to: {CONFIG_FILE}")
574
656
  else:
575
657
  print("SEQMAT_DATA_DIR is set; no config file written. Point it at this path to use the data.")
658
+ # Append SEQMAT_DATA_DIR (and default organism) to shell config so it persists
659
+ _append_seqmat_env_to_shell(Path(basepath).resolve(), organism)
576
660
  print(f"Successfully set up genomics data for {organism} in {basepath}")
577
661
  print("You can now use Gene.from_file() to load gene data.")
578
662
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: seqmat
3
- Version: 0.1.52
3
+ Version: 0.1.54
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
@@ -16,14 +16,13 @@ Classifier: Programming Language :: Python :: 3.12
16
16
  Requires-Python: >=3.10
17
17
  Description-Content-Type: text/markdown
18
18
  License-File: LICENSE
19
- Requires-Dist: numpy<2,>=1.20.0
19
+ Requires-Dist: numpy<3,>=1.20.0
20
20
  Requires-Dist: pandas<3,>=2.2.0
21
- Requires-Dist: pyarrow>=14.0.0
21
+ 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
25
  Requires-Dist: biopython>=1.79
26
- Requires-Dist: gtfparse>=1.2.0
27
26
  Requires-Dist: platformdirs>=3.0.0
28
27
  Provides-Extra: lmdb
29
28
  Requires-Dist: lmdb>=1.4.0; extra == "lmdb"
@@ -1,11 +1,10 @@
1
- numpy<2,>=1.20.0
1
+ numpy<3,>=1.20.0
2
2
  pandas<3,>=2.2.0
3
- pyarrow>=14.0.0
3
+ pyarrow>=15.0.0
4
4
  pysam>=0.19.0
5
5
  requests>=2.26.0
6
6
  tqdm>=4.62.0
7
7
  biopython>=1.79
8
- gtfparse>=1.2.0
9
8
  platformdirs>=3.0.0
10
9
 
11
10
  [dev]
@@ -8,7 +8,7 @@ long_description = (this_directory / "README.md").read_text()
8
8
 
9
9
  setup(
10
10
  name="seqmat",
11
- version="0.1.52",
11
+ version="0.1.54",
12
12
  author="Nicolas Lynn Vila",
13
13
  author_email="nicolasalynn@gmail.com",
14
14
  description="Lightning-fast gene manipulation and analysis library.",
@@ -28,14 +28,13 @@ setup(
28
28
  ],
29
29
  python_requires=">=3.10",
30
30
  install_requires=[
31
- "numpy>=1.20.0,<2", # NumPy 1.x: pyarrow 14 (from gtfparse) is built for 1.x
31
+ "numpy>=1.20.0,<3",
32
32
  "pandas>=2.2.0,<3",
33
- "pyarrow>=14.0.0",
33
+ "pyarrow>=15.0.0",
34
34
  "pysam>=0.19.0",
35
35
  "requests>=2.26.0",
36
36
  "tqdm>=4.62.0",
37
37
  "biopython>=1.79",
38
- "gtfparse>=1.2.0",
39
38
  "platformdirs>=3.0.0",
40
39
  ],
41
40
  extras_require={
@@ -1,9 +0,0 @@
1
- # NumPy 1.x required: pyarrow 14 (gtfparse) is built for NumPy 1.x; use numpy<2
2
- numpy>=1.20.0,<2
3
- pandas>=2.2.0,<3
4
- pysam>=0.19.0
5
- requests>=2.26.0
6
- tqdm>=4.62.0
7
- biopython>=1.79
8
- gtfparse>=1.2.0
9
- platformdirs>=3.0.0
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