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,541 @@
|
|
|
1
|
+
from importlib.resources import files
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
from pyfaidx import Fasta
|
|
5
|
+
import logging
|
|
6
|
+
import platform
|
|
7
|
+
import os, glob
|
|
8
|
+
from openspliceai.train_base.spliceai import SpliceAI
|
|
9
|
+
from openspliceai.constants import *
|
|
10
|
+
from openspliceai.predict.predict import *
|
|
11
|
+
from openspliceai.predict.utils import *
|
|
12
|
+
|
|
13
|
+
##############################################
|
|
14
|
+
## LOADING PYTORCH AND KERAS MODELS
|
|
15
|
+
##############################################
|
|
16
|
+
|
|
17
|
+
def setup_device():
|
|
18
|
+
"""Select computation device based on availability."""
|
|
19
|
+
device_str = "cuda" if torch.cuda.is_available() else "mps" if platform.system() == "Darwin" else "cpu"
|
|
20
|
+
return torch.device(device_str)
|
|
21
|
+
|
|
22
|
+
def load_pytorch_models(model_path, CL):
|
|
23
|
+
"""
|
|
24
|
+
Loads a SpliceAI PyTorch model from given state, inferring device.
|
|
25
|
+
|
|
26
|
+
Params:
|
|
27
|
+
- model_path (str): Path to the model state dict, or a directory of models
|
|
28
|
+
- CL (int): Context length parameter for model conversion.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
- loaded_models (list): SpliceAI model(s) loaded with given state.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def load_model(device, flanking_size):
|
|
35
|
+
"""Loads the given model."""
|
|
36
|
+
# Hyper-parameters:
|
|
37
|
+
# L: Number of convolution kernels
|
|
38
|
+
# W: Convolution window size in each residual unit
|
|
39
|
+
# AR: Atrous rate in each residual unit
|
|
40
|
+
L = 32
|
|
41
|
+
W = np.asarray([11, 11, 11, 11])
|
|
42
|
+
AR = np.asarray([1, 1, 1, 1])
|
|
43
|
+
N_GPUS = 2
|
|
44
|
+
BATCH_SIZE = 18*N_GPUS
|
|
45
|
+
|
|
46
|
+
if int(flanking_size) == 80:
|
|
47
|
+
W = np.asarray([11, 11, 11, 11])
|
|
48
|
+
AR = np.asarray([1, 1, 1, 1])
|
|
49
|
+
BATCH_SIZE = 18*N_GPUS
|
|
50
|
+
elif int(flanking_size) == 400:
|
|
51
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11])
|
|
52
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4])
|
|
53
|
+
BATCH_SIZE = 18*N_GPUS
|
|
54
|
+
elif int(flanking_size) == 2000:
|
|
55
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11,
|
|
56
|
+
21, 21, 21, 21])
|
|
57
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4,
|
|
58
|
+
10, 10, 10, 10])
|
|
59
|
+
BATCH_SIZE = 12*N_GPUS
|
|
60
|
+
elif int(flanking_size) == 10000:
|
|
61
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11,
|
|
62
|
+
21, 21, 21, 21, 41, 41, 41, 41])
|
|
63
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4,
|
|
64
|
+
10, 10, 10, 10, 25, 25, 25, 25])
|
|
65
|
+
BATCH_SIZE = 6*N_GPUS
|
|
66
|
+
|
|
67
|
+
CL = 2 * np.sum(AR*(W-1))
|
|
68
|
+
|
|
69
|
+
print(f"\t[INFO] Context nucleotides {CL}")
|
|
70
|
+
print(f"\t[INFO] Sequence length (output): {SL}")
|
|
71
|
+
|
|
72
|
+
model = SpliceAI(L, W, AR).to(device)
|
|
73
|
+
params = {'L': L, 'W': W, 'AR': AR, 'CL': CL, 'SL': SL, 'BATCH_SIZE': BATCH_SIZE, 'N_GPUS': N_GPUS}
|
|
74
|
+
|
|
75
|
+
return model, params
|
|
76
|
+
|
|
77
|
+
# Setup device
|
|
78
|
+
device = setup_device()
|
|
79
|
+
|
|
80
|
+
# Load all model state dicts given the supplied model path
|
|
81
|
+
if os.path.isdir(model_path):
|
|
82
|
+
model_files = glob.glob(os.path.join(model_path, '*.p[th]')) # gets all PyTorch models from supplied directory
|
|
83
|
+
if not model_files:
|
|
84
|
+
logging.error(f"No PyTorch model files found in directory: {model_path}")
|
|
85
|
+
exit()
|
|
86
|
+
|
|
87
|
+
models = []
|
|
88
|
+
for model_file in model_files:
|
|
89
|
+
try:
|
|
90
|
+
model = torch.load(model_file, map_location=device)
|
|
91
|
+
models.append(model)
|
|
92
|
+
except Exception as e:
|
|
93
|
+
logging.error(f"Error loading PyTorch model from file {model_file}: {e}. Skipping...")
|
|
94
|
+
|
|
95
|
+
if not models:
|
|
96
|
+
logging.error(f"No valid PyTorch models found in directory: {model_path}")
|
|
97
|
+
exit()
|
|
98
|
+
|
|
99
|
+
elif os.path.isfile(model_path):
|
|
100
|
+
try:
|
|
101
|
+
models = [torch.load(model_path, map_location=device)]
|
|
102
|
+
except Exception as e:
|
|
103
|
+
logging.error(f"Error loading PyTorch model from file {model_path}: {e}.")
|
|
104
|
+
exit()
|
|
105
|
+
|
|
106
|
+
else:
|
|
107
|
+
logging.error(f"Invalid path: {model_path}")
|
|
108
|
+
exit()
|
|
109
|
+
|
|
110
|
+
# Load state of model to device
|
|
111
|
+
# NOTE: supplied model paths should be state dicts, not model files
|
|
112
|
+
loaded_models = []
|
|
113
|
+
|
|
114
|
+
for state_dict in models:
|
|
115
|
+
try:
|
|
116
|
+
model, params = load_model(device, CL) # loads new SpliceAI model with correct hyperparams
|
|
117
|
+
model.load_state_dict(state_dict) # loads state dict
|
|
118
|
+
model = model.to(device) # puts model on device
|
|
119
|
+
model.eval() # puts model in evaluation mode
|
|
120
|
+
loaded_models.append(model) # appends model to list of loaded models
|
|
121
|
+
except Exception as e:
|
|
122
|
+
logging.error(f"Error processing model for device: {e}. Skipping...")
|
|
123
|
+
|
|
124
|
+
if not loaded_models:
|
|
125
|
+
logging.error("No models were successfully loaded to the device.")
|
|
126
|
+
exit()
|
|
127
|
+
|
|
128
|
+
return loaded_models
|
|
129
|
+
|
|
130
|
+
def load_keras_models(model_path):
|
|
131
|
+
"""
|
|
132
|
+
Loads Keras models from given path.
|
|
133
|
+
|
|
134
|
+
Params:
|
|
135
|
+
- model_path (str): Path to the model file or directory of models.
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
- models (list): List of loaded Keras models.
|
|
139
|
+
"""
|
|
140
|
+
from tensorflow import keras
|
|
141
|
+
|
|
142
|
+
if os.path.isdir(model_path): # directory supplied
|
|
143
|
+
model_files = glob.glob(os.path.join(model_path, '*.h5')) # get all Keras models from a directory
|
|
144
|
+
if not model_files:
|
|
145
|
+
logging.error(f"No Keras model files found in directory: {model_path}")
|
|
146
|
+
exit()
|
|
147
|
+
|
|
148
|
+
models = []
|
|
149
|
+
for model_file in model_files:
|
|
150
|
+
try:
|
|
151
|
+
model = keras.models.load_model(model_file)
|
|
152
|
+
models.append(model)
|
|
153
|
+
except Exception as e:
|
|
154
|
+
logging.error(f"Error loading Keras model from file {model_file}: {e}. Skipping...")
|
|
155
|
+
|
|
156
|
+
if not models:
|
|
157
|
+
logging.error(f"No valid PyTorch models found in directory: {model_path}")
|
|
158
|
+
exit()
|
|
159
|
+
|
|
160
|
+
return models
|
|
161
|
+
|
|
162
|
+
elif os.path.isfile(model_path): # file supplied
|
|
163
|
+
try:
|
|
164
|
+
return [keras.models.load_model(model_path)]
|
|
165
|
+
except Exception as e:
|
|
166
|
+
logging.error(f"Error loading Keras model from file {model_path}: {e}")
|
|
167
|
+
exit()
|
|
168
|
+
|
|
169
|
+
else: # invalid path
|
|
170
|
+
logging.error(f"Invalid path: {model_path}")
|
|
171
|
+
exit()
|
|
172
|
+
|
|
173
|
+
##############################################
|
|
174
|
+
## FORMATTING INPUT DATA FOR PREDICTION
|
|
175
|
+
##############################################
|
|
176
|
+
|
|
177
|
+
def one_hot_encode(seq):
|
|
178
|
+
"""
|
|
179
|
+
One-hot encode a DNA sequence.
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
seq (str): DNA sequence to be encoded.
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
np.ndarray: One-hot encoded representation of the sequence.
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
# Define a mapping matrix for nucleotide to one-hot encoding
|
|
189
|
+
map = np.asarray([[0, 0, 0, 0], # N or any invalid character
|
|
190
|
+
[1, 0, 0, 0], # A
|
|
191
|
+
[0, 1, 0, 0], # C
|
|
192
|
+
[0, 0, 1, 0], # G
|
|
193
|
+
[0, 0, 0, 1]]) # T
|
|
194
|
+
|
|
195
|
+
# Replace nucleotides with corresponding indices
|
|
196
|
+
seq = seq.upper().replace('A', '\x01').replace('C', '\x02')
|
|
197
|
+
seq = seq.replace('G', '\x03').replace('T', '\x04').replace('N', '\x00')
|
|
198
|
+
|
|
199
|
+
# Convert the sequence to one-hot encoded numpy array
|
|
200
|
+
return map[np.fromstring(seq, np.int8) % 5]
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
####################################################################################################################################
|
|
204
|
+
####### #######
|
|
205
|
+
####### ANNOTATOR CLASS #######
|
|
206
|
+
####### #######
|
|
207
|
+
####################################################################################################################################
|
|
208
|
+
|
|
209
|
+
class Annotator:
|
|
210
|
+
"""
|
|
211
|
+
Annotator class to handle gene annotations and reference sequences.
|
|
212
|
+
It initializes with the reference genome, annotation data, and optional model configuration.
|
|
213
|
+
"""
|
|
214
|
+
|
|
215
|
+
def __init__(self, ref_fasta, annotations, model_path='SpliceAI', model_type='keras', CL=80):
|
|
216
|
+
"""
|
|
217
|
+
Initializes the Annotator with reference genome, annotations, and model settings.
|
|
218
|
+
|
|
219
|
+
Args:
|
|
220
|
+
ref_fasta (str): Path to the reference genome FASTA file.
|
|
221
|
+
annotations (str): Path or name of the annotation file (e.g., 'grch37', 'grch38').
|
|
222
|
+
model_path (str, optional): Path to the model file or type of model ('SpliceAI'). Defaults to SpliceAI.
|
|
223
|
+
model_type (str, optional): Type of model ('keras' or 'pytorch'). Defaults to 'keras'.
|
|
224
|
+
CL (int, optional): Context length parameter for model conversion. Defaults to 80.
|
|
225
|
+
"""
|
|
226
|
+
|
|
227
|
+
# Load annotation file based on provided annotations type
|
|
228
|
+
if annotations == 'grch37':
|
|
229
|
+
annotations = './data/vcf/grch37.txt'
|
|
230
|
+
elif annotations == 'grch38':
|
|
231
|
+
annotations = './data/vcf/grch38.txt'
|
|
232
|
+
|
|
233
|
+
# Load and parse the annotation file
|
|
234
|
+
try:
|
|
235
|
+
df = pd.read_csv(annotations, sep='\t', dtype={'CHROM': object})
|
|
236
|
+
# Extract relevant columns into numpy arrays for efficient access
|
|
237
|
+
self.genes = df['#NAME'].to_numpy()
|
|
238
|
+
self.chroms = df['CHROM'].to_numpy()
|
|
239
|
+
self.strands = df['STRAND'].to_numpy()
|
|
240
|
+
self.tx_starts = df['TX_START'].to_numpy() + 1 # Transcription start sites (1-based indexing)
|
|
241
|
+
self.tx_ends = df['TX_END'].to_numpy() # Transcription end sites
|
|
242
|
+
|
|
243
|
+
# Extract and process exon start and end sites, convert into numpy array format
|
|
244
|
+
self.exon_starts = [np.asarray([int(i) for i in c.split(',') if i]) + 1
|
|
245
|
+
for c in df['EXON_START'].to_numpy()]
|
|
246
|
+
self.exon_ends = [np.asarray([int(i) for i in c.split(',') if i])
|
|
247
|
+
for c in df['EXON_END'].to_numpy()]
|
|
248
|
+
except IOError as e:
|
|
249
|
+
logging.error('{}'.format(e))
|
|
250
|
+
exit() # Exit if the file cannot be read
|
|
251
|
+
except (KeyError, pd.errors.ParserError) as e:
|
|
252
|
+
logging.error('Gene annotation file {} not formatted properly: {}'.format(annotations, e))
|
|
253
|
+
exit() # Exit if the file format is incorrect
|
|
254
|
+
|
|
255
|
+
# Load the reference genome fasta file
|
|
256
|
+
try:
|
|
257
|
+
self.ref_fasta = Fasta(ref_fasta, sequence_always_upper=True, rebuild=False)
|
|
258
|
+
except IOError as e:
|
|
259
|
+
logging.error('{}'.format(e)) # Log file read error
|
|
260
|
+
exit() # Exit if the file cannot be read
|
|
261
|
+
|
|
262
|
+
# Load models based on the specified model type or file
|
|
263
|
+
if model_path == 'SpliceAI':
|
|
264
|
+
from tensorflow import keras
|
|
265
|
+
paths = ('./models/spliceai/spliceai{}.h5'.format(x) for x in range(1, 6)) # Generate paths for SpliceAI models
|
|
266
|
+
self.models = [keras.models.load_model(x) for x in paths]
|
|
267
|
+
self.keras = True
|
|
268
|
+
elif model_type == 'keras': # load models using keras
|
|
269
|
+
self.models = load_keras_models(model_path)
|
|
270
|
+
self.keras = True
|
|
271
|
+
elif model_type == 'pytorch': # load models using pytorch
|
|
272
|
+
self.models = load_pytorch_models(model_path, CL)
|
|
273
|
+
self.keras = False
|
|
274
|
+
else:
|
|
275
|
+
logging.error('Model type {} not supported'.format(model_type))
|
|
276
|
+
exit()
|
|
277
|
+
|
|
278
|
+
print(f'\t[INFO] {len(self.models)} model(s) loaded successfully')
|
|
279
|
+
|
|
280
|
+
def get_name_and_strand(self, chrom, pos):
|
|
281
|
+
"""
|
|
282
|
+
Retrieve gene names and strands overlapping a given chromosome position.
|
|
283
|
+
|
|
284
|
+
Args:
|
|
285
|
+
chrom (str): Chromosome identifier.
|
|
286
|
+
pos (int): Position on the chromosome.
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
tuple: Lists of gene names, strands, and their indices overlapping the given position.
|
|
290
|
+
"""
|
|
291
|
+
|
|
292
|
+
# Normalize chromosome identifier to match the annotation format
|
|
293
|
+
chrom = normalise_chrom(chrom, list(self.chroms)[0])
|
|
294
|
+
# Find indices of annotations overlapping the given chromosome and position
|
|
295
|
+
idxs = np.intersect1d(np.nonzero(self.chroms == chrom)[0],
|
|
296
|
+
np.intersect1d(np.nonzero(self.tx_starts <= pos)[0],
|
|
297
|
+
np.nonzero(pos <= self.tx_ends)[0]))
|
|
298
|
+
|
|
299
|
+
if len(idxs) >= 1:
|
|
300
|
+
return self.genes[idxs], self.strands[idxs], idxs # Return matching gene names and strands
|
|
301
|
+
else:
|
|
302
|
+
return [], [], [] # Return empty lists if no matches are found
|
|
303
|
+
|
|
304
|
+
def get_pos_data(self, idx, pos):
|
|
305
|
+
"""
|
|
306
|
+
Calculate distances from a given position to the transcription start site,
|
|
307
|
+
transcription end site, and nearest exon boundary for a specific gene.
|
|
308
|
+
|
|
309
|
+
Args:
|
|
310
|
+
idx (int): Index of the gene in the annotations.
|
|
311
|
+
pos (int): Position on the chromosome.
|
|
312
|
+
|
|
313
|
+
Returns:
|
|
314
|
+
tuple: Distances to transcription start, transcription end, and nearest exon boundary.
|
|
315
|
+
"""
|
|
316
|
+
|
|
317
|
+
# Calculate distances to transcription start and end sites
|
|
318
|
+
dist_tx_start = self.tx_starts[idx] - pos
|
|
319
|
+
dist_tx_end = self.tx_ends[idx] - pos
|
|
320
|
+
# Calculate the closest distance to an exon boundary
|
|
321
|
+
dist_exon_bdry = min(np.union1d(self.exon_starts[idx], self.exon_ends[idx]) - pos, key=abs)
|
|
322
|
+
dist_ann = (dist_tx_start, dist_tx_end, dist_exon_bdry) # Package distances into a tuple
|
|
323
|
+
|
|
324
|
+
return dist_ann
|
|
325
|
+
|
|
326
|
+
##############################################
|
|
327
|
+
## CALCULATING DELTA SCORES
|
|
328
|
+
##############################################
|
|
329
|
+
|
|
330
|
+
def normalise_chrom(source, target):
|
|
331
|
+
"""
|
|
332
|
+
Normalize chromosome identifiers to ensure consistency in format (with or without 'chr' prefix).
|
|
333
|
+
|
|
334
|
+
Args:
|
|
335
|
+
source (str): Source chromosome identifier.
|
|
336
|
+
target (str): Target chromosome identifier for comparison.
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
str: Normalized chromosome identifier.
|
|
340
|
+
"""
|
|
341
|
+
|
|
342
|
+
def has_prefix(x):
|
|
343
|
+
return x.startswith('chr') # Check if a chromosome name has 'chr' prefix
|
|
344
|
+
|
|
345
|
+
if has_prefix(source) and not has_prefix(target):
|
|
346
|
+
return source.strip('chr') # Remove 'chr' prefix if target doesn't have it
|
|
347
|
+
elif not has_prefix(source) and has_prefix(target):
|
|
348
|
+
return 'chr' + source # Add 'chr' prefix if target has it
|
|
349
|
+
|
|
350
|
+
return source # Return source as is if both or neither have 'chr' prefix
|
|
351
|
+
|
|
352
|
+
def get_delta_scores(record, ann, dist_var, mask, flanking_size=5000, precision=2):
|
|
353
|
+
"""
|
|
354
|
+
Calculate delta scores for variant impacts on splice sites.
|
|
355
|
+
|
|
356
|
+
Args:
|
|
357
|
+
record (pysam Record): Record containing variant information (e.g., chrom, pos, ref, alts).
|
|
358
|
+
ann (Annotator): Annotator instance with annotation and reference genome data.
|
|
359
|
+
dist_var (int): Max distance between variant and gained/lost splice site, defaults to 50.
|
|
360
|
+
mask (bool): Mask scores representing annotated acceptor/donor gain and unannotated acceptor/donor loss, defaults to 0.
|
|
361
|
+
flanking_size (int, optional): Size of the flanking region around the variant, defaults to 5000.
|
|
362
|
+
|
|
363
|
+
Returns:
|
|
364
|
+
list: Delta scores indicating the impact of variants on splicing.
|
|
365
|
+
"""
|
|
366
|
+
|
|
367
|
+
# Define coverage and window size around the variant
|
|
368
|
+
cov = 2 * dist_var + 1
|
|
369
|
+
wid = 2 * flanking_size + cov
|
|
370
|
+
delta_scores = []
|
|
371
|
+
device = setup_device()
|
|
372
|
+
|
|
373
|
+
# Validate the record fields
|
|
374
|
+
try:
|
|
375
|
+
record.chrom, record.pos, record.ref, len(record.alts)
|
|
376
|
+
except TypeError:
|
|
377
|
+
logging.warning('Skipping record (bad input): {}'.format(record))
|
|
378
|
+
return delta_scores
|
|
379
|
+
|
|
380
|
+
# Get gene names and strands overlapping the variant position
|
|
381
|
+
(genes, strands, idxs) = ann.get_name_and_strand(record.chrom, record.pos)
|
|
382
|
+
if len(idxs) == 0:
|
|
383
|
+
return delta_scores # Return empty list if no overlapping genes are found
|
|
384
|
+
|
|
385
|
+
# Normalize chromosome and retrieve reference sequence around the variant
|
|
386
|
+
chrom = normalise_chrom(record.chrom, list(ann.ref_fasta.keys())[0])
|
|
387
|
+
try:
|
|
388
|
+
seq = ann.ref_fasta[chrom][record.pos - wid // 2 - 1 : record.pos + wid // 2].seq
|
|
389
|
+
except (IndexError, ValueError):
|
|
390
|
+
logging.warning('Skipping record (fasta issue): {}'.format(record))
|
|
391
|
+
return delta_scores
|
|
392
|
+
|
|
393
|
+
# Check if the reference sequence matches the expected reference allele
|
|
394
|
+
if seq[wid // 2 : wid // 2 + len(record.ref)].upper() != record.ref:
|
|
395
|
+
logging.warning('Skipping record (ref issue): {}'.format(record))
|
|
396
|
+
return delta_scores
|
|
397
|
+
|
|
398
|
+
# Check if the sequence length matches the expected window size
|
|
399
|
+
if len(seq) != wid:
|
|
400
|
+
logging.warning('Skipping record (near chromosome end): {}'.format(record))
|
|
401
|
+
return delta_scores
|
|
402
|
+
|
|
403
|
+
# Skip records with a reference allele longer than the distance variable
|
|
404
|
+
if len(record.ref) > 2 * dist_var:
|
|
405
|
+
logging.warning('Skipping record (ref too long): {}'.format(record))
|
|
406
|
+
return delta_scores
|
|
407
|
+
|
|
408
|
+
# Iterate over each alternative allele and each gene index to calculate delta score
|
|
409
|
+
for j in range(len(record.alts)):
|
|
410
|
+
for i in range(len(idxs)):
|
|
411
|
+
|
|
412
|
+
# Skip specific alternative allele types
|
|
413
|
+
if '.' in record.alts[j] or '-' in record.alts[j] or '*' in record.alts[j]:
|
|
414
|
+
continue
|
|
415
|
+
if '<' in record.alts[j] or '>' in record.alts[j]:
|
|
416
|
+
continue
|
|
417
|
+
|
|
418
|
+
# Handle multi-nucleotide variants
|
|
419
|
+
if len(record.ref) > 1 and len(record.alts[j]) > 1:
|
|
420
|
+
delta_scores.append("{}|{}|.|.|.|.|.|.|.|.".format(record.alts[j], genes[i]))
|
|
421
|
+
continue
|
|
422
|
+
|
|
423
|
+
# Calculate position-related distances
|
|
424
|
+
dist_ann = ann.get_pos_data(idxs[i], record.pos)
|
|
425
|
+
pad_size = [max(wid // 2 + dist_ann[0], 0), max(wid // 2 - dist_ann[1], 0)]
|
|
426
|
+
ref_len = len(record.ref)
|
|
427
|
+
alt_len = len(record.alts[j])
|
|
428
|
+
del_len = max(ref_len - alt_len, 0)
|
|
429
|
+
|
|
430
|
+
# Construct reference and alternative sequences with padding
|
|
431
|
+
x_ref = 'N' * pad_size[0] + seq[pad_size[0]: wid - pad_size[1]] + 'N' * pad_size[1]
|
|
432
|
+
x_alt = x_ref[: wid // 2] + str(record.alts[j]) + x_ref[wid // 2 + ref_len:]
|
|
433
|
+
|
|
434
|
+
# One-hot encode the sequences
|
|
435
|
+
x_ref = one_hot_encode(x_ref)[None, :]
|
|
436
|
+
x_alt = one_hot_encode(x_alt)[None, :]
|
|
437
|
+
|
|
438
|
+
'''separate handling of PyTorch and Keras models'''
|
|
439
|
+
|
|
440
|
+
if ann.keras: # keras model handling
|
|
441
|
+
# Reverse the sequences if on the negative strand
|
|
442
|
+
if strands[i] == '-':
|
|
443
|
+
x_ref = x_ref[:, ::-1, ::-1]
|
|
444
|
+
x_alt = x_alt[:, ::-1, ::-1]
|
|
445
|
+
|
|
446
|
+
# Predict scores using the models
|
|
447
|
+
y_ref = np.mean([ann.models[m].predict(x_ref) for m in range(len(ann.models))], axis=0)
|
|
448
|
+
y_alt = np.mean([ann.models[m].predict(x_alt) for m in range(len(ann.models))], axis=0)
|
|
449
|
+
|
|
450
|
+
# Reverse the predicted scores if on the negative strand
|
|
451
|
+
if strands[i] == '-':
|
|
452
|
+
y_ref = y_ref[:, ::-1]
|
|
453
|
+
y_alt = y_alt[:, ::-1]
|
|
454
|
+
|
|
455
|
+
else: # pytorch model handling
|
|
456
|
+
|
|
457
|
+
# Reshape tensor to match the model input shape
|
|
458
|
+
x_ref = x_ref.transpose(0, 2, 1)
|
|
459
|
+
x_alt = x_alt.transpose(0, 2, 1)
|
|
460
|
+
|
|
461
|
+
# Convert to PyTorch tensors
|
|
462
|
+
x_ref = torch.tensor(x_ref, dtype=torch.float32)
|
|
463
|
+
x_alt = torch.tensor(x_alt, dtype=torch.float32)
|
|
464
|
+
|
|
465
|
+
# Reverse the sequences if on the negative strand
|
|
466
|
+
if strands[i] == '-':
|
|
467
|
+
x_ref = torch.flip(x_ref, dims=[1, 2])
|
|
468
|
+
x_alt = torch.flip(x_alt, dims=[1, 2])
|
|
469
|
+
|
|
470
|
+
# Put tensors on device
|
|
471
|
+
x_ref = x_ref.to(device)
|
|
472
|
+
x_alt = x_alt.to(device)
|
|
473
|
+
|
|
474
|
+
# Predict scores using the models
|
|
475
|
+
with torch.no_grad():
|
|
476
|
+
y_ref = torch.mean(torch.stack([ann.models[m](x_ref).detach().cpu() for m in range(len(ann.models))]), axis=0)
|
|
477
|
+
y_alt = torch.mean(torch.stack([ann.models[m](x_alt).detach().cpu() for m in range(len(ann.models))]), axis=0)
|
|
478
|
+
|
|
479
|
+
# Remove flanking sequence and permute shape
|
|
480
|
+
y_ref = y_ref.permute(0, 2, 1)
|
|
481
|
+
y_alt = y_alt.permute(0, 2, 1)
|
|
482
|
+
|
|
483
|
+
# Reverse the predicted scores if on the negative strand and convert back to numpy arrays
|
|
484
|
+
if strands[i] == '-':
|
|
485
|
+
y_ref = torch.flip(y_ref, dims=[1])
|
|
486
|
+
y_alt = torch.flip(y_alt, dims=[1])
|
|
487
|
+
|
|
488
|
+
# Convert to numpy arrays
|
|
489
|
+
y_ref = y_ref.numpy()
|
|
490
|
+
y_alt = y_alt.numpy()
|
|
491
|
+
|
|
492
|
+
'''end'''
|
|
493
|
+
|
|
494
|
+
# Adjust the alternative sequence scores based on reference and alternative lengths
|
|
495
|
+
if ref_len > 1 and alt_len == 1:
|
|
496
|
+
y_alt = np.concatenate([
|
|
497
|
+
y_alt[:, : cov // 2 + alt_len],
|
|
498
|
+
np.zeros((1, del_len, 3)),
|
|
499
|
+
y_alt[:, cov // 2 + alt_len:]
|
|
500
|
+
], axis=1)
|
|
501
|
+
elif ref_len == 1 and alt_len > 1:
|
|
502
|
+
y_alt = np.concatenate([
|
|
503
|
+
y_alt[:, : cov // 2],
|
|
504
|
+
np.max(y_alt[:, cov // 2 : cov // 2 + alt_len], axis=1)[:, None, :],
|
|
505
|
+
y_alt[:, cov // 2 + alt_len:]
|
|
506
|
+
], axis=1)
|
|
507
|
+
|
|
508
|
+
# Concatenate the reference and alternative scores
|
|
509
|
+
y = np.concatenate([y_ref, y_alt])
|
|
510
|
+
|
|
511
|
+
# Find the indices of maximum delta scores for splicing acceptor and donor sites
|
|
512
|
+
idx_pa = (y[1, :, 1] - y[0, :, 1]).argmax()
|
|
513
|
+
idx_na = (y[0, :, 1] - y[1, :, 1]).argmax()
|
|
514
|
+
idx_pd = (y[1, :, 2] - y[0, :, 2]).argmax()
|
|
515
|
+
idx_nd = (y[0, :, 2] - y[1, :, 2]).argmax()
|
|
516
|
+
|
|
517
|
+
# Apply masks to delta scores based on calculated indices and provided mask
|
|
518
|
+
mask_pa = np.logical_and((idx_pa - cov // 2 == dist_ann[2]), mask)
|
|
519
|
+
mask_na = np.logical_and((idx_na - cov // 2 != dist_ann[2]), mask)
|
|
520
|
+
mask_pd = np.logical_and((idx_pd - cov // 2 == dist_ann[2]), mask)
|
|
521
|
+
mask_nd = np.logical_and((idx_nd - cov // 2 != dist_ann[2]), mask)
|
|
522
|
+
|
|
523
|
+
# Create a format string with the desired precision
|
|
524
|
+
format_str = "{{}}|{{}}|{{:.{}f}}|{{:.{}f}}|{{:.{}f}}|{{:.{}f}}|{{}}|{{}}|{{}}|{{}}".format(
|
|
525
|
+
precision, precision, precision, precision)
|
|
526
|
+
|
|
527
|
+
# Write delta scores for given alternative allele, gene, and calculated indices
|
|
528
|
+
delta_scores.append(format_str.format(
|
|
529
|
+
record.alts[j],
|
|
530
|
+
genes[i],
|
|
531
|
+
(y[1, idx_pa, 1] - y[0, idx_pa, 1]) * (1 - mask_pa),
|
|
532
|
+
(y[0, idx_na, 1] - y[1, idx_na, 1]) * (1 - mask_na),
|
|
533
|
+
(y[1, idx_pd, 2] - y[0, idx_pd, 2]) * (1 - mask_pd),
|
|
534
|
+
(y[0, idx_nd, 2] - y[1, idx_nd, 2]) * (1 - mask_nd),
|
|
535
|
+
idx_pa - cov // 2,
|
|
536
|
+
idx_na - cov // 2,
|
|
537
|
+
idx_pd - cov // 2,
|
|
538
|
+
idx_nd - cov // 2
|
|
539
|
+
))
|
|
540
|
+
|
|
541
|
+
return delta_scores
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
'''
|
|
2
|
+
variant.py
|
|
3
|
+
This command annotates variants in a VCF file using SpliceAI-toolkit. It reads the input VCF file, annotates
|
|
4
|
+
each variant with delta scores and delta positions, and writes the annotated variants to an output VCF file.
|
|
5
|
+
It uses the Annotator class to annotate variants based on the reference genome and annotation provided. The
|
|
6
|
+
annotated variants are written to the output VCF file with the 'SpliceAI' INFO field containing the delta
|
|
7
|
+
scores and delta positions for acceptor gain (AG), acceptor loss (AL), donor gain (DG), and donor loss (DL).
|
|
8
|
+
'''
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import pysam
|
|
12
|
+
import numpy as np
|
|
13
|
+
from openspliceai.variant.utils import *
|
|
14
|
+
from tqdm import tqdm
|
|
15
|
+
import os
|
|
16
|
+
|
|
17
|
+
# NOTE: if running with gpu, note that cudnn version should be 8.9.6 or higher, numpy <2.0.0
|
|
18
|
+
|
|
19
|
+
def variant(args):
|
|
20
|
+
print("Running SpliceAI-toolkit with 'variant' mode")
|
|
21
|
+
start_time = time.time()
|
|
22
|
+
|
|
23
|
+
# Set up logging
|
|
24
|
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
25
|
+
|
|
26
|
+
# Error handling for required arguments
|
|
27
|
+
if None in [args.I, args.O, args.R, args.A, args.model, args.flanking_size]:
|
|
28
|
+
logging.error('Usage: spliceai [-h] [-m [model]] [-f [flanking_size]] [-I [input]] [-O [output]] -R reference -A annotation '
|
|
29
|
+
'[-D [distance]] [-M [mask]]')
|
|
30
|
+
exit(1)
|
|
31
|
+
|
|
32
|
+
# Define arguments
|
|
33
|
+
ref_genome = args.R
|
|
34
|
+
annotation = args.A
|
|
35
|
+
input_vcf = args.I
|
|
36
|
+
output_vcf = args.O
|
|
37
|
+
distance = args.D
|
|
38
|
+
mask = args.M
|
|
39
|
+
model = args.model
|
|
40
|
+
flanking_size = args.flanking_size
|
|
41
|
+
model_type = args.model_type
|
|
42
|
+
precision = args.precision
|
|
43
|
+
|
|
44
|
+
print(f'''Running with genome: {ref_genome}, annotation: {annotation},
|
|
45
|
+
model(s): {model}, model_type: {model_type},
|
|
46
|
+
input: {input_vcf}, output: {output_vcf},
|
|
47
|
+
distance: {distance}, mask: {mask}, flanking_size: {flanking_size}, precision: {precision}''')
|
|
48
|
+
|
|
49
|
+
# Reading input VCF file
|
|
50
|
+
print('\t[INFO] Reading input VCF file')
|
|
51
|
+
try:
|
|
52
|
+
vcf = pysam.VariantFile(input_vcf)
|
|
53
|
+
except (IOError, ValueError) as e:
|
|
54
|
+
logging.error('Error reading input file: {}'.format(e))
|
|
55
|
+
exit(1)
|
|
56
|
+
|
|
57
|
+
# Adding annotation to the header
|
|
58
|
+
header = vcf.header
|
|
59
|
+
header.add_line('##INFO=<ID=SpliceAI,Number=.,Type=String,Description="OpenSpliceAI variant '
|
|
60
|
+
'annotation. These include delta scores (DS) and delta positions (DP) for '
|
|
61
|
+
'acceptor gain (AG), acceptor loss (AL), donor gain (DG), and donor loss (DL). '
|
|
62
|
+
'Format: ALLELE|SYMBOL|DS_AG|DS_AL|DS_DG|DS_DL|DP_AG|DP_AL|DP_DG|DP_DL">')
|
|
63
|
+
|
|
64
|
+
# Generating output VCF file
|
|
65
|
+
print('\t[INFO] Generating output VCF file')
|
|
66
|
+
os.makedirs(os.path.dirname(output_vcf), exist_ok=True)
|
|
67
|
+
try:
|
|
68
|
+
output = pysam.VariantFile(output_vcf, mode='w', header=header)
|
|
69
|
+
except (IOError, ValueError) as e:
|
|
70
|
+
logging.error('Error generating output VCF file: {}'.format(e))
|
|
71
|
+
exit(1)
|
|
72
|
+
|
|
73
|
+
# Setup the Annotator based on reference genome and annotation
|
|
74
|
+
logging.info('Initializing Annotator class')
|
|
75
|
+
ann = Annotator(ref_genome, annotation, model, model_type, flanking_size)
|
|
76
|
+
|
|
77
|
+
# Obtain delta score for each variant in VCF
|
|
78
|
+
for record in tqdm(vcf):
|
|
79
|
+
scores = get_delta_scores(record, ann, distance, mask, flanking_size, precision)
|
|
80
|
+
if scores:
|
|
81
|
+
record.info['SpliceAI'] = scores
|
|
82
|
+
output.write(record)
|
|
83
|
+
|
|
84
|
+
# Close input and output VCF files
|
|
85
|
+
vcf.close()
|
|
86
|
+
output.close()
|
|
87
|
+
logging.info('Annotation completed and written to output VCF file')
|
|
88
|
+
|
|
89
|
+
print("--- %s seconds ---" % (time.time() - start_time))
|