seqmat 0.1.49__tar.gz → 0.1.51__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.
- {seqmat-0.1.49/seqmat.egg-info → seqmat-0.1.51}/PKG-INFO +34 -11
- {seqmat-0.1.49 → seqmat-0.1.51}/README.md +31 -9
- seqmat-0.1.51/requirements.txt +9 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat/__init__.py +4 -2
- seqmat-0.1.51/seqmat/config.py +187 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat/gene.py +14 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat/seqmat.py +14 -15
- seqmat-0.1.51/seqmat/sqlite_store.py +48 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat/transcript.py +27 -4
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat/utils.py +208 -109
- {seqmat-0.1.49 → seqmat-0.1.51/seqmat.egg-info}/PKG-INFO +34 -11
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat.egg-info/SOURCES.txt +1 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat.egg-info/requires.txt +2 -1
- {seqmat-0.1.49 → seqmat-0.1.51}/setup.py +3 -2
- {seqmat-0.1.49 → seqmat-0.1.51}/tests/test_gene.py +56 -26
- {seqmat-0.1.49 → seqmat-0.1.51}/tests/test_seqmat.py +6 -5
- seqmat-0.1.49/requirements.txt +0 -9
- seqmat-0.1.49/seqmat/config.py +0 -120
- {seqmat-0.1.49 → seqmat-0.1.51}/LICENSE +0 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/MANIFEST.in +0 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/examples/basic_usage.py +0 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/examples/data_inspection.py +0 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat/cli.py +0 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat/lmdb_store.py +0 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat.egg-info/dependency_links.txt +0 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat.egg-info/entry_points.txt +0 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/seqmat.egg-info/top_level.txt +0 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/setup.cfg +0 -0
- {seqmat-0.1.49 → seqmat-0.1.51}/tests/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: seqmat
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.51
|
|
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
|
|
@@ -17,7 +17,8 @@ Requires-Python: >=3.10
|
|
|
17
17
|
Description-Content-Type: text/markdown
|
|
18
18
|
License-File: LICENSE
|
|
19
19
|
Requires-Dist: numpy<3,>=1.20.0
|
|
20
|
-
Requires-Dist: pandas
|
|
20
|
+
Requires-Dist: pandas<3,>=2.2.0
|
|
21
|
+
Requires-Dist: pyarrow>=14.0.0
|
|
21
22
|
Requires-Dist: pysam>=0.19.0
|
|
22
23
|
Requires-Dist: requests>=2.26.0
|
|
23
24
|
Requires-Dist: tqdm>=4.62.0
|
|
@@ -244,9 +245,12 @@ For the built-in organisms (hg38, mm39), setup is straightforward:
|
|
|
244
245
|
```python
|
|
245
246
|
from seqmat import setup_genomics_data
|
|
246
247
|
|
|
247
|
-
# Download and setup human genome data
|
|
248
|
+
# Download and setup human genome data (GTF parsing uses multiple cores by default)
|
|
248
249
|
setup_genomics_data("/path/to/your/data", organism="hg38")
|
|
249
250
|
|
|
251
|
+
# Optional: limit or set parallel workers (faster on multi-core machines)
|
|
252
|
+
setup_genomics_data("/path/to/your/data", organism="hg38", n_jobs=8) # or n_jobs=1 for serial
|
|
253
|
+
|
|
250
254
|
# Download and setup mouse genome data
|
|
251
255
|
setup_genomics_data("/path/to/your/data", organism="mm39")
|
|
252
256
|
```
|
|
@@ -262,7 +266,25 @@ seqmat setup --path /path/to/your/data --organism mm39 --force
|
|
|
262
266
|
|
|
263
267
|
### Configuration System
|
|
264
268
|
|
|
265
|
-
|
|
269
|
+
**Config-less mode (no config file):**
|
|
270
|
+
Set **`SEQMAT_DATA_DIR`** to the root path where organism dirs live (e.g. where you ran `setup_genomics_data`):
|
|
271
|
+
|
|
272
|
+
```bash
|
|
273
|
+
export SEQMAT_DATA_DIR=/path/to/seqmat_base # e.g. in .bashrc or .zshrc
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
SeqMat will derive all paths from it: `{SEQMAT_DATA_DIR}/{organism}/genes.db`, `*.fa`, etc. Optional: **`SEQMAT_DEFAULT_ORGANISM`** (default `hg38`). No config file is used or written.
|
|
277
|
+
|
|
278
|
+
**Config file mode** (when `SEQMAT_DATA_DIR` is not set):
|
|
279
|
+
|
|
280
|
+
1. **`SEQMAT_CONFIG_FILE`** – exact path to config.json.
|
|
281
|
+
2. **`SEQMAT_CONFIG_DIR`** – directory; config is `{SEQMAT_CONFIG_DIR}/config.json`.
|
|
282
|
+
3. **Default** – platform config dir (e.g. `~/.config/seqmat/config.json` on Linux).
|
|
283
|
+
|
|
284
|
+
To see which file is used: `from seqmat import get_config_file; print(get_config_file())`.
|
|
285
|
+
To see if config-less: `from seqmat import get_data_base; print(get_data_base())`.
|
|
286
|
+
|
|
287
|
+
The config file (when used) contains:
|
|
266
288
|
|
|
267
289
|
- **Organism paths**: Where each organism's data is stored
|
|
268
290
|
- **Default organism**: Which organism to use when none specified
|
|
@@ -488,7 +510,7 @@ print("Paths:", config)
|
|
|
488
510
|
### Configuration Best Practices
|
|
489
511
|
|
|
490
512
|
**For single-user systems:**
|
|
491
|
-
- Use the default
|
|
513
|
+
- Use the default location (see resolution order above) or set `SEQMAT_CONFIG_FILE` or `SEQMAT_CONFIG_DIR`.
|
|
492
514
|
- Set up organisms as needed with `setup_genomics_data()`
|
|
493
515
|
|
|
494
516
|
**For multi-user or shared systems:**
|
|
@@ -497,8 +519,7 @@ print("Paths:", config)
|
|
|
497
519
|
- Consider using environment variables for paths
|
|
498
520
|
|
|
499
521
|
**For ephemeral environments (e.g. Run.ai, Docker):**
|
|
500
|
-
- Store `config.json` in
|
|
501
|
-
- Set `SEQMAT_CONFIG_DIR` to that directory so SeqMat finds the config even when the rest of the filesystem is ephemeral: `export SEQMAT_CONFIG_DIR=/storage/nicolaslynn/data/seqmat` (then keep `config.json` in that directory).
|
|
522
|
+
- Store `config.json` in persistent storage and point to it: `export SEQMAT_CONFIG_FILE=/path/to/config.json` or `export SEQMAT_CONFIG_DIR=/path/to/dir` (config will be `dir/config.json`).
|
|
502
523
|
|
|
503
524
|
**For development/testing:**
|
|
504
525
|
- Use separate config files or directories
|
|
@@ -661,7 +682,8 @@ $ seqmat summary
|
|
|
661
682
|
### Configuration Management
|
|
662
683
|
|
|
663
684
|
**Core Functions:**
|
|
664
|
-
- `load_config()`: Load configuration from
|
|
685
|
+
- `load_config()`: Load configuration (file path from `get_config_file()`)
|
|
686
|
+
- `get_config_file()`: Return the active config file path
|
|
665
687
|
- `save_config(config)`: Save configuration to file
|
|
666
688
|
- `get_default_organism()`: Get default organism from config
|
|
667
689
|
- `get_available_organisms()`: Get list of all configured organisms
|
|
@@ -690,7 +712,7 @@ save_config(config)
|
|
|
690
712
|
- `list_supported_organisms()`: Get all supported organisms (dynamic from config)
|
|
691
713
|
- `list_available_organisms()`: Get configured organisms
|
|
692
714
|
- `get_organism_info(organism)`: Detailed organism information
|
|
693
|
-
- `setup_genomics_data(basepath, organism=None, force=False)`: Download and setup data (
|
|
715
|
+
- `setup_genomics_data(basepath, organism=None, force=False, pickup=False, n_jobs=None)`: Download and setup data. `n_jobs` controls GTF parsing workers (default: CPU count - 1; use 1 for serial).
|
|
694
716
|
|
|
695
717
|
**Gene Discovery:**
|
|
696
718
|
- `list_gene_biotypes(organism)`: Get available gene types
|
|
@@ -731,8 +753,8 @@ SeqMat is optimized for performance:
|
|
|
731
753
|
## Dependencies
|
|
732
754
|
|
|
733
755
|
**Core (always required):**
|
|
734
|
-
- numpy >= 1.20.0, <3
|
|
735
|
-
- pandas >=
|
|
756
|
+
- numpy >= 1.20.0, <3
|
|
757
|
+
- pandas >= 2.2.0 (required for NumPy 2 compatibility)
|
|
736
758
|
- pysam >= 0.19.0
|
|
737
759
|
- requests >= 2.26.0
|
|
738
760
|
- tqdm >= 4.62.0
|
|
@@ -740,6 +762,7 @@ SeqMat is optimized for performance:
|
|
|
740
762
|
**Optional:**
|
|
741
763
|
- biopython >= 1.79 (for protein translation)
|
|
742
764
|
- gtfparse >= 1.2.0 (for genomics data setup)
|
|
765
|
+
- pyarrow >= 14 (included; used for parquet export in `save_seqmat`)
|
|
743
766
|
|
|
744
767
|
## Examples
|
|
745
768
|
|
|
@@ -198,9 +198,12 @@ For the built-in organisms (hg38, mm39), setup is straightforward:
|
|
|
198
198
|
```python
|
|
199
199
|
from seqmat import setup_genomics_data
|
|
200
200
|
|
|
201
|
-
# Download and setup human genome data
|
|
201
|
+
# Download and setup human genome data (GTF parsing uses multiple cores by default)
|
|
202
202
|
setup_genomics_data("/path/to/your/data", organism="hg38")
|
|
203
203
|
|
|
204
|
+
# Optional: limit or set parallel workers (faster on multi-core machines)
|
|
205
|
+
setup_genomics_data("/path/to/your/data", organism="hg38", n_jobs=8) # or n_jobs=1 for serial
|
|
206
|
+
|
|
204
207
|
# Download and setup mouse genome data
|
|
205
208
|
setup_genomics_data("/path/to/your/data", organism="mm39")
|
|
206
209
|
```
|
|
@@ -216,7 +219,25 @@ seqmat setup --path /path/to/your/data --organism mm39 --force
|
|
|
216
219
|
|
|
217
220
|
### Configuration System
|
|
218
221
|
|
|
219
|
-
|
|
222
|
+
**Config-less mode (no config file):**
|
|
223
|
+
Set **`SEQMAT_DATA_DIR`** to the root path where organism dirs live (e.g. where you ran `setup_genomics_data`):
|
|
224
|
+
|
|
225
|
+
```bash
|
|
226
|
+
export SEQMAT_DATA_DIR=/path/to/seqmat_base # e.g. in .bashrc or .zshrc
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
SeqMat will derive all paths from it: `{SEQMAT_DATA_DIR}/{organism}/genes.db`, `*.fa`, etc. Optional: **`SEQMAT_DEFAULT_ORGANISM`** (default `hg38`). No config file is used or written.
|
|
230
|
+
|
|
231
|
+
**Config file mode** (when `SEQMAT_DATA_DIR` is not set):
|
|
232
|
+
|
|
233
|
+
1. **`SEQMAT_CONFIG_FILE`** – exact path to config.json.
|
|
234
|
+
2. **`SEQMAT_CONFIG_DIR`** – directory; config is `{SEQMAT_CONFIG_DIR}/config.json`.
|
|
235
|
+
3. **Default** – platform config dir (e.g. `~/.config/seqmat/config.json` on Linux).
|
|
236
|
+
|
|
237
|
+
To see which file is used: `from seqmat import get_config_file; print(get_config_file())`.
|
|
238
|
+
To see if config-less: `from seqmat import get_data_base; print(get_data_base())`.
|
|
239
|
+
|
|
240
|
+
The config file (when used) contains:
|
|
220
241
|
|
|
221
242
|
- **Organism paths**: Where each organism's data is stored
|
|
222
243
|
- **Default organism**: Which organism to use when none specified
|
|
@@ -442,7 +463,7 @@ print("Paths:", config)
|
|
|
442
463
|
### Configuration Best Practices
|
|
443
464
|
|
|
444
465
|
**For single-user systems:**
|
|
445
|
-
- Use the default
|
|
466
|
+
- Use the default location (see resolution order above) or set `SEQMAT_CONFIG_FILE` or `SEQMAT_CONFIG_DIR`.
|
|
446
467
|
- Set up organisms as needed with `setup_genomics_data()`
|
|
447
468
|
|
|
448
469
|
**For multi-user or shared systems:**
|
|
@@ -451,8 +472,7 @@ print("Paths:", config)
|
|
|
451
472
|
- Consider using environment variables for paths
|
|
452
473
|
|
|
453
474
|
**For ephemeral environments (e.g. Run.ai, Docker):**
|
|
454
|
-
- Store `config.json` in
|
|
455
|
-
- Set `SEQMAT_CONFIG_DIR` to that directory so SeqMat finds the config even when the rest of the filesystem is ephemeral: `export SEQMAT_CONFIG_DIR=/storage/nicolaslynn/data/seqmat` (then keep `config.json` in that directory).
|
|
475
|
+
- Store `config.json` in persistent storage and point to it: `export SEQMAT_CONFIG_FILE=/path/to/config.json` or `export SEQMAT_CONFIG_DIR=/path/to/dir` (config will be `dir/config.json`).
|
|
456
476
|
|
|
457
477
|
**For development/testing:**
|
|
458
478
|
- Use separate config files or directories
|
|
@@ -615,7 +635,8 @@ $ seqmat summary
|
|
|
615
635
|
### Configuration Management
|
|
616
636
|
|
|
617
637
|
**Core Functions:**
|
|
618
|
-
- `load_config()`: Load configuration from
|
|
638
|
+
- `load_config()`: Load configuration (file path from `get_config_file()`)
|
|
639
|
+
- `get_config_file()`: Return the active config file path
|
|
619
640
|
- `save_config(config)`: Save configuration to file
|
|
620
641
|
- `get_default_organism()`: Get default organism from config
|
|
621
642
|
- `get_available_organisms()`: Get list of all configured organisms
|
|
@@ -644,7 +665,7 @@ save_config(config)
|
|
|
644
665
|
- `list_supported_organisms()`: Get all supported organisms (dynamic from config)
|
|
645
666
|
- `list_available_organisms()`: Get configured organisms
|
|
646
667
|
- `get_organism_info(organism)`: Detailed organism information
|
|
647
|
-
- `setup_genomics_data(basepath, organism=None, force=False)`: Download and setup data (
|
|
668
|
+
- `setup_genomics_data(basepath, organism=None, force=False, pickup=False, n_jobs=None)`: Download and setup data. `n_jobs` controls GTF parsing workers (default: CPU count - 1; use 1 for serial).
|
|
648
669
|
|
|
649
670
|
**Gene Discovery:**
|
|
650
671
|
- `list_gene_biotypes(organism)`: Get available gene types
|
|
@@ -685,8 +706,8 @@ SeqMat is optimized for performance:
|
|
|
685
706
|
## Dependencies
|
|
686
707
|
|
|
687
708
|
**Core (always required):**
|
|
688
|
-
- numpy >= 1.20.0, <3
|
|
689
|
-
- pandas >=
|
|
709
|
+
- numpy >= 1.20.0, <3
|
|
710
|
+
- pandas >= 2.2.0 (required for NumPy 2 compatibility)
|
|
690
711
|
- pysam >= 0.19.0
|
|
691
712
|
- requests >= 2.26.0
|
|
692
713
|
- tqdm >= 4.62.0
|
|
@@ -694,6 +715,7 @@ SeqMat is optimized for performance:
|
|
|
694
715
|
**Optional:**
|
|
695
716
|
- biopython >= 1.79 (for protein translation)
|
|
696
717
|
- gtfparse >= 1.2.0 (for genomics data setup)
|
|
718
|
+
- pyarrow >= 14 (included; used for parquet export in `save_seqmat`)
|
|
697
719
|
|
|
698
720
|
## Examples
|
|
699
721
|
|
|
@@ -5,14 +5,14 @@ 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.
|
|
8
|
+
__version__ = "0.1.51"
|
|
9
9
|
__author__ = "Nicolas Lynn Vila"
|
|
10
10
|
__email__ = "nicolasalynn@gmail.com"
|
|
11
11
|
|
|
12
12
|
from .seqmat import SeqMat
|
|
13
13
|
from .gene import Gene
|
|
14
14
|
from .transcript import Transcript
|
|
15
|
-
from .config import get_default_organism, get_data_dir, get_config_dir
|
|
15
|
+
from .config import get_default_organism, get_data_dir, get_config_dir, get_config_file, get_data_base
|
|
16
16
|
from .lmdb_store import build_lmdb
|
|
17
17
|
from .utils import (
|
|
18
18
|
setup_genomics_data,
|
|
@@ -39,6 +39,8 @@ __all__ = [
|
|
|
39
39
|
"get_default_organism",
|
|
40
40
|
"get_data_dir",
|
|
41
41
|
"get_config_dir",
|
|
42
|
+
"get_config_file",
|
|
43
|
+
"get_data_base",
|
|
42
44
|
"setup_genomics_data",
|
|
43
45
|
"set_fasta_path",
|
|
44
46
|
"load_config",
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Configuration management for SeqMat.
|
|
2
|
+
|
|
3
|
+
Config-less mode (no config file):
|
|
4
|
+
- SEQMAT_DATA_DIR → root path where organism dirs live (e.g. /path/to/seqmat_base).
|
|
5
|
+
All paths are derived: {SEQMAT_DATA_DIR}/{organism}/genes.db, *.fa, etc.
|
|
6
|
+
Set SEQMAT_DEFAULT_ORGANISM for default (default: hg38). No config file needed.
|
|
7
|
+
|
|
8
|
+
Config file mode (when SEQMAT_DATA_DIR is not set):
|
|
9
|
+
1. SEQMAT_CONFIG_FILE → exact path to config.json
|
|
10
|
+
2. SEQMAT_CONFIG_DIR → directory; config is {SEQMAT_CONFIG_DIR}/config.json
|
|
11
|
+
3. Default → platformdirs user config dir
|
|
12
|
+
"""
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Dict, Any, List, Optional
|
|
17
|
+
|
|
18
|
+
from platformdirs import user_config_dir, user_data_dir
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _resolve_config_file() -> Path:
|
|
22
|
+
"""Single place for config file path. Env overrides, else default dir + config.json."""
|
|
23
|
+
env_file = os.environ.get("SEQMAT_CONFIG_FILE", "").strip()
|
|
24
|
+
if env_file:
|
|
25
|
+
return Path(env_file)
|
|
26
|
+
env_dir = os.environ.get("SEQMAT_CONFIG_DIR", "").strip()
|
|
27
|
+
if env_dir:
|
|
28
|
+
return Path(env_dir) / "config.json"
|
|
29
|
+
return Path(user_config_dir("seqmat", appauthor=False)) / "config.json"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
CONFIG_FILE = _resolve_config_file()
|
|
33
|
+
DEFAULT_CONFIG_DIR = CONFIG_FILE.parent
|
|
34
|
+
DEFAULT_DATA_DIR = Path(user_data_dir("seqmat", appauthor=False))
|
|
35
|
+
|
|
36
|
+
DEFAULT_ORGANISM_DATA = {
|
|
37
|
+
'hg38': {
|
|
38
|
+
'name': 'Homo sapiens (Human)',
|
|
39
|
+
'urls': {
|
|
40
|
+
'fasta': 'https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/latest/hg38.fa.gz',
|
|
41
|
+
'gtf': 'https://ftp.ensembl.org/pub/release-111/gtf/homo_sapiens/Homo_sapiens.GRCh38.111.gtf.gz',
|
|
42
|
+
'conservation': 'https://genome-data-public-access.s3.eu-north-1.amazonaws.com/conservation.pkl',
|
|
43
|
+
'gtex': 'https://storage.googleapis.com/adult-gtex/bulk-gex/v8/rna-seq/GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct.gz'
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
'mm39': {
|
|
47
|
+
'name': 'Mus musculus (Mouse)',
|
|
48
|
+
'urls': {
|
|
49
|
+
'fasta': 'https://hgdownload.soe.ucsc.edu/goldenPath/mm39/bigZips/mm39.fa.gz',
|
|
50
|
+
'gtf': 'https://ftp.ensembl.org/pub/release-112/gtf/mus_musculus/Mus_musculus.GRCm39.112.gtf.gz'
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
DEFAULT_SETTINGS = {
|
|
56
|
+
'default_organism': 'hg38',
|
|
57
|
+
'directory_structure': {
|
|
58
|
+
'chromosomes': 'chromosomes',
|
|
59
|
+
'annotations': 'annotations'
|
|
60
|
+
},
|
|
61
|
+
'gene_lmdb_path': None,
|
|
62
|
+
'gene_lmdb_local_staging': False,
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
def load_config() -> Dict[str, Any]:
|
|
66
|
+
"""Load config from CONFIG_FILE, merged with DEFAULT_SETTINGS."""
|
|
67
|
+
if CONFIG_FILE.exists():
|
|
68
|
+
with open(CONFIG_FILE, "r") as f:
|
|
69
|
+
config = json.load(f)
|
|
70
|
+
merged_config = DEFAULT_SETTINGS.copy()
|
|
71
|
+
merged_config.update(config)
|
|
72
|
+
return merged_config
|
|
73
|
+
return DEFAULT_SETTINGS.copy()
|
|
74
|
+
|
|
75
|
+
def save_config(config: Dict[str, Any]) -> None:
|
|
76
|
+
"""Save config to CONFIG_FILE (creates parent dir if needed)."""
|
|
77
|
+
CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
with open(CONFIG_FILE, "w") as f:
|
|
79
|
+
json.dump(config, f, indent=2)
|
|
80
|
+
|
|
81
|
+
def get_data_base() -> Optional[Path]:
|
|
82
|
+
"""If SEQMAT_DATA_DIR is set and exists, return that path (config-less mode). Else None."""
|
|
83
|
+
env = os.environ.get("SEQMAT_DATA_DIR", "").strip()
|
|
84
|
+
if not env:
|
|
85
|
+
return None
|
|
86
|
+
p = Path(env).expanduser().resolve()
|
|
87
|
+
return p if p.exists() else None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def get_default_organism() -> str:
|
|
91
|
+
"""Default organism: from SEQMAT_DEFAULT_ORGANISM in config-less mode, else from config file."""
|
|
92
|
+
if get_data_base() is not None:
|
|
93
|
+
return os.environ.get("SEQMAT_DEFAULT_ORGANISM", "").strip() or "hg38"
|
|
94
|
+
config = load_config()
|
|
95
|
+
return config.get('default_organism', DEFAULT_SETTINGS['default_organism'])
|
|
96
|
+
|
|
97
|
+
NON_ORGANISM_KEYS = {"default_organism", "directory_structure", "gene_lmdb_path", "gene_lmdb_local_staging"}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def get_available_organisms() -> List[str]:
|
|
101
|
+
"""Organism IDs: in config-less mode, subdirs of SEQMAT_DATA_DIR that contain genes.db; else from config."""
|
|
102
|
+
base = get_data_base()
|
|
103
|
+
if base is not None:
|
|
104
|
+
organisms = []
|
|
105
|
+
for d in base.iterdir():
|
|
106
|
+
if d.is_dir() and (d / "genes.db").exists():
|
|
107
|
+
organisms.append(d.name)
|
|
108
|
+
return sorted(organisms) if organisms else list(DEFAULT_ORGANISM_DATA.keys())
|
|
109
|
+
config = load_config()
|
|
110
|
+
configured_organisms = set(config.keys()) - NON_ORGANISM_KEYS
|
|
111
|
+
default_organisms = set(DEFAULT_ORGANISM_DATA.keys())
|
|
112
|
+
return sorted(configured_organisms | default_organisms)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def get_organism_info(organism: str) -> Dict[str, Any]:
|
|
116
|
+
"""Organism metadata (name, URLs) from DEFAULT_ORGANISM_DATA; paths from get_organism_config in config-less mode."""
|
|
117
|
+
if organism in DEFAULT_ORGANISM_DATA:
|
|
118
|
+
return DEFAULT_ORGANISM_DATA[organism].copy()
|
|
119
|
+
if get_data_base() is not None and organism in get_available_organisms():
|
|
120
|
+
return {"name": organism, "urls": {}}
|
|
121
|
+
config = load_config()
|
|
122
|
+
if organism in config and isinstance(config[organism], dict):
|
|
123
|
+
org_config = config[organism]
|
|
124
|
+
if organism in DEFAULT_ORGANISM_DATA:
|
|
125
|
+
out = DEFAULT_ORGANISM_DATA[organism].copy()
|
|
126
|
+
out.update(org_config)
|
|
127
|
+
return out
|
|
128
|
+
return org_config
|
|
129
|
+
raise ValueError(f"Organism '{organism}' not configured. Available: {get_available_organisms()}")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _organism_config_from_data_base(organism: str, base: Path) -> Dict[str, Path]:
|
|
133
|
+
"""Build path dict from data base + organism (no config file). Hardcoded layout."""
|
|
134
|
+
org_path = base / organism
|
|
135
|
+
if not org_path.exists():
|
|
136
|
+
raise ValueError(f"Organism '{organism}' not found under {base}. Run setup_genomics_data() first.")
|
|
137
|
+
# Fasta: single .fa file in organism dir (from setup)
|
|
138
|
+
fa_files = list(org_path.glob("*.fa"))
|
|
139
|
+
config = {
|
|
140
|
+
"BASE": org_path,
|
|
141
|
+
"MRNA_PATH": org_path,
|
|
142
|
+
"CHROM_SOURCE": org_path,
|
|
143
|
+
"genes_db": org_path / "genes.db",
|
|
144
|
+
"MISSPLICING_PATH": org_path / "missplicing",
|
|
145
|
+
"ONCOSPLICE_PATH": org_path / "oncosplice",
|
|
146
|
+
"TEMP": org_path / "temp",
|
|
147
|
+
}
|
|
148
|
+
if fa_files:
|
|
149
|
+
config["fasta_full_genome"] = fa_files[0]
|
|
150
|
+
return config
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def get_organism_config(organism: Optional[str] = None) -> Dict[str, Path]:
|
|
154
|
+
"""Return path config for an organism. In config-less mode (SEQMAT_DATA_DIR), paths are derived from it."""
|
|
155
|
+
if organism is None:
|
|
156
|
+
organism = get_default_organism()
|
|
157
|
+
base = get_data_base()
|
|
158
|
+
if base is not None:
|
|
159
|
+
return _organism_config_from_data_base(organism, base)
|
|
160
|
+
config = load_config()
|
|
161
|
+
if organism not in config:
|
|
162
|
+
raise ValueError(f"Organism '{organism}' not configured. Run setup_genomics_data() first.")
|
|
163
|
+
org_config = config[organism]
|
|
164
|
+
if isinstance(org_config, str):
|
|
165
|
+
raise ValueError(f"Invalid configuration for organism '{organism}'. Expected dictionary.")
|
|
166
|
+
if not isinstance(org_config, dict):
|
|
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)}
|
|
169
|
+
|
|
170
|
+
def get_directory_config() -> Dict[str, str]:
|
|
171
|
+
"""Return directory_structure (e.g. chromosomes, annotations folder names)."""
|
|
172
|
+
config = load_config()
|
|
173
|
+
return config.get('directory_structure', DEFAULT_SETTINGS['directory_structure'])
|
|
174
|
+
|
|
175
|
+
def get_data_dir() -> Path:
|
|
176
|
+
"""Return user data directory for seqmat (platformdirs)."""
|
|
177
|
+
return DEFAULT_DATA_DIR
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def get_config_dir() -> Path:
|
|
181
|
+
"""Return the directory containing the active config file."""
|
|
182
|
+
return DEFAULT_CONFIG_DIR
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def get_config_file() -> Path:
|
|
186
|
+
"""Return the active config file path (for display or override)."""
|
|
187
|
+
return CONFIG_FILE
|
|
@@ -102,6 +102,20 @@ class Gene:
|
|
|
102
102
|
)
|
|
103
103
|
except ImportError:
|
|
104
104
|
pass
|
|
105
|
+
try:
|
|
106
|
+
from .sqlite_store import load_gene_from_sqlite
|
|
107
|
+
data = load_gene_from_sqlite(gene_name, organism)
|
|
108
|
+
if data is not None:
|
|
109
|
+
return cls(
|
|
110
|
+
gene_name=data.get('gene_name'),
|
|
111
|
+
gene_id=data.get('gene_id'),
|
|
112
|
+
rev=data.get('rev'),
|
|
113
|
+
chrm=data.get('chrm'),
|
|
114
|
+
transcripts=data.get('transcripts', {}),
|
|
115
|
+
organism=organism
|
|
116
|
+
)
|
|
117
|
+
except ImportError:
|
|
118
|
+
pass
|
|
105
119
|
try:
|
|
106
120
|
config = get_organism_config(organism)
|
|
107
121
|
except ValueError:
|
|
@@ -141,22 +141,21 @@ class SeqMat:
|
|
|
141
141
|
"""
|
|
142
142
|
if source_fasta is None:
|
|
143
143
|
config = get_organism_config(genome)
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
# Fall back to full genome FASTA if no chromosome file found
|
|
144
|
+
# Prefer single full-genome FASTA (no per-chromosome split needed)
|
|
145
|
+
source_fasta = config.get('fasta_full_genome') or config.get('fasta')
|
|
146
|
+
if source_fasta is None:
|
|
147
|
+
# Fall back to per-chromosome files for backward compatibility
|
|
148
|
+
chrom_source = config.get('CHROM_SOURCE')
|
|
149
|
+
if chrom_source:
|
|
150
|
+
chrom_path = Path(chrom_source)
|
|
151
|
+
chrom_file = chrom_path / f"{chrom}.fasta"
|
|
152
|
+
if chrom_file.exists():
|
|
153
|
+
source_fasta = chrom_file
|
|
155
154
|
if source_fasta is None:
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
155
|
+
raise ValueError(
|
|
156
|
+
f"No FASTA configured for genome '{genome}'. Set 'fasta_full_genome' or 'fasta' in config, "
|
|
157
|
+
f"or provide per-chromosome files in CHROM_SOURCE. Run setup_genomics_data() or set_fasta_path()."
|
|
158
|
+
)
|
|
160
159
|
|
|
161
160
|
fasta = pysam.FastaFile(str(source_fasta))
|
|
162
161
|
seq = fasta.fetch(f'{chrom}', start-1, end).upper()
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""SQLite backend for gene data loading.
|
|
2
|
+
|
|
3
|
+
When setup writes annotations/genes.db, Gene.from_file() tries SQLite first (after LMDB),
|
|
4
|
+
then falls back to per-gene pickle files. Single indexed DB for fast lookups.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import pickle
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Dict, Optional
|
|
10
|
+
|
|
11
|
+
from .config import get_organism_config, get_default_organism, load_config
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_genes_db_path(organism: Optional[str] = None) -> Optional[str]:
|
|
15
|
+
"""Return genes_db path from config if set and file exists; else None."""
|
|
16
|
+
if organism is None:
|
|
17
|
+
organism = get_default_organism()
|
|
18
|
+
try:
|
|
19
|
+
config = get_organism_config(organism)
|
|
20
|
+
except ValueError:
|
|
21
|
+
return None
|
|
22
|
+
path = config.get("genes_db")
|
|
23
|
+
if not path:
|
|
24
|
+
return None
|
|
25
|
+
p = Path(path)
|
|
26
|
+
return str(p) if p.exists() else None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def load_gene_from_sqlite(gene_name: str, organism: Optional[str] = None) -> Optional[Dict[str, Any]]:
|
|
30
|
+
"""Load gene dict from genes.db if configured; otherwise return None."""
|
|
31
|
+
db_path = get_genes_db_path(organism)
|
|
32
|
+
if not db_path:
|
|
33
|
+
return None
|
|
34
|
+
try:
|
|
35
|
+
import sqlite3
|
|
36
|
+
conn = sqlite3.connect(db_path)
|
|
37
|
+
conn.row_factory = sqlite3.Row
|
|
38
|
+
cursor = conn.execute(
|
|
39
|
+
"SELECT data FROM genes WHERE UPPER(gene_name) = UPPER(?) LIMIT 1",
|
|
40
|
+
(gene_name.strip(),),
|
|
41
|
+
)
|
|
42
|
+
row = cursor.fetchone()
|
|
43
|
+
conn.close()
|
|
44
|
+
if row is None:
|
|
45
|
+
return None
|
|
46
|
+
return pickle.loads(row["data"])
|
|
47
|
+
except Exception:
|
|
48
|
+
return None
|
|
@@ -196,14 +196,37 @@ class Transcript:
|
|
|
196
196
|
upstream: int = 0,
|
|
197
197
|
downstream: int = 0,
|
|
198
198
|
) -> Dict[str, Any]:
|
|
199
|
-
"""Pre-mRNA sequence from FASTA. Optional upstream/downstream
|
|
199
|
+
"""Pre-mRNA sequence from the single full-genome FASTA (e.g. hg38.fa). Optional upstream/downstream."""
|
|
200
200
|
if fasta_path is None:
|
|
201
201
|
config = get_organism_config(self.organism)
|
|
202
|
-
|
|
202
|
+
# Single full-genome FASTA only (no per-chromosome files in current setup)
|
|
203
|
+
fasta_path = config.get("fasta_full_genome") or config.get("fasta")
|
|
204
|
+
if fasta_path is None:
|
|
205
|
+
# Legacy: per-chromosome files under CHROM_SOURCE
|
|
206
|
+
fasta_path = config.get("CHROM_SOURCE") and (Path(config["CHROM_SOURCE"]) / f"chr{self.chrm}.fasta")
|
|
207
|
+
fasta_path = Path(fasta_path) if fasta_path else None
|
|
208
|
+
if not fasta_path or not fasta_path.exists():
|
|
209
|
+
raise ValueError(
|
|
210
|
+
"No FASTA path in config (fasta_full_genome or fasta). "
|
|
211
|
+
"Run setup_genomics_data() to install the full-genome FASTA (e.g. hg38.fa)."
|
|
212
|
+
)
|
|
213
|
+
# Full-genome FASTA: UCSC uses chr17, Ensembl sometimes 17 — try both
|
|
214
|
+
raw_chr = str(self.chrm).replace("chr", "") or "17"
|
|
215
|
+
with_chr = f"chr{raw_chr}"
|
|
216
|
+
contigs_to_try = [with_chr, raw_chr] if with_chr != raw_chr else [with_chr]
|
|
203
217
|
start = max(1, self.transcript_lower - upstream)
|
|
204
218
|
end = self.transcript_upper + downstream
|
|
205
|
-
|
|
206
|
-
|
|
219
|
+
last_err = None
|
|
220
|
+
for contig in contigs_to_try:
|
|
221
|
+
try:
|
|
222
|
+
seq_mat = SeqMat.from_fasta_file(fasta_path, contig, start, end)
|
|
223
|
+
if len(seq_mat.seq) > 0:
|
|
224
|
+
return {"seq": seq_mat.seq, "indices": seq_mat.index}
|
|
225
|
+
except Exception as e:
|
|
226
|
+
last_err = e
|
|
227
|
+
if last_err is not None:
|
|
228
|
+
raise last_err
|
|
229
|
+
raise ValueError(f"Could not fetch {self.chrm}:{start}-{end} from FASTA (tried contigs {contigs_to_try})")
|
|
207
230
|
|
|
208
231
|
def generate_pre_mrna(
|
|
209
232
|
self,
|