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,1091 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import os, sys
|
|
3
|
+
import re
|
|
4
|
+
import numpy as np
|
|
5
|
+
import torch
|
|
6
|
+
from torch.utils.data import TensorDataset, DataLoader
|
|
7
|
+
from tqdm import tqdm
|
|
8
|
+
import platform
|
|
9
|
+
import h5py
|
|
10
|
+
import time
|
|
11
|
+
from pyfaidx import Fasta
|
|
12
|
+
from openspliceai.train_base.spliceai import SpliceAI
|
|
13
|
+
import openspliceai.predict.utils as utils
|
|
14
|
+
|
|
15
|
+
################
|
|
16
|
+
## STEP 1 ##
|
|
17
|
+
################
|
|
18
|
+
|
|
19
|
+
def process_gff(fasta_file, gff_file, output_dir):
|
|
20
|
+
"""
|
|
21
|
+
Processes a GFF file to extract gene regions and creates a new FASTA file
|
|
22
|
+
with the extracted gene sequences.
|
|
23
|
+
|
|
24
|
+
Parameters:
|
|
25
|
+
- gff_file: Path to the GFF file.
|
|
26
|
+
- fasta_file: Path to the input FASTA file.
|
|
27
|
+
- output_fasta_file: Path to the output FASTA file.
|
|
28
|
+
"""
|
|
29
|
+
# define output FASTA file
|
|
30
|
+
output_fasta_file = f'{output_dir}{os.path.splitext(os.path.basename(fasta_file))[0]}_genes.fa'
|
|
31
|
+
|
|
32
|
+
# read the input FASTA file
|
|
33
|
+
fasta = Fasta(fasta_file)
|
|
34
|
+
|
|
35
|
+
# open the output FASTA file for writing
|
|
36
|
+
count = 0
|
|
37
|
+
with open(output_fasta_file, 'w') as output_fasta:
|
|
38
|
+
# read the GFF file
|
|
39
|
+
with open(gff_file, 'r') as gff:
|
|
40
|
+
for line in gff:
|
|
41
|
+
if line.startswith('#'):
|
|
42
|
+
continue
|
|
43
|
+
|
|
44
|
+
# split the GFF line into fields
|
|
45
|
+
fields = line.strip().split('\t')
|
|
46
|
+
if len(fields) < 9:
|
|
47
|
+
print(f'\t[ERR] line does not have enough fields:\n{line}')
|
|
48
|
+
continue # lines with not enough fields are erroneous?
|
|
49
|
+
|
|
50
|
+
# extract relevant information from the GFF fields
|
|
51
|
+
seqid = fields[0]
|
|
52
|
+
feature_type = fields[2]
|
|
53
|
+
start = int(fields[3])
|
|
54
|
+
end = int(fields[4])
|
|
55
|
+
strand = fields[6]
|
|
56
|
+
attributes = fields[8]
|
|
57
|
+
|
|
58
|
+
# process only gene features
|
|
59
|
+
if feature_type != 'gene':
|
|
60
|
+
continue
|
|
61
|
+
|
|
62
|
+
# extract gene ID, or if not then Name, from the attributes
|
|
63
|
+
gene_id = 'unknown_gene'
|
|
64
|
+
for attribute in attributes.split(';'):
|
|
65
|
+
if attribute.startswith('ID=') or attribute.startswith('Name='):
|
|
66
|
+
gene_id = attribute.split('=')[1]
|
|
67
|
+
break
|
|
68
|
+
|
|
69
|
+
# extract the gene sequence from the FASTA file
|
|
70
|
+
sequence = fasta[seqid][start-1:end] # adjust for 0-based indexing
|
|
71
|
+
|
|
72
|
+
# reverse complement the sequence if on the negative strand
|
|
73
|
+
if strand == '-':
|
|
74
|
+
sequence = sequence.reverse.complement
|
|
75
|
+
|
|
76
|
+
# write the gene sequence to the output FASTA file
|
|
77
|
+
output_fasta.write(f'>{gene_id} {seqid}:{start}-{end}({strand})\n')
|
|
78
|
+
output_fasta.write(str(sequence) + '\n')
|
|
79
|
+
count += 1
|
|
80
|
+
|
|
81
|
+
print(f"\t[INFO] {count} gene sequences have been extracted to {output_fasta_file}")
|
|
82
|
+
|
|
83
|
+
return output_fasta_file
|
|
84
|
+
|
|
85
|
+
def split_fasta(genes, split_fasta_file, CL_max, split_fasta_threshold):
|
|
86
|
+
'''
|
|
87
|
+
Splits any long genes in the given Fasta object into segments of SPLIT_FASTA_THRESHOLD length and writes them to a FASTA file.
|
|
88
|
+
|
|
89
|
+
Parameters:
|
|
90
|
+
- genes (Fasta): A pyfaidx dictionary-like object containing gene records.
|
|
91
|
+
- split_fasta_file (str): The path to the output FASTA file.
|
|
92
|
+
'''
|
|
93
|
+
name_pattern = re.compile(r'(.*)(chr[a-zA-Z0-9_]*):(\d+)-(\d+)\(([-+])\)')
|
|
94
|
+
chrom_pattern = re.compile(r'(chr[a-zA-Z0-9_]+)')
|
|
95
|
+
|
|
96
|
+
def create_name(record, start_pos, end_pos):
|
|
97
|
+
'''
|
|
98
|
+
Write a line of the split FASTA file.
|
|
99
|
+
|
|
100
|
+
Params:
|
|
101
|
+
- record: Gene record
|
|
102
|
+
- start_pos: Relative start position of the segment (1-indexed)
|
|
103
|
+
- end_pos: Relative end position of the segment (1-indexed)
|
|
104
|
+
'''
|
|
105
|
+
|
|
106
|
+
# default extended name
|
|
107
|
+
segment_name = record.long_name
|
|
108
|
+
|
|
109
|
+
# search for the pattern in the name
|
|
110
|
+
match = name_pattern.search(segment_name)
|
|
111
|
+
if match:
|
|
112
|
+
prefix = match.group(1)
|
|
113
|
+
chromosome = match.group(2)
|
|
114
|
+
strand = match.group(5)
|
|
115
|
+
abs_start = int(match.group(3))
|
|
116
|
+
|
|
117
|
+
# compute true absolute start and end positions
|
|
118
|
+
start = abs_start - 1 + start_pos
|
|
119
|
+
end = abs_start - 1 + end_pos
|
|
120
|
+
|
|
121
|
+
segment_name = f"{prefix}{chromosome}:{start}-{end}({strand})"
|
|
122
|
+
|
|
123
|
+
else:
|
|
124
|
+
chrom_match = chrom_pattern.search(segment_name)
|
|
125
|
+
if chrom_match:
|
|
126
|
+
seqid = chrom_match.group(1) # use chromosome to denote sequence ID
|
|
127
|
+
else:
|
|
128
|
+
seqid = record.name # use original name to denote sequence ID (NOTE: must be unique for each sequence in the FASTA file)
|
|
129
|
+
|
|
130
|
+
strand = '.' # NOTE: unknown strands will be treated as a forward strand further downstream (supply neg_strands argument to get_sequences() to override)
|
|
131
|
+
|
|
132
|
+
# construct the fixed string with the split denoted
|
|
133
|
+
segment_name = f"{seqid}:{start_pos}-{end_pos}({strand})"
|
|
134
|
+
|
|
135
|
+
return segment_name
|
|
136
|
+
|
|
137
|
+
with open(split_fasta_file, 'w') as output_file:
|
|
138
|
+
for record in genes:
|
|
139
|
+
seq_length = len(genes[record.name])
|
|
140
|
+
if seq_length > split_fasta_threshold:
|
|
141
|
+
# process each segment into a new entry
|
|
142
|
+
for i in range(0, seq_length, split_fasta_threshold):
|
|
143
|
+
|
|
144
|
+
# obtain the split sequence (with flanking to preserve predictions across splits)
|
|
145
|
+
start_slice = i - (CL_max // 2) if i - (CL_max // 2) >= 0 else 0
|
|
146
|
+
end_slice = i + split_fasta_threshold + (CL_max // 2) if i + split_fasta_threshold + (CL_max // 2) <= seq_length else seq_length
|
|
147
|
+
segment_seq = genes[record.name][start_slice:end_slice].seq # added flanking sequences to preserve predictions
|
|
148
|
+
|
|
149
|
+
# formulate the sequence name using pattern matching
|
|
150
|
+
segment_name = create_name(record, start_slice+1, end_slice)
|
|
151
|
+
|
|
152
|
+
output_file.write(f">{segment_name}\n")
|
|
153
|
+
output_file.write(f"{segment_seq}\n")
|
|
154
|
+
|
|
155
|
+
else:
|
|
156
|
+
# write sequence as is (still ensuring name in format)
|
|
157
|
+
segment_seq = genes[record.name][:]
|
|
158
|
+
segment_name = create_name(record, 1, len(segment_seq))
|
|
159
|
+
|
|
160
|
+
output_file.write(f">{segment_name}\n")
|
|
161
|
+
output_file.write(f"{segment_seq}\n")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def get_sequences(fasta_file, output_dir, CL_max, hdf_threshold_len=0, split_fasta_threshold=1500000, neg_strands=None, debug=False):
|
|
165
|
+
"""
|
|
166
|
+
Extract sequences for each protein-coding gene, process them based on strand orientation,
|
|
167
|
+
and save data in file depending on the sequence size (HDF file if sequence >HDF_THRESHOLD_LEN,
|
|
168
|
+
else temp file).
|
|
169
|
+
|
|
170
|
+
Parameters:
|
|
171
|
+
- fasta_file: Path to the FASTA file.
|
|
172
|
+
- output_dir: Directory to save the output files.
|
|
173
|
+
- neg_strands (list): List of IDs for fasta entries where the sequence is on the reverse strand. Default is None.
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
- Path to datafile.
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
# detect sequence length, determine file saving method to use
|
|
180
|
+
total_length = 0
|
|
181
|
+
use_hdf = False
|
|
182
|
+
need_splitting = False
|
|
183
|
+
|
|
184
|
+
# NOTE: always creates uppercase sequence, uses [1,0]-indexed sequence names (does not affect slicing), takes simple name from FASTA
|
|
185
|
+
genes = Fasta(fasta_file, one_based_attributes=True, read_long_names=False, sequence_always_upper=True)
|
|
186
|
+
|
|
187
|
+
for record in genes:
|
|
188
|
+
record_length = len(genes[record.name])
|
|
189
|
+
total_length += record_length
|
|
190
|
+
if not use_hdf and total_length > hdf_threshold_len:
|
|
191
|
+
use_hdf = True
|
|
192
|
+
print(f'\t[INFO] Input FASTA sequences over {hdf_threshold_len}: use_hdf = True.')
|
|
193
|
+
if not need_splitting and record_length > split_fasta_threshold:
|
|
194
|
+
need_splitting = True
|
|
195
|
+
print(f'\t[INFO] Input FASTA contains sequence(s) over {split_fasta_threshold}: need_splitting = True')
|
|
196
|
+
if use_hdf and need_splitting:
|
|
197
|
+
break
|
|
198
|
+
|
|
199
|
+
if need_splitting:
|
|
200
|
+
split_fasta_file = f'{output_dir}{os.path.splitext(os.path.basename(fasta_file))[0]}_split.fa'
|
|
201
|
+
print(f'\t[INFO] Splitting {fasta_file}.')
|
|
202
|
+
|
|
203
|
+
split_fasta(genes, split_fasta_file, CL_max, split_fasta_threshold)
|
|
204
|
+
|
|
205
|
+
# re-loads the pyfaidx Fasta object with split genes
|
|
206
|
+
genes = Fasta(split_fasta_file, one_based_attributes=True, read_long_names=True, sequence_always_upper=True) # need long name to handle duplicate seqids after splits
|
|
207
|
+
print(f"\t[INFO] Saved and loaded {split_fasta_file}.")
|
|
208
|
+
|
|
209
|
+
NAME = [] # Gene Header
|
|
210
|
+
SEQ = [] # Sequences
|
|
211
|
+
|
|
212
|
+
# obtain the headers and sequences from FASTA file
|
|
213
|
+
for record in genes:
|
|
214
|
+
seq_id = record.long_name
|
|
215
|
+
sequence = genes[record.name][:].seq
|
|
216
|
+
|
|
217
|
+
# reverse strand if explicitly specified, name with strand info
|
|
218
|
+
if neg_strands is not None and record.name in neg_strands:
|
|
219
|
+
seq_id = str(seq_id) + ':-'
|
|
220
|
+
sequence = sequence.reverse.complement
|
|
221
|
+
else:
|
|
222
|
+
seq_id = str(seq_id) + ':+'
|
|
223
|
+
|
|
224
|
+
NAME.append(seq_id)
|
|
225
|
+
SEQ.append(str(sequence))
|
|
226
|
+
|
|
227
|
+
# write the sequences to datafile
|
|
228
|
+
if use_hdf:
|
|
229
|
+
datafile_path = f'{output_dir}datafile.h5'
|
|
230
|
+
dt = h5py.string_dtype(encoding='utf-8')
|
|
231
|
+
with h5py.File(datafile_path, 'w') as datafile: # hdf5 information file
|
|
232
|
+
datafile.create_dataset('NAME', data=np.asarray(NAME, dtype=dt), dtype=dt)
|
|
233
|
+
datafile.create_dataset('SEQ', data=np.asarray(SEQ, dtype=dt), dtype=dt)
|
|
234
|
+
else:
|
|
235
|
+
datafile_path = f'{output_dir}datafile.txt'
|
|
236
|
+
with open(datafile_path, 'w') as datafile: # temp sequence file
|
|
237
|
+
for name, seq in zip(NAME, SEQ):
|
|
238
|
+
datafile.write(f'{name}\n{seq}\n')
|
|
239
|
+
|
|
240
|
+
if debug:
|
|
241
|
+
print(f'\t[DEBUG] len(NAME): {len(NAME)}, len(SEQ): {len(SEQ)}', file=sys.stderr)
|
|
242
|
+
|
|
243
|
+
return datafile_path, NAME, SEQ
|
|
244
|
+
|
|
245
|
+
# check_and_count_motifs(gene_seq, labels, gene.strand) # maybe adapt to count motifs that were found in the predicted file...
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
################
|
|
249
|
+
## STEP 2 ##
|
|
250
|
+
################
|
|
251
|
+
|
|
252
|
+
def create_datapoints(input_string, SL, CL_max, debug=False):
|
|
253
|
+
"""
|
|
254
|
+
Parameters:
|
|
255
|
+
- input_string (str): The nucleotide sequence.
|
|
256
|
+
|
|
257
|
+
Returns:
|
|
258
|
+
- X (np.ndarray): The one-hot encoded input nucleotide sequence.
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
def reformat_data(X0):
|
|
262
|
+
"""
|
|
263
|
+
Breaks up an input sequence into overlapping windows of size SL + CL_max.
|
|
264
|
+
|
|
265
|
+
Parameters:
|
|
266
|
+
- X0 (numpy.ndarray): Original sequence data as an array of integer encodings.
|
|
267
|
+
- (global) CL_max: Maximum context length for sequence prediction (flanking size sum).
|
|
268
|
+
- (global) SL: Sequence length for prediction, default = 5000.
|
|
269
|
+
|
|
270
|
+
Returns:
|
|
271
|
+
- numpy.ndarray: Reformatted sequence data.
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
if debug:
|
|
275
|
+
print('\n\t[DEBUG] reformat_data', file=sys.stderr)
|
|
276
|
+
print('\tlen(X0)', len(X0), file=sys.stderr)
|
|
277
|
+
print('\tSL', SL, ' CL_max', CL_max, file=sys.stderr)
|
|
278
|
+
# Calculate the number of data points needed
|
|
279
|
+
num_points = utils.ceil_div(len(X0) - CL_max, SL) # NOTE: subtracting the flanking here because X0 is already padded at the ends by create_datapoints and only want window on actual sequence length
|
|
280
|
+
if debug:
|
|
281
|
+
print('\tnum_points', num_points, file=sys.stderr)
|
|
282
|
+
# Initialize arrays to hold the reformatted data
|
|
283
|
+
Xd = np.zeros((num_points, SL + CL_max))
|
|
284
|
+
if debug:
|
|
285
|
+
print('\tXd.shape', Xd.shape, file=sys.stderr)
|
|
286
|
+
# Pad the end sequence to ensure divisibility
|
|
287
|
+
padding_length = ((SL + CL_max) * num_points) - len(X0)
|
|
288
|
+
X0 = np.pad(X0, (0, padding_length), 'constant', constant_values=0)
|
|
289
|
+
if debug:
|
|
290
|
+
print('\tpadding_length', padding_length, file=sys.stderr)
|
|
291
|
+
print('\tnew len(X0)', len(X0), file=sys.stderr)
|
|
292
|
+
|
|
293
|
+
# Fill the initialized arrays with data in blocks
|
|
294
|
+
for i in range(num_points):
|
|
295
|
+
Xd[i] = X0[SL * i : SL * (i + 1) + CL_max]
|
|
296
|
+
|
|
297
|
+
return Xd
|
|
298
|
+
|
|
299
|
+
def one_hot_encode(Xd):
|
|
300
|
+
"""
|
|
301
|
+
Perform one-hot encoding on the input sequence data (Xd).
|
|
302
|
+
|
|
303
|
+
Parameters:
|
|
304
|
+
- Xd (numpy.ndarray): An array of integers representing the input sequence data where each nucleotide
|
|
305
|
+
is encoded as an integer (1 for 'A', 2 for 'C', 3 for 'G', 4 for 'T', and 0 for padding).
|
|
306
|
+
|
|
307
|
+
Returns:
|
|
308
|
+
- numpy.ndarray: the one-hot encoded input sequence data.
|
|
309
|
+
"""
|
|
310
|
+
|
|
311
|
+
# One-hot encoding of the inputs:
|
|
312
|
+
# 1: A; 2: C; 3: G; 4: T; 0: padding
|
|
313
|
+
IN_MAP = np.asarray([[0, 0, 0, 0],
|
|
314
|
+
[1, 0, 0, 0],
|
|
315
|
+
[0, 1, 0, 0],
|
|
316
|
+
[0, 0, 1, 0],
|
|
317
|
+
[0, 0, 0, 1]])
|
|
318
|
+
|
|
319
|
+
return IN_MAP[Xd.astype('int8')]
|
|
320
|
+
|
|
321
|
+
# NOTE: No need to reverse complement the sequence, as sequence is already reverse complemented from previous step
|
|
322
|
+
|
|
323
|
+
# Replace all non-ACTG to N
|
|
324
|
+
allowed_chars = {'A', 'C', 'G', 'T'} # NOTE: this will turn all lowercase actg into N! (will not happen in here as seq already uppered)
|
|
325
|
+
seq = ''.join(char if char in allowed_chars else 'N' for char in input_string)
|
|
326
|
+
|
|
327
|
+
# Convert to vector array
|
|
328
|
+
seq = 'N' * (CL_max // 2) + seq + 'N' * (CL_max // 2)
|
|
329
|
+
seq = seq.replace('A', '1').replace('C', '2').replace('G', '3').replace('T', '4').replace('N', '0')
|
|
330
|
+
|
|
331
|
+
# One-hot-encode the inputs
|
|
332
|
+
if debug:
|
|
333
|
+
print('\n\t[DEBUG] create_datapoints:', file=sys.stderr)
|
|
334
|
+
print('\tlen(seq):', len(seq), file=sys.stderr)
|
|
335
|
+
X0 = np.asarray(list(map(int, list(seq)))) # convert string to np array
|
|
336
|
+
if debug:
|
|
337
|
+
print('\tX0.shape', X0.shape, file=sys.stderr)
|
|
338
|
+
Xd = reformat_data(X0) # apply window size
|
|
339
|
+
if debug:
|
|
340
|
+
print('\tXd.shape', Xd.shape, file=sys.stderr)
|
|
341
|
+
X = one_hot_encode(Xd) # one-hot encode
|
|
342
|
+
if debug:
|
|
343
|
+
print('\tX', X.shape, file=sys.stderr)
|
|
344
|
+
return X
|
|
345
|
+
|
|
346
|
+
def convert_sequences(datafile_path, output_dir, SL, CL_max, chunk_size=100, SEQ=None, debug=False):
|
|
347
|
+
'''
|
|
348
|
+
Script to convert datafile into a one-hot encoded dataset ready to input to model.
|
|
349
|
+
If HDF5 file used, data is chunked for loading.
|
|
350
|
+
|
|
351
|
+
Parameters:
|
|
352
|
+
- datafile_path: path to the datafile
|
|
353
|
+
- output_dir: output directory path
|
|
354
|
+
- SEQ: list of sequences
|
|
355
|
+
|
|
356
|
+
Returns:
|
|
357
|
+
- Path to the dataset.
|
|
358
|
+
- LEN: list of how many chunks each gene takes up
|
|
359
|
+
'''
|
|
360
|
+
|
|
361
|
+
def process_chunk(NEW_CHUNK_SIZE, i, SEQ, LEN, out_h5f):
|
|
362
|
+
'''Processes an entire chunk and writes to dataset.'''
|
|
363
|
+
X_batch = []
|
|
364
|
+
for j in range(NEW_CHUNK_SIZE):
|
|
365
|
+
idx = i * chunk_size + j
|
|
366
|
+
|
|
367
|
+
seq_decode = SEQ[idx]
|
|
368
|
+
X = create_datapoints(seq_decode, SL, CL_max, debug=debug)
|
|
369
|
+
if debug:
|
|
370
|
+
print('\tX.shape:', X.shape, file=sys.stderr)
|
|
371
|
+
LEN.append(len(X))
|
|
372
|
+
X_batch.extend(X)
|
|
373
|
+
|
|
374
|
+
# Convert batches to arrays and save as HDF5
|
|
375
|
+
X_batch = np.asarray(X_batch).astype('int8')
|
|
376
|
+
if debug:
|
|
377
|
+
print('\tNEW_CHUNK_SIZE:', NEW_CHUNK_SIZE, file=sys.stderr)
|
|
378
|
+
print("\tX_batch.shape:", X_batch.shape, file=sys.stderr)
|
|
379
|
+
utils.log_memory_usage()
|
|
380
|
+
out_h5f.create_dataset('X' + str(i), data=X_batch)
|
|
381
|
+
|
|
382
|
+
# determine whether to convert an h5 or txt file
|
|
383
|
+
file_ext = os.path.splitext(datafile_path)[1]
|
|
384
|
+
assert file_ext in ['.h5', '.txt']
|
|
385
|
+
use_h5 = file_ext == '.h5'
|
|
386
|
+
|
|
387
|
+
# read the given input file if both datastreams were not provided
|
|
388
|
+
if SEQ == None:
|
|
389
|
+
print(f"\t[INFO] Reading {datafile_path} ... ")
|
|
390
|
+
if use_h5:
|
|
391
|
+
with h5py.File(datafile_path, 'r') as in_h5f:
|
|
392
|
+
SEQ = in_h5f['SEQ'][:]
|
|
393
|
+
else:
|
|
394
|
+
SEQ = []
|
|
395
|
+
with open(datafile_path, 'r') as in_file:
|
|
396
|
+
lines = in_file.readlines()
|
|
397
|
+
for i, line in enumerate(lines):
|
|
398
|
+
if i % 2 == 1:
|
|
399
|
+
SEQ.append(line)
|
|
400
|
+
else:
|
|
401
|
+
print('\t[INFO] NAME and SEQ data provided, skipping reading ...')
|
|
402
|
+
|
|
403
|
+
num_seqs = len(SEQ)
|
|
404
|
+
if debug:
|
|
405
|
+
print('\n\t[DEBUG] convert_sequences', file=sys.stderr)
|
|
406
|
+
print("\tnum_seqs: ", num_seqs, file=sys.stderr)
|
|
407
|
+
|
|
408
|
+
LEN = [] # number of batches for each sequence
|
|
409
|
+
|
|
410
|
+
# write to h5 file by chunking and one-hot encoding inputs
|
|
411
|
+
if use_h5:
|
|
412
|
+
dataset_path = f'{output_dir}dataset.h5'
|
|
413
|
+
|
|
414
|
+
print(f"\t[INFO] Writing {dataset_path} ... ")
|
|
415
|
+
|
|
416
|
+
with h5py.File(dataset_path, 'w') as out_h5f:
|
|
417
|
+
|
|
418
|
+
# create dataset
|
|
419
|
+
num_chunks = utils.ceil_div(num_seqs, chunk_size) # ensures that even if num_seqs < CHUNK_SIZE, will still create a chunk
|
|
420
|
+
for i in tqdm(range(num_chunks), desc='Processing chunks...'):
|
|
421
|
+
|
|
422
|
+
# each dataset has CHUNK_SIZE genes
|
|
423
|
+
if i == num_chunks - 1: # if last chunk, process remainder or full chunk size if no remainder
|
|
424
|
+
NEW_CHUNK_SIZE = num_seqs % chunk_size or chunk_size
|
|
425
|
+
else:
|
|
426
|
+
NEW_CHUNK_SIZE = chunk_size
|
|
427
|
+
|
|
428
|
+
# chunk conversion
|
|
429
|
+
process_chunk(NEW_CHUNK_SIZE, i, SEQ, LEN, out_h5f)
|
|
430
|
+
|
|
431
|
+
# convert to tensor and write directly to a binary PyTorch file for quick loading
|
|
432
|
+
else:
|
|
433
|
+
dataset_path = f'{output_dir}/dataset.pt'
|
|
434
|
+
|
|
435
|
+
print(f"\t[INFO] Writing {dataset_path} ... ")
|
|
436
|
+
X_all = []
|
|
437
|
+
for idx in range(num_seqs):
|
|
438
|
+
seq_decode = SEQ[idx].decode('ascii')
|
|
439
|
+
X = create_datapoints(seq_decode, SL, CL_max, debug=debug)
|
|
440
|
+
if debug:
|
|
441
|
+
print('\tX.shape:', X.shape, file=sys.stderr)
|
|
442
|
+
utils.log_memory_usage()
|
|
443
|
+
LEN.append(len(X))
|
|
444
|
+
X_all.extend(X)
|
|
445
|
+
|
|
446
|
+
# convert batches to a tensor
|
|
447
|
+
X_tensor = torch.tensor(X_all, dtype=torch.int8)
|
|
448
|
+
|
|
449
|
+
# save as a binary file
|
|
450
|
+
torch.save(X_tensor, dataset_path)
|
|
451
|
+
|
|
452
|
+
return dataset_path, LEN
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
################
|
|
456
|
+
## STEP 3 ##
|
|
457
|
+
################
|
|
458
|
+
|
|
459
|
+
def setup_device():
|
|
460
|
+
"""Select computation device based on availability."""
|
|
461
|
+
device_str = "cuda" if torch.cuda.is_available() else "mps" if platform.system() == "Darwin" else "cpu"
|
|
462
|
+
return torch.device(device_str)
|
|
463
|
+
|
|
464
|
+
def load_model(model_path, device, flanking_size):
|
|
465
|
+
"""Loads the given model."""
|
|
466
|
+
# Hyper-parameters:
|
|
467
|
+
# L: Number of convolution kernels
|
|
468
|
+
# W: Convolution window size in each residual unit
|
|
469
|
+
# AR: Atrous rate in each residual unit
|
|
470
|
+
L = 32
|
|
471
|
+
W = np.asarray([11, 11, 11, 11])
|
|
472
|
+
AR = np.asarray([1, 1, 1, 1])
|
|
473
|
+
N_GPUS = 2
|
|
474
|
+
BATCH_SIZE = 18*N_GPUS
|
|
475
|
+
|
|
476
|
+
if int(flanking_size) == 80:
|
|
477
|
+
W = np.asarray([11, 11, 11, 11])
|
|
478
|
+
AR = np.asarray([1, 1, 1, 1])
|
|
479
|
+
BATCH_SIZE = 18*N_GPUS
|
|
480
|
+
elif int(flanking_size) == 400:
|
|
481
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11])
|
|
482
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4])
|
|
483
|
+
BATCH_SIZE = 18*N_GPUS
|
|
484
|
+
elif int(flanking_size) == 2000:
|
|
485
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11,
|
|
486
|
+
21, 21, 21, 21])
|
|
487
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4,
|
|
488
|
+
10, 10, 10, 10])
|
|
489
|
+
BATCH_SIZE = 12*N_GPUS
|
|
490
|
+
elif int(flanking_size) == 10000:
|
|
491
|
+
W = np.asarray([11, 11, 11, 11, 11, 11, 11, 11,
|
|
492
|
+
21, 21, 21, 21, 41, 41, 41, 41])
|
|
493
|
+
AR = np.asarray([1, 1, 1, 1, 4, 4, 4, 4,
|
|
494
|
+
10, 10, 10, 10, 25, 25, 25, 25])
|
|
495
|
+
BATCH_SIZE = 6*N_GPUS
|
|
496
|
+
|
|
497
|
+
CL = 2 * np.sum(AR*(W-1))
|
|
498
|
+
|
|
499
|
+
print(f"\t[INFO] Context nucleotides: {CL}")
|
|
500
|
+
|
|
501
|
+
model = SpliceAI(L, W, AR).to(device)
|
|
502
|
+
model.load_state_dict(torch.load(model_path, map_location=device, weights_only=True))
|
|
503
|
+
model = model.to(device)
|
|
504
|
+
|
|
505
|
+
params = {'L': L, 'W': W, 'AR': AR, 'CL': CL, 'BATCH_SIZE': BATCH_SIZE, 'N_GPUS': N_GPUS}
|
|
506
|
+
|
|
507
|
+
return model, params
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
################
|
|
511
|
+
## STEP 4 ##
|
|
512
|
+
################
|
|
513
|
+
|
|
514
|
+
# only used when file in hdf5
|
|
515
|
+
def load_shard(h5f, batch_size, shard_idx):
|
|
516
|
+
'''
|
|
517
|
+
Loads a selected shard from HDF5 file.
|
|
518
|
+
|
|
519
|
+
Parameters:
|
|
520
|
+
- h5f: an OPEN dataset file in read mode
|
|
521
|
+
'''
|
|
522
|
+
|
|
523
|
+
X = h5f[f'X{shard_idx}'][:].transpose(0, 2, 1)
|
|
524
|
+
X = torch.tensor(X, dtype=torch.float32)
|
|
525
|
+
ds = TensorDataset(X)
|
|
526
|
+
|
|
527
|
+
return DataLoader(ds, batch_size=batch_size, shuffle=False, drop_last=False, pin_memory=True)
|
|
528
|
+
|
|
529
|
+
def flush_predictions(predictions, file_path):
|
|
530
|
+
"""
|
|
531
|
+
Flush predictions continuously to HDF5 file, in cases where too many predictions are currently in memory.
|
|
532
|
+
|
|
533
|
+
Parameters:
|
|
534
|
+
- predictions: Tensor of predictions to save.
|
|
535
|
+
- file_path: Path to the file where predictions are saved.
|
|
536
|
+
"""
|
|
537
|
+
with h5py.File(file_path, 'a') as f:
|
|
538
|
+
if 'predictions' in f:
|
|
539
|
+
dataset = f['predictions']
|
|
540
|
+
dataset.resize((dataset.shape[0] + predictions.shape[0]), axis=0)
|
|
541
|
+
dataset[-predictions.shape[0]:] = predictions.numpy()
|
|
542
|
+
else:
|
|
543
|
+
maxshape = (None,) + predictions.shape[1:]
|
|
544
|
+
f.create_dataset('predictions', data=predictions.numpy(), maxshape=maxshape, chunks=True)
|
|
545
|
+
|
|
546
|
+
def get_prediction(model, dataset_path, device, batch_size, output_dir, flush_predict_threshold=500, debug=False):
|
|
547
|
+
"""
|
|
548
|
+
Parameters:
|
|
549
|
+
- model (torch.nn.Module): The SpliceAI model to be evaluated.
|
|
550
|
+
- dataset_path (path): Path to the selected dataset.
|
|
551
|
+
- device (torch.device): The computational device (CUDA, MPS, CPU).
|
|
552
|
+
- batch_size (int): The batch size for prediction.
|
|
553
|
+
- output_dir (str): Root of output directory for predict file.
|
|
554
|
+
- flush_predict_threshold (int): The number of predictions to collect before flushing to file.
|
|
555
|
+
|
|
556
|
+
Returns:
|
|
557
|
+
- Path to predictions binary file
|
|
558
|
+
"""
|
|
559
|
+
# define batch_size and count
|
|
560
|
+
count = 0
|
|
561
|
+
print(f'\t[INFO] Batch size: {batch_size}')
|
|
562
|
+
if debug:
|
|
563
|
+
print('\n\t[DEBUG] get_prediction', file=sys.stderr)
|
|
564
|
+
|
|
565
|
+
# put model in evaluation mode
|
|
566
|
+
model.eval()
|
|
567
|
+
print('\t[INFO] Model in evaluation mode.')
|
|
568
|
+
|
|
569
|
+
# determine which file to proceed with
|
|
570
|
+
file_ext = os.path.splitext(dataset_path)[1]
|
|
571
|
+
assert file_ext in ['.h5', '.pt']
|
|
572
|
+
use_h5 = file_ext == '.h5'
|
|
573
|
+
|
|
574
|
+
if use_h5: # read from the h5 file
|
|
575
|
+
|
|
576
|
+
# initialize predict file (to prevent continuous appending)
|
|
577
|
+
predict_path = f'{output_dir}predict.h5'
|
|
578
|
+
pfile = h5py.File(predict_path, 'w')
|
|
579
|
+
pfile.close()
|
|
580
|
+
|
|
581
|
+
# read dataset and iterate over shards in index
|
|
582
|
+
h5f = h5py.File(dataset_path, 'r')
|
|
583
|
+
idxs = np.arange(len(h5f.keys()))
|
|
584
|
+
if debug:
|
|
585
|
+
print('\th5 indices:', idxs, file=sys.stderr)
|
|
586
|
+
|
|
587
|
+
for i, shard_idx in enumerate(idxs, 1):
|
|
588
|
+
|
|
589
|
+
if debug:
|
|
590
|
+
print('\tshard_idx, h5 len', shard_idx, len(h5f[f'X{shard_idx}']), file=sys.stderr)
|
|
591
|
+
loader = load_shard(h5f, batch_size, shard_idx)
|
|
592
|
+
if debug:
|
|
593
|
+
print('\t\tloader batches ', len(loader), file=sys.stderr)
|
|
594
|
+
|
|
595
|
+
batch_ypred = [] # list of tensors containing the predictions from model
|
|
596
|
+
pbar = tqdm(loader, leave=False, total=len(loader), desc=f'Shard {i}/{len(idxs)}')
|
|
597
|
+
for batch in pbar:
|
|
598
|
+
DNAs = batch[0].to(device)
|
|
599
|
+
if debug:
|
|
600
|
+
print('\t\t\tbatch DNA ', len(DNAs), end='', file=sys.stderr)
|
|
601
|
+
DNAs = DNAs.to(torch.float32).to(device)
|
|
602
|
+
with torch.no_grad():
|
|
603
|
+
y_pred = model(DNAs)
|
|
604
|
+
y_pred = y_pred.detach().cpu()
|
|
605
|
+
|
|
606
|
+
if debug:
|
|
607
|
+
print('\tbatch ', len(y_pred), file=sys.stderr)
|
|
608
|
+
|
|
609
|
+
batch_ypred.append(y_pred)
|
|
610
|
+
count += 1
|
|
611
|
+
|
|
612
|
+
# write predictions to file if exceeding threshold
|
|
613
|
+
if len(batch_ypred) > flush_predict_threshold:
|
|
614
|
+
print(f'\t[INFO] Reached {flush_predict_threshold} predictions. Flushing to file...', file=sys.stderr)
|
|
615
|
+
batch_ypred_tensor = torch.cat(batch_ypred, dim=0)
|
|
616
|
+
flush_predictions(batch_ypred_tensor, predict_path)
|
|
617
|
+
batch_ypred = [] # reset the list after flushing
|
|
618
|
+
|
|
619
|
+
pbar.update(1)
|
|
620
|
+
|
|
621
|
+
if debug:
|
|
622
|
+
utils.log_memory_usage()
|
|
623
|
+
|
|
624
|
+
pbar.close()
|
|
625
|
+
|
|
626
|
+
# flush any remaining predictions
|
|
627
|
+
if batch_ypred:
|
|
628
|
+
print(f'\t[INFO] Flushing remaining {len(batch_ypred)} predictions..', file=sys.stderr)
|
|
629
|
+
batch_ypred_tensor = torch.cat(batch_ypred, dim=0)
|
|
630
|
+
flush_predictions(batch_ypred_tensor, predict_path)
|
|
631
|
+
|
|
632
|
+
h5f.close()
|
|
633
|
+
|
|
634
|
+
else: # read from the PyTorch file
|
|
635
|
+
predict_path = f'{output_dir}predict.pt'
|
|
636
|
+
|
|
637
|
+
# load all data
|
|
638
|
+
X = torch.load(dataset_path).transpose(0, 2, 1)
|
|
639
|
+
X = torch.tensor(X, dtype=torch.float32)
|
|
640
|
+
ds = TensorDataset(X)
|
|
641
|
+
loader = DataLoader(ds, batch_size=batch_size, shuffle=False, drop_last=False, pin_memory=True)
|
|
642
|
+
|
|
643
|
+
batch_ypred = [] # list of tensors containing the predictions from model
|
|
644
|
+
pbar = tqdm(loader, leave=False, total=len(loader))
|
|
645
|
+
for batch in pbar:
|
|
646
|
+
DNAs = batch[0].to(device)
|
|
647
|
+
DNAs = DNAs.to(torch.float32).to(device)
|
|
648
|
+
|
|
649
|
+
with torch.no_grad():
|
|
650
|
+
y_pred = model(DNAs)
|
|
651
|
+
|
|
652
|
+
batch_ypred.append(y_pred.detach().cpu())
|
|
653
|
+
count += 1
|
|
654
|
+
|
|
655
|
+
pbar.update(1)
|
|
656
|
+
|
|
657
|
+
pbar.close()
|
|
658
|
+
|
|
659
|
+
print('\t[INFO] Saving predictions...')
|
|
660
|
+
predictions = torch.cat(batch_ypred, dim=0)
|
|
661
|
+
torch.save(predictions, predict_path)
|
|
662
|
+
|
|
663
|
+
# preview information
|
|
664
|
+
print(f'\t[INFO] {count} predictions collected.')
|
|
665
|
+
if debug:
|
|
666
|
+
try:
|
|
667
|
+
head_length = 5 if len(batch_ypred) >= 5 else len(batch_ypred)
|
|
668
|
+
print(f'\tPreview predictions: {batch_ypred[:head_length]}', file=sys.stderr)
|
|
669
|
+
except Exception as e:
|
|
670
|
+
print(f'Preview could not be generated: {e}.', file=sys.stderr)
|
|
671
|
+
print(f'\t[INFO] Predictions saved to {predict_path}.')
|
|
672
|
+
|
|
673
|
+
return predict_path
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
################
|
|
677
|
+
## STEP 5 ##
|
|
678
|
+
################
|
|
679
|
+
|
|
680
|
+
def write_batch_to_bed(seq_name, gene_predictions, acceptor_bed, donor_bed, threshold=1e-6, debug=False):
|
|
681
|
+
|
|
682
|
+
# flatten the predictions to a 2D array [total positions, channels]
|
|
683
|
+
if debug:
|
|
684
|
+
print('\traw prediction:', file=sys.stderr)
|
|
685
|
+
print('\t',gene_predictions.shape, file=sys.stderr)
|
|
686
|
+
print('\t',gene_predictions[:5], file=sys.stderr)
|
|
687
|
+
gene_predictions = gene_predictions.permute(0, 2, 1).contiguous().view(-1, gene_predictions.shape[1])
|
|
688
|
+
if debug:
|
|
689
|
+
print('\tflattened:', file=sys.stderr)
|
|
690
|
+
print('\t',gene_predictions.shape, file=sys.stderr)
|
|
691
|
+
print('\t',gene_predictions[:5], file=sys.stderr)
|
|
692
|
+
|
|
693
|
+
acceptor_scores = gene_predictions[:, 1].numpy() # Acceptor channel
|
|
694
|
+
donor_scores = gene_predictions[:, 2].numpy() # Donor channel
|
|
695
|
+
|
|
696
|
+
if debug:
|
|
697
|
+
print('\tacceptor\tdonor (assuming + strand):', file=sys.stderr)
|
|
698
|
+
print('\t',acceptor_scores.shape, donor_scores.shape, file=sys.stderr)
|
|
699
|
+
print('\t',acceptor_scores[:5], donor_scores[:5], file=sys.stderr)
|
|
700
|
+
|
|
701
|
+
# parse out key information from name
|
|
702
|
+
pattern = re.compile(r'.*(chr[a-zA-Z0-9_]*):(\d+)-(\d+)\(([-+.])\):([-+])')
|
|
703
|
+
match = pattern.match(seq_name)
|
|
704
|
+
|
|
705
|
+
if match:
|
|
706
|
+
chrom = match.group(1)
|
|
707
|
+
start = int(match.group(2))
|
|
708
|
+
end = int(match.group(3))
|
|
709
|
+
strand = match.group(4)
|
|
710
|
+
name = seq_name[:-2] # remove endings
|
|
711
|
+
|
|
712
|
+
if strand == '.': # in case of unknown/unspecified strand, gets the manually specified strand and use full name
|
|
713
|
+
strand = match.group(5)
|
|
714
|
+
name = seq_name
|
|
715
|
+
|
|
716
|
+
# handle file writing based on strand
|
|
717
|
+
if strand == '+':
|
|
718
|
+
for pos in range(len(acceptor_scores)): # NOTE: donor and acceptor should have same num of scores
|
|
719
|
+
acceptor_score = acceptor_scores[pos]
|
|
720
|
+
donor_score = donor_scores[pos]
|
|
721
|
+
if acceptor_score > threshold:
|
|
722
|
+
acceptor_bed.write(f"{chrom}\t{start+pos-3}\t{start+pos-1}\t{name}_Acceptor\t{acceptor_score:.6f}\t{strand}\n")
|
|
723
|
+
if donor_score > threshold:
|
|
724
|
+
donor_bed.write(f"{chrom}\t{start+pos}\t{start+pos+2}\t{name}_Donor\t{donor_score:.6f}\t{strand}\n")
|
|
725
|
+
elif strand == '-':
|
|
726
|
+
for pos in range(len(acceptor_scores)):
|
|
727
|
+
acceptor_score = acceptor_scores[pos]
|
|
728
|
+
donor_score = donor_scores[pos]
|
|
729
|
+
if acceptor_score > threshold:
|
|
730
|
+
acceptor_bed.write(f"{chrom}\t{end-pos}\t{end-pos+2}\t{name}_Acceptor\t{acceptor_score:.6f}\t{strand}\n")
|
|
731
|
+
if donor_score > threshold:
|
|
732
|
+
donor_bed.write(f"{chrom}\t{end-pos-3}\t{end-pos-1}\t{name}_Donor\t{donor_score:.6f}\t{strand}\n")
|
|
733
|
+
else:
|
|
734
|
+
print(f'\t[ERR] Undefined strand {strand}. Skipping {seq_name} batch...')
|
|
735
|
+
|
|
736
|
+
else: # does not match pattern, could be due to not having gff file, keep writing it
|
|
737
|
+
|
|
738
|
+
strand = seq_name[-1] # use the ending as the strand (when lack other information)
|
|
739
|
+
|
|
740
|
+
# write to file using absolute coordinates (using input FASTA as coordinates rather than GFF)
|
|
741
|
+
for pos in range(len(acceptor_scores)):
|
|
742
|
+
acceptor_score = acceptor_scores[pos]
|
|
743
|
+
donor_score = donor_scores[pos]
|
|
744
|
+
if acceptor_score > threshold:
|
|
745
|
+
acceptor_bed.write(f"{seq_name}\t{pos-3}\t{pos-1}\t{seq_name}_Acceptor\t{acceptor_score:.6f}\t{strand}\tabsolute_coordinates\n")
|
|
746
|
+
if donor_score > threshold:
|
|
747
|
+
donor_bed.write(f"{seq_name}\t{pos}\t{pos-2}\t{seq_name}_Donor\t{donor_score:.6f}\t{strand}\tabsolute_coordinates\n")
|
|
748
|
+
|
|
749
|
+
# NOTE: need to handle naming when gff file not provided.
|
|
750
|
+
def generate_bed(predict_file, NAME, LEN, output_dir, threshold=1e-6, batch_ypred=None, debug=False):
|
|
751
|
+
'''
|
|
752
|
+
Generates the BED file pertaining to the predictions
|
|
753
|
+
'''
|
|
754
|
+
# determine which file to proceed with
|
|
755
|
+
file_ext = os.path.splitext(predict_file)[1]
|
|
756
|
+
assert file_ext in ['.h5', '.pt']
|
|
757
|
+
use_h5 = file_ext == '.h5'
|
|
758
|
+
|
|
759
|
+
# load the predictions (if not already there)
|
|
760
|
+
if use_h5:
|
|
761
|
+
print('\t[INFO] Loading predictions...')
|
|
762
|
+
with h5py.File(predict_file, 'r') as h5f:
|
|
763
|
+
batch_ypred_np = h5f['predictions'][:]
|
|
764
|
+
batch_ypred = torch.tensor(batch_ypred_np)
|
|
765
|
+
elif batch_ypred is not None:
|
|
766
|
+
batch_ypred = torch.load(predict_file)
|
|
767
|
+
|
|
768
|
+
if debug:
|
|
769
|
+
print('\n\t[DEBUG] generate_bed', file=sys.stderr)
|
|
770
|
+
print('\tlen(NAME)', len(NAME), 'len(LEN)', len(LEN), 'sum(LEN)', sum(LEN), 'len(batch_ypred)', len(batch_ypred), file=sys.stderr)
|
|
771
|
+
assert len(NAME) == len(LEN)
|
|
772
|
+
assert sum(LEN) == len(batch_ypred)
|
|
773
|
+
|
|
774
|
+
print('\t[INFO] Batch predictions loaded.')
|
|
775
|
+
print(f'\t[INFO] Shape of predictions: {batch_ypred.shape}')
|
|
776
|
+
print(f'\t[INFO] {len(LEN)} targets detected.')
|
|
777
|
+
|
|
778
|
+
acceptor_bed_path = f'{output_dir}acceptor_predictions.bed'
|
|
779
|
+
donor_bed_path = f'{output_dir}donor_predictions.bed'
|
|
780
|
+
|
|
781
|
+
with open(acceptor_bed_path, 'w') as acceptor_bed, open(donor_bed_path, 'w') as donor_bed:
|
|
782
|
+
start_idx = 0
|
|
783
|
+
for i in tqdm(range(len(NAME)), desc='Generating BED tasks...'):
|
|
784
|
+
seq_name = NAME[i]
|
|
785
|
+
num_batches = LEN[i] # number of batches for this gene
|
|
786
|
+
end_idx = start_idx + num_batches
|
|
787
|
+
|
|
788
|
+
# extract predictions for the current gene
|
|
789
|
+
gene_predictions = batch_ypred[start_idx:end_idx]
|
|
790
|
+
|
|
791
|
+
# write to BED file
|
|
792
|
+
write_batch_to_bed(seq_name, gene_predictions, acceptor_bed, donor_bed, threshold=threshold, debug=debug)
|
|
793
|
+
|
|
794
|
+
# update the start index for the next gene
|
|
795
|
+
start_idx = end_idx
|
|
796
|
+
|
|
797
|
+
print(f"\t[INFO] Acceptor BED file saved to {acceptor_bed_path}")
|
|
798
|
+
print(f"\t[INFO] Donor BED file saved to {donor_bed_path}")
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
#################
|
|
802
|
+
## STEP 4o ##
|
|
803
|
+
#################
|
|
804
|
+
|
|
805
|
+
def predict_and_write(model, dataset_path, device, batch_size, NAME, LEN, output_dir, threshold=1e-6, debug=False):
|
|
806
|
+
|
|
807
|
+
# define batch_size
|
|
808
|
+
print(f'\t[INFO] Batch size: {batch_size}')
|
|
809
|
+
if debug:
|
|
810
|
+
print('\n\t[DEBUG] predict_and_write', file=sys.stderr)
|
|
811
|
+
print('\tlen(NAME)', len(NAME), 'len(LEN)', len(LEN), 'sum(LEN)', sum(LEN), file=sys.stderr)
|
|
812
|
+
assert len(NAME) == len(LEN)
|
|
813
|
+
|
|
814
|
+
# put model in evaluation mode
|
|
815
|
+
model.eval()
|
|
816
|
+
print('\t[INFO] Model in evaluation mode.')
|
|
817
|
+
|
|
818
|
+
# determine which file to proceed with
|
|
819
|
+
file_ext = os.path.splitext(dataset_path)[1]
|
|
820
|
+
assert file_ext in ['.h5', '.pt']
|
|
821
|
+
use_h5 = file_ext == '.h5'
|
|
822
|
+
|
|
823
|
+
# initialize output BED files
|
|
824
|
+
acceptor_bed_path = f'{output_dir}acceptor_predictions.bed'
|
|
825
|
+
donor_bed_path = f'{output_dir}donor_predictions.bed'
|
|
826
|
+
acceptor_bed = open(acceptor_bed_path, 'w')
|
|
827
|
+
donor_bed = open(donor_bed_path, 'w')
|
|
828
|
+
|
|
829
|
+
count = 0
|
|
830
|
+
len_idx = 0
|
|
831
|
+
accumulated_predictions = []
|
|
832
|
+
accumulated_length = 0
|
|
833
|
+
|
|
834
|
+
if use_h5: # read from the h5 file
|
|
835
|
+
|
|
836
|
+
with h5py.File(dataset_path, 'r') as h5f:
|
|
837
|
+
|
|
838
|
+
# iterate over shards in index
|
|
839
|
+
idxs = np.arange(len(h5f.keys()))
|
|
840
|
+
if debug:
|
|
841
|
+
print('\th5 indices:', idxs, file=sys.stderr)
|
|
842
|
+
|
|
843
|
+
for i, shard_idx in enumerate(idxs, 1):
|
|
844
|
+
|
|
845
|
+
if debug:
|
|
846
|
+
print('\tshard_idx, h5 len', shard_idx, len(h5f[f'X{shard_idx}']), file=sys.stderr)
|
|
847
|
+
loader = load_shard(h5f, batch_size, shard_idx)
|
|
848
|
+
if debug:
|
|
849
|
+
print('\t\tloader batches ', len(loader), file=sys.stderr)
|
|
850
|
+
|
|
851
|
+
pbar = tqdm(loader, leave=False, total=len(loader), desc=f'Shard {i}/{len(idxs)}')
|
|
852
|
+
for batch in pbar:
|
|
853
|
+
|
|
854
|
+
# getting predictions
|
|
855
|
+
DNAs = batch[0].to(device)
|
|
856
|
+
if debug:
|
|
857
|
+
print('\t\t\tbatch DNA ', len(DNAs), end='', file=sys.stderr) # should be 36 -> referring to 5k blocks
|
|
858
|
+
DNAs = DNAs.to(torch.float32).to(device)
|
|
859
|
+
with torch.no_grad():
|
|
860
|
+
y_pred = model(DNAs)
|
|
861
|
+
y_pred = y_pred.detach().cpu()
|
|
862
|
+
count += len(y_pred) # update the count for the current batch
|
|
863
|
+
|
|
864
|
+
if debug:
|
|
865
|
+
print('\tbatch ', len(y_pred), file=sys.stderr)
|
|
866
|
+
print('\tcount ', count, 'cumsum of lengths ', sum(LEN[:len_idx+1]), file=sys.stderr)
|
|
867
|
+
|
|
868
|
+
# handle predictions and write to BED
|
|
869
|
+
accumulated_predictions.append(y_pred)
|
|
870
|
+
accumulated_length += len(y_pred)
|
|
871
|
+
|
|
872
|
+
while len_idx < len(LEN) and accumulated_length >= LEN[len_idx]:
|
|
873
|
+
# enough predictions to cover the current gene
|
|
874
|
+
seq_name = NAME[len_idx]
|
|
875
|
+
gene_length = LEN[len_idx]
|
|
876
|
+
|
|
877
|
+
# combine accumulated predictions into a tensor for the current gene
|
|
878
|
+
accumulated_predictions = torch.cat(accumulated_predictions, dim=0)
|
|
879
|
+
combined_predictions = accumulated_predictions[:gene_length]
|
|
880
|
+
|
|
881
|
+
if debug:
|
|
882
|
+
print(f'\t[predict_and_write] Writing gene {seq_name} with length {gene_length}', file=sys.stderr)
|
|
883
|
+
print(f'\tlen(accumulated_predictions) {len(accumulated_predictions)}, accumulated_length, {accumulated_length}', file=sys.stderr)
|
|
884
|
+
|
|
885
|
+
write_batch_to_bed(seq_name, combined_predictions, acceptor_bed, donor_bed, threshold=threshold, debug=debug)
|
|
886
|
+
|
|
887
|
+
# move to the next gene
|
|
888
|
+
accumulated_predictions = [accumulated_predictions[gene_length:]]
|
|
889
|
+
accumulated_length -= gene_length
|
|
890
|
+
len_idx += 1
|
|
891
|
+
|
|
892
|
+
pbar.update(1)
|
|
893
|
+
|
|
894
|
+
if debug:
|
|
895
|
+
utils.log_memory_usage()
|
|
896
|
+
|
|
897
|
+
pbar.close()
|
|
898
|
+
|
|
899
|
+
else: # read from the PyTorch file
|
|
900
|
+
|
|
901
|
+
# load all data
|
|
902
|
+
X = torch.load(dataset_path).transpose(0, 2, 1)
|
|
903
|
+
X = torch.tensor(X, dtype=torch.float32)
|
|
904
|
+
ds = TensorDataset(X)
|
|
905
|
+
loader = DataLoader(ds, batch_size=batch_size, shuffle=False, drop_last=False, pin_memory=True)
|
|
906
|
+
|
|
907
|
+
pbar = tqdm(loader, leave=False, total=len(loader))
|
|
908
|
+
for batch in pbar:
|
|
909
|
+
|
|
910
|
+
# getting prediction
|
|
911
|
+
DNAs = batch[0].to(device)
|
|
912
|
+
DNAs = DNAs.to(torch.float32).to(device)
|
|
913
|
+
with torch.no_grad():
|
|
914
|
+
y_pred = model(DNAs)
|
|
915
|
+
y_pred = y_pred.detach().cpu()
|
|
916
|
+
count += 1
|
|
917
|
+
|
|
918
|
+
# writing to BED
|
|
919
|
+
seq_name = NAME[i]
|
|
920
|
+
gene_predictions = y_pred.permute(0, 2, 1).contiguous().view(-1, y_pred.shape[1])
|
|
921
|
+
write_batch_to_bed(seq_name, gene_predictions, acceptor_bed, donor_bed, threshold=threshold, debug=debug)
|
|
922
|
+
|
|
923
|
+
pbar.update(1)
|
|
924
|
+
|
|
925
|
+
pbar.close()
|
|
926
|
+
|
|
927
|
+
acceptor_bed.close()
|
|
928
|
+
donor_bed.close()
|
|
929
|
+
|
|
930
|
+
print(f'\t[INFO] {count} predictions processed.')
|
|
931
|
+
print(f"\t[INFO] Acceptor BED file saved to {acceptor_bed_path}")
|
|
932
|
+
print(f"\t[INFO] Donor BED file saved to {donor_bed_path}")
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
################
|
|
936
|
+
## DRIVER ##
|
|
937
|
+
################
|
|
938
|
+
|
|
939
|
+
# Command-line prediction
|
|
940
|
+
def predict_cli(args):
|
|
941
|
+
'''
|
|
942
|
+
Parameters:
|
|
943
|
+
- args (argparse.args):
|
|
944
|
+
- model: Path to SpliceAI model
|
|
945
|
+
- output_dir: Output directory
|
|
946
|
+
- flanking_size: Flanking sequence size
|
|
947
|
+
- input_sequence: FASTA file
|
|
948
|
+
- gff_file (opt): GFF file
|
|
949
|
+
- threshold (opt): Threshold for prediction
|
|
950
|
+
- debug (opt): Debug mode
|
|
951
|
+
- predict_all (opt): Run steps 4 and 5 vs 4o
|
|
952
|
+
- hdf_threshold (opt): Threshold for HDF5 file
|
|
953
|
+
- flush_threshold (opt): Threshold for flushing predictions
|
|
954
|
+
- split_threshold (opt): Threshold for splitting FASTA file
|
|
955
|
+
- chunk_size (opt): Chunk size for processing
|
|
956
|
+
|
|
957
|
+
'''
|
|
958
|
+
print("Running SpliceAI-toolkit with 'predict' mode")
|
|
959
|
+
|
|
960
|
+
# get all input args
|
|
961
|
+
output_dir = args.output_dir
|
|
962
|
+
flanking_size = args.flanking_size
|
|
963
|
+
model_path = args.model
|
|
964
|
+
input_sequence = args.input_sequence
|
|
965
|
+
gff_file = args.annotation_file
|
|
966
|
+
threshold = np.float32(args.threshold)
|
|
967
|
+
debug = args.debug
|
|
968
|
+
predict_all = args.predict_all
|
|
969
|
+
hdf_threshold_len = args.hdf_threshold
|
|
970
|
+
flush_predict_threshold = args.flush_threshold
|
|
971
|
+
split_fasta_threshold = args.split_threshold
|
|
972
|
+
chunk_size = args.chunk_size
|
|
973
|
+
|
|
974
|
+
# initialize global variables
|
|
975
|
+
consts = utils.initialize_constants(flanking_size, hdf_threshold_len, flush_predict_threshold, chunk_size, split_fasta_threshold)
|
|
976
|
+
|
|
977
|
+
print(f'''Running predict with SL: {consts['SL']}, flanking_size: {flanking_size}, threshold: {threshold}, in {'debug, ' if debug else ''}{'turbo' if not predict_all else 'all'} mode.
|
|
978
|
+
model: {model_path},
|
|
979
|
+
input_sequence: {input_sequence},
|
|
980
|
+
gff_file: {gff_file},
|
|
981
|
+
output_dir: {output_dir},
|
|
982
|
+
hdf_threshold_len: {hdf_threshold_len}, flush_predict_threshold: {flush_predict_threshold}, split_fasta_threshold: {split_fasta_threshold}, chunk_size: {chunk_size}''')
|
|
983
|
+
|
|
984
|
+
# create output directory
|
|
985
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
986
|
+
output_base = utils.initialize_paths(output_dir, flanking_size, consts['SL'])
|
|
987
|
+
print("Output path: ", output_base, file=sys.stderr)
|
|
988
|
+
print("Model path: ", model_path, file=sys.stderr)
|
|
989
|
+
print("Flanking sequence size: ", flanking_size, file=sys.stderr)
|
|
990
|
+
print("Sequence length: ", consts['SL'], file=sys.stderr)
|
|
991
|
+
|
|
992
|
+
### PART 1: Extracting input sequence
|
|
993
|
+
print("--- Step 1: Extracting input sequence ... ---", flush=True)
|
|
994
|
+
start_time = time.time()
|
|
995
|
+
|
|
996
|
+
# if gff file is provided, extract just the gene regions into a new FASTA file
|
|
997
|
+
if gff_file:
|
|
998
|
+
print('\t[INFO] GFF file provided: extracting gene sequences.')
|
|
999
|
+
new_fasta = process_gff(input_sequence, gff_file, output_base)
|
|
1000
|
+
datafile_path, NAME, SEQ = get_sequences(new_fasta, output_base, consts['CL_max'], hdf_threshold_len=consts['HDF_THRESHOLD_LEN'], split_fasta_threshold=consts['SPLIT_FASTA_THRESHOLD'], debug=debug)
|
|
1001
|
+
else:
|
|
1002
|
+
# otherwise, collect all sequences from FASTA into file
|
|
1003
|
+
datafile_path, NAME, SEQ = get_sequences(input_sequence, output_base, consts['CL_max'], hdf_threshold_len=consts['HDF_THRESHOLD_LEN'], split_fasta_threshold=consts['SPLIT_FASTA_THRESHOLD'], debug=debug)
|
|
1004
|
+
|
|
1005
|
+
print("--- %s seconds ---" % (time.time() - start_time))
|
|
1006
|
+
|
|
1007
|
+
### PART 2: Getting one-hot encoding of inputs
|
|
1008
|
+
print("--- Step 2: Creating one-hot encoding ... ---", flush=True)
|
|
1009
|
+
start_time = time.time()
|
|
1010
|
+
|
|
1011
|
+
dataset_path, LEN = convert_sequences(datafile_path, output_base, consts['SL'], consts['CL_max'], chunk_size=consts['CHUNK_SIZE'], SEQ=SEQ, debug=debug)
|
|
1012
|
+
|
|
1013
|
+
print("--- %s seconds ---" % (time.time() - start_time))
|
|
1014
|
+
|
|
1015
|
+
### PART 3: Loading model
|
|
1016
|
+
print("--- Step 3: Load model ... ---", flush=True)
|
|
1017
|
+
start_time = time.time()
|
|
1018
|
+
|
|
1019
|
+
# setup device
|
|
1020
|
+
device = setup_device()
|
|
1021
|
+
|
|
1022
|
+
# load model from current state
|
|
1023
|
+
model, params = load_model(model_path, device, flanking_size)
|
|
1024
|
+
print(f"\t[INFO] Device: {device}, Model: {model}, Params: {params}")
|
|
1025
|
+
|
|
1026
|
+
print("--- %s seconds ---" % (time.time() - start_time))
|
|
1027
|
+
|
|
1028
|
+
if predict_all: # predict using intermediate files
|
|
1029
|
+
|
|
1030
|
+
### PART 4: Get predictions
|
|
1031
|
+
print("--- Step 4: Get predictions ... ---", flush=True)
|
|
1032
|
+
start_time = time.time()
|
|
1033
|
+
|
|
1034
|
+
predict_file = get_prediction(model, dataset_path, device, params['BATCH_SIZE'], output_base, flush_predict_threshold=consts['FLUSH_PREDICT_THRESHOLD'], debug=debug)
|
|
1035
|
+
|
|
1036
|
+
print("--- %s seconds ---" % (time.time() - start_time))
|
|
1037
|
+
|
|
1038
|
+
### PART 5: Generate BED report
|
|
1039
|
+
print("--- Step 5: Generating BED report ... ---", flush=True)
|
|
1040
|
+
start_time = time.time()
|
|
1041
|
+
|
|
1042
|
+
generate_bed(predict_file, NAME, LEN, output_base, threshold=threshold, debug=debug)
|
|
1043
|
+
|
|
1044
|
+
print("--- %s seconds ---" % (time.time() - start_time))
|
|
1045
|
+
|
|
1046
|
+
else: # combine prediction and output
|
|
1047
|
+
|
|
1048
|
+
### PART 4o: Get only predictions and write to BED
|
|
1049
|
+
print("--- Step 4o: Extract predictions to BED ... ---", flush=True)
|
|
1050
|
+
start_time = time.time()
|
|
1051
|
+
|
|
1052
|
+
predict_and_write(model, dataset_path, device, params['BATCH_SIZE'], NAME, LEN, output_base, threshold=threshold, debug=debug)
|
|
1053
|
+
|
|
1054
|
+
print("--- %s seconds ---" % (time.time() - start_time))
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
# Simplified in-memory prediction
|
|
1058
|
+
def predict(input_sequence, model_path, flanking_size):
|
|
1059
|
+
'''
|
|
1060
|
+
Parameters:
|
|
1061
|
+
- input_sequence (str): Raw gene sequence
|
|
1062
|
+
- model_path (str): Path to SpliceAI model
|
|
1063
|
+
- flanking_size (int): Size of flanking sequences
|
|
1064
|
+
|
|
1065
|
+
Outputs:
|
|
1066
|
+
- Raw predicted tensors
|
|
1067
|
+
'''
|
|
1068
|
+
|
|
1069
|
+
# Initialize global variables to defaults
|
|
1070
|
+
consts = utils.initialize_constants(flanking_size)
|
|
1071
|
+
sequence_length = len(input_sequence)
|
|
1072
|
+
|
|
1073
|
+
# One-hot encode input
|
|
1074
|
+
X = create_datapoints(input_sequence, SL=consts['SL'], CL_max=consts['CL_max'])
|
|
1075
|
+
X = torch.tensor(X, dtype=torch.float32) # Convert to tensor
|
|
1076
|
+
X = X.permute(0, 2, 1)
|
|
1077
|
+
|
|
1078
|
+
# Setup device and model
|
|
1079
|
+
device = setup_device()
|
|
1080
|
+
print(f'\t[INFO] Device: {device}')
|
|
1081
|
+
model, params = load_model(model_path, device, flanking_size)
|
|
1082
|
+
|
|
1083
|
+
# Get predictions
|
|
1084
|
+
DNAs = X.to(device)
|
|
1085
|
+
with torch.no_grad():
|
|
1086
|
+
y_pred = model(DNAs)
|
|
1087
|
+
y_pred = y_pred.detach().cpu()
|
|
1088
|
+
y_pred = y_pred.permute(0, 2, 1).contiguous().view(-1, y_pred.shape[1])
|
|
1089
|
+
y_pred = y_pred[:sequence_length, :] # crop out the extra padding
|
|
1090
|
+
|
|
1091
|
+
return y_pred
|