OpenSpliceai 0.0.1__py3-none-any.whl
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.
- OpenSpliceai-0.0.1.dist-info/LICENSE +674 -0
- OpenSpliceai-0.0.1.dist-info/METADATA +177 -0
- OpenSpliceai-0.0.1.dist-info/RECORD +42 -0
- OpenSpliceai-0.0.1.dist-info/WHEEL +5 -0
- OpenSpliceai-0.0.1.dist-info/entry_points.txt +2 -0
- OpenSpliceai-0.0.1.dist-info/top_level.txt +1 -0
- openspliceai/__init__.py +1 -0
- openspliceai/calibrate/__init__.py +0 -0
- openspliceai/calibrate/calibrate.py +85 -0
- openspliceai/calibrate/calibrate_utils.py +42 -0
- openspliceai/calibrate/model_utils.py +59 -0
- openspliceai/calibrate/temperature_scaling.py +211 -0
- openspliceai/calibrate/visualization.py +99 -0
- openspliceai/constants.py +14 -0
- openspliceai/create_data/__init__.py +0 -0
- openspliceai/create_data/create_datafile.py +159 -0
- openspliceai/create_data/create_dataset.py +64 -0
- openspliceai/create_data/paralogs.py +81 -0
- openspliceai/create_data/utils.py +254 -0
- openspliceai/create_data/verify_h5_file.py +61 -0
- openspliceai/header.py +11 -0
- openspliceai/merge_data/__init__.py +0 -0
- openspliceai/merge_data/merge_dataset.py +103 -0
- openspliceai/openspliceai.py +197 -0
- openspliceai/predict/__init__.py +0 -0
- openspliceai/predict/predict.py +1091 -0
- openspliceai/predict/utils.py +53 -0
- openspliceai/test/__init__.py +0 -0
- openspliceai/test/spliceai.py +45 -0
- openspliceai/test/test.py +92 -0
- openspliceai/train/__init__.py +0 -0
- openspliceai/train/train.py +76 -0
- openspliceai/train_base/__init__.py +0 -0
- openspliceai/train_base/spliceai.py +61 -0
- openspliceai/train_base/utils.py +644 -0
- openspliceai/transfer/__init__.py +0 -0
- openspliceai/transfer/transfer.py +107 -0
- openspliceai/variant/__init__.py +0 -0
- openspliceai/variant/get_anno.py +129 -0
- openspliceai/variant/test.py +31 -0
- openspliceai/variant/utils.py +541 -0
- openspliceai/variant/variant.py +89 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import h5py
|
|
3
|
+
import os, sys
|
|
4
|
+
import numpy as np
|
|
5
|
+
import torch
|
|
6
|
+
import torch.nn as nn
|
|
7
|
+
import torch.optim as optim
|
|
8
|
+
from torch.utils.data import TensorDataset, DataLoader
|
|
9
|
+
from tqdm import tqdm
|
|
10
|
+
import platform
|
|
11
|
+
from openspliceai.train_base.spliceai import *
|
|
12
|
+
from openspliceai.train_base.utils import *
|
|
13
|
+
from openspliceai.constants import *
|
|
14
|
+
import h5py
|
|
15
|
+
import time
|
|
16
|
+
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def initialize_model_and_optim_transfer(device, flanking_size, epochs, scheduler,
|
|
20
|
+
pretrained_model, unfreeze, unfreeze_all):
|
|
21
|
+
L = 32
|
|
22
|
+
N_GPUS = 2
|
|
23
|
+
W = np.asarray([11, 11, 11, 11])
|
|
24
|
+
AR = np.asarray([1, 1, 1, 1])
|
|
25
|
+
BATCH_SIZE = 18 * N_GPUS
|
|
26
|
+
if int(flanking_size) == 80:
|
|
27
|
+
W = np.asarray([11, 11, 11, 11])
|
|
28
|
+
AR = np.asarray([1, 1, 1, 1])
|
|
29
|
+
BATCH_SIZE = 18 * N_GPUS
|
|
30
|
+
elif int(flanking_size) == 400:
|
|
31
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11])
|
|
32
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4])
|
|
33
|
+
BATCH_SIZE = 18 * N_GPUS
|
|
34
|
+
elif int(flanking_size) == 2000:
|
|
35
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11,
|
|
36
|
+
21, 21, 21, 21])
|
|
37
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4,
|
|
38
|
+
10, 10, 10, 10])
|
|
39
|
+
BATCH_SIZE = 12 * N_GPUS
|
|
40
|
+
elif int(flanking_size) == 10000:
|
|
41
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11,
|
|
42
|
+
21, 21, 21, 21, 41, 41, 41, 41])
|
|
43
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4,
|
|
44
|
+
10, 10, 10, 10, 25, 25, 25, 25])
|
|
45
|
+
BATCH_SIZE = 6 * N_GPUS
|
|
46
|
+
CL = 2 * np.sum(AR * (W - 1))
|
|
47
|
+
print("\033[1mContext nucleotides: %d\033[0m" % (CL))
|
|
48
|
+
print("\033[1mSequence length (output): %d\033[0m" % (SL))
|
|
49
|
+
# Initialize the model
|
|
50
|
+
model = SpliceAI(L, W, AR).to(device)
|
|
51
|
+
# Print the shapes of the parameters in the initialized model
|
|
52
|
+
print("\nInitialized model parameter shapes:")
|
|
53
|
+
for name, param in model.named_parameters():
|
|
54
|
+
print(f"{name}: {param.shape}", end=", ")
|
|
55
|
+
|
|
56
|
+
# Load the pretrained model
|
|
57
|
+
state_dict = torch.load(pretrained_model, map_location=device)
|
|
58
|
+
|
|
59
|
+
# Filter out unnecessary keys and load matching keys into model
|
|
60
|
+
model_dict = model.state_dict()
|
|
61
|
+
state_dict = {k: v for k, v in state_dict.items() if k in model_dict and v.size() == model_dict[k].size()}
|
|
62
|
+
|
|
63
|
+
# Load state dict into the model
|
|
64
|
+
missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
|
|
65
|
+
|
|
66
|
+
# Print missing and unexpected keys
|
|
67
|
+
print("\nMissing keys:", missing_keys)
|
|
68
|
+
print("Unexpected keys:", unexpected_keys)
|
|
69
|
+
|
|
70
|
+
print("\n unfreeze_all:", unfreeze_all)
|
|
71
|
+
if not unfreeze_all:
|
|
72
|
+
# Freeze all layers first
|
|
73
|
+
for param in model.parameters():
|
|
74
|
+
param.requires_grad = False
|
|
75
|
+
# Unfreeze the last `unfreeze` layers
|
|
76
|
+
if unfreeze > 0:
|
|
77
|
+
# Unfreeze the last few layers (example: last residual unit)
|
|
78
|
+
for param in model.residual_units[-unfreeze].parameters():
|
|
79
|
+
param.requires_grad = True
|
|
80
|
+
# Set up optimizer and scheduler
|
|
81
|
+
optimizer = optim.AdamW(filter(lambda p: p.requires_grad, model.parameters()), lr=1e-4)
|
|
82
|
+
if scheduler == "MultiStepLR":
|
|
83
|
+
scheduler_obj = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[epochs-4, epochs-3, epochs-2, epochs-1], gamma=0.5)
|
|
84
|
+
elif scheduler == "CosineAnnealingWarmRestarts":
|
|
85
|
+
scheduler_obj = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(
|
|
86
|
+
optimizer, T_0=5, T_mult=1, eta_min=1e-5, last_epoch=-1)
|
|
87
|
+
params = {'L': L, 'W': W, 'AR': AR, 'CL': CL, 'SL': SL, 'BATCH_SIZE': BATCH_SIZE, 'N_GPUS': N_GPUS}
|
|
88
|
+
return model, optimizer, scheduler_obj, params
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def transfer(args):
|
|
92
|
+
print('Running OpenSpliceAI with transfer mode.')
|
|
93
|
+
# assert training_target in ["RefSeq", "MANE", "SpliceAI", "SpliceAI27"]
|
|
94
|
+
device = setup_environment(args)
|
|
95
|
+
model_output_base, log_output_train_base, log_output_val_base, log_output_test_base = initialize_paths(args)
|
|
96
|
+
train_h5f, test_h5f, batch_num = load_datasets(args)
|
|
97
|
+
train_idxs, val_idxs, test_idxs = generate_indices(batch_num, args.random_seed, test_h5f)
|
|
98
|
+
model, optimizer, scheduler, params = initialize_model_and_optim_transfer(device, args.flanking_size, args.epochs, args.scheduler, args.pretrained_model, args.unfreeze, args.unfreeze_all)
|
|
99
|
+
|
|
100
|
+
params["RANDOM_SEED"] = args.random_seed
|
|
101
|
+
train_metric_files = create_metric_files(log_output_train_base)
|
|
102
|
+
valid_metric_files = create_metric_files(log_output_val_base)
|
|
103
|
+
test_metric_files = create_metric_files(log_output_test_base)
|
|
104
|
+
train_model(model, optimizer, scheduler, train_h5f, test_h5f, train_idxs,
|
|
105
|
+
val_idxs, test_idxs, model_output_base, args, device, params, train_metric_files, valid_metric_files, test_metric_files)
|
|
106
|
+
train_h5f.close()
|
|
107
|
+
test_h5f.close()
|
|
File without changes
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import gffutils
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
def parse_arguments():
|
|
6
|
+
parser = argparse.ArgumentParser(description="Convert GFF file to custom tabular format.")
|
|
7
|
+
parser.add_argument(
|
|
8
|
+
"--gff",
|
|
9
|
+
required=True,
|
|
10
|
+
help="Path to the input GFF file (e.g., data/GRCh38_chr21_chr22.gff)."
|
|
11
|
+
)
|
|
12
|
+
parser.add_argument(
|
|
13
|
+
"--output",
|
|
14
|
+
required=True,
|
|
15
|
+
help="Path to the output custom annotation file (e.g., data/grch38_chr21_chr22.txt)."
|
|
16
|
+
)
|
|
17
|
+
parser.add_argument(
|
|
18
|
+
"--db",
|
|
19
|
+
default=None,
|
|
20
|
+
help="Path to the temporary GFF database. If not provided, a temporary database will be created."
|
|
21
|
+
)
|
|
22
|
+
return parser.parse_args()
|
|
23
|
+
|
|
24
|
+
def create_gff_database(gff_file, db_file=None):
|
|
25
|
+
"""
|
|
26
|
+
Create a gffutils database from the GFF file.
|
|
27
|
+
If db_file is None, a temporary in-memory database is created.
|
|
28
|
+
"""
|
|
29
|
+
if db_file and os.path.exists(db_file):
|
|
30
|
+
print(f"Connecting to existing GFF database: {db_file}")
|
|
31
|
+
db = gffutils.FeatureDB(db_file)
|
|
32
|
+
else:
|
|
33
|
+
if db_file:
|
|
34
|
+
print(f"Creating new GFF database: {db_file}")
|
|
35
|
+
else:
|
|
36
|
+
print("Creating in-memory GFF database.")
|
|
37
|
+
db = gffutils.create_db(
|
|
38
|
+
gff_file,
|
|
39
|
+
dbfn=db_file if db_file else ":memory:",
|
|
40
|
+
force=True,
|
|
41
|
+
keep_order=True,
|
|
42
|
+
merge_strategy='create_unique',
|
|
43
|
+
sort_attribute_values=True,
|
|
44
|
+
verbose=True
|
|
45
|
+
)
|
|
46
|
+
return db
|
|
47
|
+
|
|
48
|
+
def extract_gene_info(db):
|
|
49
|
+
"""
|
|
50
|
+
Extract gene information from the GFF database.
|
|
51
|
+
Returns a list of dictionaries containing gene details.
|
|
52
|
+
"""
|
|
53
|
+
gene_data = []
|
|
54
|
+
for gene in db.features_of_type('gene'):
|
|
55
|
+
# extract gene name
|
|
56
|
+
gene_name = None
|
|
57
|
+
for key in ['gene_name', 'Name', 'gene', 'ID']:
|
|
58
|
+
if key in gene.attributes:
|
|
59
|
+
gene_name = gene.attributes[key][0]
|
|
60
|
+
break
|
|
61
|
+
if not gene_name:
|
|
62
|
+
gene_name = gene.id # fallback to gene ID if name not available
|
|
63
|
+
|
|
64
|
+
chrom = gene.seqid
|
|
65
|
+
strand = gene.strand
|
|
66
|
+
tx_start = gene.start
|
|
67
|
+
tx_end = gene.end
|
|
68
|
+
|
|
69
|
+
# Extract exons
|
|
70
|
+
exons = list(db.children(gene, featuretype='exon', order_by='start'))
|
|
71
|
+
if not exons:
|
|
72
|
+
continue # Skip genes without exons
|
|
73
|
+
|
|
74
|
+
exon_starts = []
|
|
75
|
+
exon_ends = []
|
|
76
|
+
for exon in exons:
|
|
77
|
+
exon_starts.append(str(exon.start))
|
|
78
|
+
exon_ends.append(str(exon.end))
|
|
79
|
+
|
|
80
|
+
# Concatenate exon positions with commas
|
|
81
|
+
exon_start_str = ",".join(exon_starts) + ","
|
|
82
|
+
exon_end_str = ",".join(exon_ends) + ","
|
|
83
|
+
|
|
84
|
+
gene_entry = {
|
|
85
|
+
"NAME": gene_name,
|
|
86
|
+
"CHROM": chrom,
|
|
87
|
+
"STRAND": strand,
|
|
88
|
+
"TX_START": tx_start,
|
|
89
|
+
"TX_END": tx_end,
|
|
90
|
+
"EXON_START": exon_start_str,
|
|
91
|
+
"EXON_END": exon_end_str
|
|
92
|
+
}
|
|
93
|
+
gene_data.append(gene_entry)
|
|
94
|
+
return gene_data
|
|
95
|
+
|
|
96
|
+
def write_output(gene_data, output_file):
|
|
97
|
+
"""
|
|
98
|
+
Write the extracted gene information to the output file in tab-separated format.
|
|
99
|
+
"""
|
|
100
|
+
header = ["#NAME", "CHROM", "STRAND", "TX_START", "TX_END", "EXON_START", "EXON_END"]
|
|
101
|
+
with open(output_file, "w") as out_f:
|
|
102
|
+
out_f.write("\t".join(header) + "\n")
|
|
103
|
+
for gene in gene_data:
|
|
104
|
+
row = [
|
|
105
|
+
gene["NAME"],
|
|
106
|
+
gene["CHROM"],
|
|
107
|
+
gene["STRAND"],
|
|
108
|
+
str(gene["TX_START"]),
|
|
109
|
+
str(gene["TX_END"]),
|
|
110
|
+
gene["EXON_START"],
|
|
111
|
+
gene["EXON_END"]
|
|
112
|
+
]
|
|
113
|
+
out_f.write("\t".join(row) + "\n")
|
|
114
|
+
print(f"Output written to {output_file}")
|
|
115
|
+
|
|
116
|
+
def main():
|
|
117
|
+
args = parse_arguments()
|
|
118
|
+
|
|
119
|
+
# Create or connect to GFF database
|
|
120
|
+
db = create_gff_database(args.gff, args.db)
|
|
121
|
+
|
|
122
|
+
# Extract gene information
|
|
123
|
+
gene_data = extract_gene_info(db)
|
|
124
|
+
|
|
125
|
+
# Write to output file
|
|
126
|
+
write_output(gene_data, args.output)
|
|
127
|
+
|
|
128
|
+
if __name__ == "__main__":
|
|
129
|
+
main()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import pysam
|
|
2
|
+
from openspliceai.variant.utils import *
|
|
3
|
+
|
|
4
|
+
# vcf = pysam.VariantFile('test.vcf')
|
|
5
|
+
|
|
6
|
+
# import torch
|
|
7
|
+
# from collections import OrderedDict
|
|
8
|
+
|
|
9
|
+
# # Load the state_dict
|
|
10
|
+
# state_dict = torch.load('models/spliceai-mane/400nt/model_400nt_rs42.pt')
|
|
11
|
+
|
|
12
|
+
# # Print the keys in the state_dict
|
|
13
|
+
# print("State_dict keys:")
|
|
14
|
+
# for key in state_dict.keys():
|
|
15
|
+
# print(key)
|
|
16
|
+
|
|
17
|
+
# # Assume `YourModelClass` is your model class
|
|
18
|
+
# device = setup_device()
|
|
19
|
+
# model, params = load_model(device, 400)
|
|
20
|
+
|
|
21
|
+
# # Print model's named parameters
|
|
22
|
+
# print("\nModel's named parameters:")
|
|
23
|
+
# for name, param in model.named_parameters():
|
|
24
|
+
# print(name, param)
|
|
25
|
+
|
|
26
|
+
# # Optionally, load state_dict with strict=False
|
|
27
|
+
# try:
|
|
28
|
+
# model.load_state_dict(state_dict, strict=False)
|
|
29
|
+
# print("Model loaded successfully with strict=False.")
|
|
30
|
+
# except Exception as e:
|
|
31
|
+
# print(f"Error loading model with strict=False: {e}")
|