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,99 @@
|
|
|
1
|
+
# visualization.py
|
|
2
|
+
import matplotlib.pyplot as plt
|
|
3
|
+
import numpy as np
|
|
4
|
+
import os
|
|
5
|
+
from openspliceai.calibrate.calibrate_utils import *
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def plot_score_distribution(probs, probs_scaled, labels, output_dir, index):
|
|
9
|
+
index_names = {
|
|
10
|
+
0: ('non-splice site', 'neither'),
|
|
11
|
+
1: ('acceptor site', 'acceptor'),
|
|
12
|
+
2: ('donor site', 'donor')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
positive_indices = (labels == index)
|
|
16
|
+
probs_positive = probs[:, index][positive_indices]
|
|
17
|
+
probs_scaled_positive = probs_scaled[:, index][positive_indices]
|
|
18
|
+
|
|
19
|
+
plt.figure(figsize=(5.5, 4))
|
|
20
|
+
plt.hist(probs_positive, bins=30, alpha=0.5, label='Original')
|
|
21
|
+
plt.hist(probs_scaled_positive, bins=30, alpha=0.5, label='Calibrated')
|
|
22
|
+
plt.xlabel('Score')
|
|
23
|
+
plt.ylabel('Density')
|
|
24
|
+
plt.legend()
|
|
25
|
+
plt.grid(True)
|
|
26
|
+
plt.title(f'Score Distribution for {index_names[index][0]}')
|
|
27
|
+
plt.tight_layout()
|
|
28
|
+
plt.savefig(f"{output_dir}/calibration/prob_dist_{index_names[index][1]}.png")
|
|
29
|
+
plt.close()
|
|
30
|
+
|
|
31
|
+
def plot_calibration_curves(calibration_data, calibration_data_scaled, classes, output_dir):
|
|
32
|
+
fig, axs = plt.subplots(1, 3, figsize=(20, 5.5))
|
|
33
|
+
for i, (class_name, (orig_data, scaled_data)) in enumerate(zip(classes, zip(calibration_data, calibration_data_scaled))):
|
|
34
|
+
prob_true, prob_pred, bin_counts = orig_data
|
|
35
|
+
prob_true_s, prob_pred_s, _ = scaled_data
|
|
36
|
+
|
|
37
|
+
ci_lower, ci_upper = compute_confidence_intervals(prob_true, bin_counts)
|
|
38
|
+
ci_lower_s, ci_upper_s = compute_confidence_intervals(prob_true_s, bin_counts)
|
|
39
|
+
|
|
40
|
+
axs[i].plot(prob_pred, prob_true, 'o-', color='blue', label='Original')
|
|
41
|
+
axs[i].fill_between(prob_pred, ci_lower, ci_upper, color='blue', alpha=0.1)
|
|
42
|
+
axs[i].plot(prob_pred_s, prob_true_s, 'o-', color='green', label='Calibrated')
|
|
43
|
+
axs[i].fill_between(prob_pred_s, ci_lower_s, ci_upper_s, color='green', alpha=0.1)
|
|
44
|
+
axs[i].plot([0, 1], [0, 1], 'k--')
|
|
45
|
+
axs[i].set_title(class_name)
|
|
46
|
+
axs[i].set_xlabel('Predicted Probability')
|
|
47
|
+
axs[i].set_ylabel('Empirical Probability')
|
|
48
|
+
axs[i].legend()
|
|
49
|
+
plt.tight_layout()
|
|
50
|
+
plt.savefig(f"{output_dir}/calibration/calibration_curve.png", dpi=300)
|
|
51
|
+
plt.close()
|
|
52
|
+
|
|
53
|
+
def plot_brier_scores(brier_uncal, brier_cal, classes, output_dir):
|
|
54
|
+
plt.figure(figsize=(8, 6))
|
|
55
|
+
x = np.arange(len(classes))
|
|
56
|
+
plt.bar(x - 0.2, brier_uncal, 0.4, label='Uncalibrated')
|
|
57
|
+
plt.bar(x + 0.2, brier_cal, 0.4, label='Calibrated')
|
|
58
|
+
plt.xticks(x, classes)
|
|
59
|
+
plt.ylabel('Brier Score')
|
|
60
|
+
plt.title('Brier Score Comparison')
|
|
61
|
+
plt.legend()
|
|
62
|
+
plt.tight_layout()
|
|
63
|
+
plt.savefig(f"{output_dir}/calibration/brier_scores.png", dpi=300)
|
|
64
|
+
plt.close()
|
|
65
|
+
|
|
66
|
+
def plot_calibration_map(scaled_model, device, output_dir):
|
|
67
|
+
p1d = np.linspace(0, 1, 20)
|
|
68
|
+
p0, p1 = np.meshgrid(p1d, p1d)
|
|
69
|
+
p2 = 1 - p0 - p1
|
|
70
|
+
mask = (p2 >= 0) & (p2 <= 1)
|
|
71
|
+
p = np.vstack([p0[mask], p1[mask], p2[mask]]).T
|
|
72
|
+
|
|
73
|
+
logits = reverse_softmax(p)
|
|
74
|
+
with torch.no_grad():
|
|
75
|
+
logits_scaled = scaled_model.temperature_scale(torch.tensor(logits).float().to(device))
|
|
76
|
+
probs_scaled = torch.nn.functional.softmax(logits_scaled, dim=1).cpu().numpy()
|
|
77
|
+
|
|
78
|
+
plt.figure(figsize=(4.8, 4.8))
|
|
79
|
+
colors = ['red', 'green', 'blue']
|
|
80
|
+
for i in range(p.shape[0]):
|
|
81
|
+
color = colors[np.argmax(p[i])]
|
|
82
|
+
plt.arrow(p[i][1], p[i][2],
|
|
83
|
+
probs_scaled[i][1]-p[i][1], probs_scaled[i][2]-p[i][2],
|
|
84
|
+
color=color, head_width=0.01, length_includes_head=True)
|
|
85
|
+
|
|
86
|
+
plt.plot([0, 1], [0, 0], 'k-')
|
|
87
|
+
plt.plot([1, 0], [0, 1], 'k-')
|
|
88
|
+
plt.plot([0, 0], [1, 0], 'k-')
|
|
89
|
+
plt.xlabel("Acceptor Probability")
|
|
90
|
+
plt.ylabel("Donor Probability")
|
|
91
|
+
plt.title("Calibration Map")
|
|
92
|
+
plt.legend(handles=[
|
|
93
|
+
plt.Line2D([0], [0], color='red', label='Non-splice'),
|
|
94
|
+
plt.Line2D([0], [0], color='green', label='Acceptor'),
|
|
95
|
+
plt.Line2D([0], [0], color='blue', label='Donor')
|
|
96
|
+
])
|
|
97
|
+
plt.tight_layout()
|
|
98
|
+
plt.savefig(f"{output_dir}/calibration/calibration_map.png", dpi=300)
|
|
99
|
+
plt.close()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
CL_max=10000
|
|
2
|
+
# Maximum nucleotide context length (CL_max/2 on either side of the
|
|
3
|
+
# position of interest)
|
|
4
|
+
# CL_max should be an even number
|
|
5
|
+
|
|
6
|
+
SL=5000
|
|
7
|
+
# Sequence length of SpliceAIs (SL+CL will be the input length and
|
|
8
|
+
# SL will be the output length)
|
|
9
|
+
#############################
|
|
10
|
+
# Global variable definition
|
|
11
|
+
##############################
|
|
12
|
+
EPOCH_NUM = 10
|
|
13
|
+
|
|
14
|
+
|
|
File without changes
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from Bio.Seq import Seq # Import the Seq class
|
|
3
|
+
from Bio import SeqIO, SeqRecord
|
|
4
|
+
import numpy as np
|
|
5
|
+
import h5py
|
|
6
|
+
import time
|
|
7
|
+
import openspliceai.create_data.utils as utils
|
|
8
|
+
import openspliceai.create_data.paralogs as paralogs
|
|
9
|
+
|
|
10
|
+
donor_motif_counts = {} # Initialize counts
|
|
11
|
+
acceptor_motif_counts = {} # Initialize counts
|
|
12
|
+
|
|
13
|
+
def get_sequences_and_labels(db, output_dir, seq_dict, chrom_dict, train_or_test, parse_type="canonical", biotype="protein-coding", canonical_only=True, write_fasta=False):
|
|
14
|
+
"""
|
|
15
|
+
Extract sequences for each protein-coding gene, reverse complement sequences for genes on the reverse strand,
|
|
16
|
+
and label donor and acceptor sites correctly based on strand orientation.
|
|
17
|
+
"""
|
|
18
|
+
fw_stats = open(f"{output_dir}{train_or_test}_stats.txt", "w")
|
|
19
|
+
if write_fasta:
|
|
20
|
+
fasta_handle = open(f"{output_dir}{train_or_test}.fa", "w") # Open a file to write FASTA format sequences
|
|
21
|
+
NAME = [] # Gene Name
|
|
22
|
+
CHROM = [] # Chromosome
|
|
23
|
+
STRAND = [] # Strand in which the gene lies (+ or -)
|
|
24
|
+
TX_START = [] # Position where transcription starts
|
|
25
|
+
TX_END = [] # Position where transcription ends
|
|
26
|
+
SEQ = [] # Nucleotide sequence
|
|
27
|
+
LABEL = [] # Label for each nucleotide in the sequence
|
|
28
|
+
GENE_COUNTER = 0
|
|
29
|
+
for gene in db.features_of_type('gene'):
|
|
30
|
+
if "exception" in gene.attributes.keys() and gene.attributes["exception"][0] == "trans-splicing":
|
|
31
|
+
continue
|
|
32
|
+
if gene.seqid not in chrom_dict:
|
|
33
|
+
continue
|
|
34
|
+
if biotype =="protein-coding":
|
|
35
|
+
if gene.attributes["gene_biotype"][0] != "protein_coding":
|
|
36
|
+
continue
|
|
37
|
+
elif biotype =="non-coding":
|
|
38
|
+
if gene.attributes["gene_biotype"][0] != "lncRNA" and gene.attributes["gene_biotype"][0] != "ncRNA":
|
|
39
|
+
continue
|
|
40
|
+
else:
|
|
41
|
+
continue
|
|
42
|
+
chrom_dict[gene.seqid] += 1
|
|
43
|
+
gene_id = gene.id
|
|
44
|
+
|
|
45
|
+
# Process the gene sequence
|
|
46
|
+
gene_seq = seq_dict[gene.seqid].seq[gene.start-1:gene.end].upper() # Extract gene sequence
|
|
47
|
+
if gene.strand == '-':
|
|
48
|
+
gene_seq = gene_seq.reverse_complement() # reverse complement the sequence
|
|
49
|
+
gene_seq = str(gene_seq.upper())
|
|
50
|
+
print(f"\tProcessing gene {gene_id} on chromosome {gene.seqid}..., len(gene_seq): {len(gene_seq)}")
|
|
51
|
+
labels = [0] * len(gene_seq) # Initialize all labels to 0
|
|
52
|
+
if biotype =="protein-coding":
|
|
53
|
+
transcripts = list(db.children(gene, featuretype='mRNA', order_by='start'))
|
|
54
|
+
elif biotype =="non-coding":
|
|
55
|
+
transcripts = list(db.children(gene, level=1, order_by='start'))
|
|
56
|
+
if len(transcripts) == 0:
|
|
57
|
+
continue
|
|
58
|
+
elif len(transcripts) > 1:
|
|
59
|
+
print(f"\tGene {gene_id} has multiple transcripts: {len(transcripts)}")
|
|
60
|
+
|
|
61
|
+
# Selecting which mode to process the data
|
|
62
|
+
transcripts_ls = []
|
|
63
|
+
if parse_type == 'canonical':
|
|
64
|
+
max_trans = transcripts[0]
|
|
65
|
+
max_len = max_trans.end - max_trans.start + 1
|
|
66
|
+
for transcript in transcripts:
|
|
67
|
+
if transcript.end - transcript.start + 1 > max_len:
|
|
68
|
+
max_trans = transcript
|
|
69
|
+
max_len = transcript.end - transcript.start + 1
|
|
70
|
+
transcripts_ls = [max_trans]
|
|
71
|
+
elif parse_type == 'all_isoforms':
|
|
72
|
+
transcripts_ls = transcripts
|
|
73
|
+
|
|
74
|
+
# Process transcripts
|
|
75
|
+
for transcript in transcripts_ls:
|
|
76
|
+
exons = list(db.children(transcript, featuretype='exon', order_by='start'))
|
|
77
|
+
if len(exons) > 1:
|
|
78
|
+
GENE_COUNTER += 1
|
|
79
|
+
for i in range(len(exons) - 1):
|
|
80
|
+
# Donor site is one base after the end of the current exon
|
|
81
|
+
first_site = exons[i].end - gene.start # Adjusted for python indexing
|
|
82
|
+
# Acceptor site is at the start of the next exon
|
|
83
|
+
second_site = exons[i + 1].start - gene.start
|
|
84
|
+
# Adjusted for python indexing
|
|
85
|
+
if gene.strand == '+':
|
|
86
|
+
d_idx = first_site
|
|
87
|
+
a_idx = second_site
|
|
88
|
+
elif gene.strand == '-':
|
|
89
|
+
d_idx = len(labels) - second_site-1
|
|
90
|
+
a_idx = len(labels) - first_site-1
|
|
91
|
+
# Check if the donor / acceptor sites are valid
|
|
92
|
+
d_motif = str(gene_seq[d_idx+1:d_idx+3])
|
|
93
|
+
a_motif = str(gene_seq[a_idx-2:a_idx])
|
|
94
|
+
if not canonical_only:
|
|
95
|
+
labels[d_idx] = 2 # Mark donor site
|
|
96
|
+
labels[a_idx] = 1 # Mark acceptor site
|
|
97
|
+
elif (d_motif == "GT" and a_motif == "AG") or (d_motif == "GC" and a_motif == "AG") or (d_motif == "AT" and a_motif == "AC"):
|
|
98
|
+
labels[d_idx] = 2 # Mark donor site
|
|
99
|
+
labels[a_idx] = 1 # Mark acceptor site
|
|
100
|
+
labels_str = ''.join(str(num) for num in labels)
|
|
101
|
+
NAME.append(gene_id)
|
|
102
|
+
CHROM.append(gene.seqid)
|
|
103
|
+
STRAND.append(gene.strand)
|
|
104
|
+
TX_START.append(str(gene.start))
|
|
105
|
+
TX_END.append(str(gene.end))
|
|
106
|
+
SEQ.append(gene_seq)
|
|
107
|
+
LABEL.append(labels_str)
|
|
108
|
+
|
|
109
|
+
# Write to the FASTA file if the path is provided
|
|
110
|
+
if write_fasta:
|
|
111
|
+
record = SeqRecord.SeqRecord(
|
|
112
|
+
Seq(gene_seq),
|
|
113
|
+
id=gene_id,
|
|
114
|
+
description=f"{gene.seqid}:{gene.start}-{gene.end}({gene.strand})"
|
|
115
|
+
)
|
|
116
|
+
SeqIO.write(record, fasta_handle, "fasta")
|
|
117
|
+
|
|
118
|
+
fw_stats.write(f"{gene.seqid}\t{gene.start}\t{gene.end}\t{gene.id}\t{1}\t{gene.strand}\n")
|
|
119
|
+
utils.check_and_count_motifs(gene_seq, labels, donor_motif_counts, acceptor_motif_counts)
|
|
120
|
+
print(f"Total SEQ: {len(SEQ)}")
|
|
121
|
+
fw_stats.close()
|
|
122
|
+
if write_fasta:
|
|
123
|
+
fasta_handle.close() # Close the FASTA file handle
|
|
124
|
+
return [NAME, CHROM, STRAND, TX_START, TX_END, SEQ, LABEL]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def create_datafile(args):
|
|
128
|
+
print("--- Step 1: Creating datafile.h5 ... ---")
|
|
129
|
+
start_time = time.process_time()
|
|
130
|
+
|
|
131
|
+
# Use gffutils to parse annotation file
|
|
132
|
+
os.makedirs(args.output_dir, exist_ok=True)
|
|
133
|
+
db = utils.create_or_load_db(args.annotation_gff, db_file=f'{args.annotation_gff}_db')
|
|
134
|
+
seq_dict = SeqIO.to_dict(SeqIO.parse(args.genome_fasta, "fasta"))
|
|
135
|
+
|
|
136
|
+
# Find all distinct chromosomes and split them
|
|
137
|
+
TRAIN_CHROM_GROUP, TEST_CHROM_GROUP = utils.split_chromosomes(db, method=args.split_method, split_ratio=args.split_ratio)
|
|
138
|
+
print("* TRAIN_CHROM_GROUP: ", TRAIN_CHROM_GROUP)
|
|
139
|
+
print("* TEST_CHROM_GROUP: ", TEST_CHROM_GROUP)
|
|
140
|
+
|
|
141
|
+
# Collect sequences and labels for testing and/or training groups
|
|
142
|
+
if args.chr_split == 'test':
|
|
143
|
+
print("> Creating test datafile...")
|
|
144
|
+
test_data = get_sequences_and_labels(db, args.output_dir, seq_dict, TEST_CHROM_GROUP, 'test', parse_type=args.parse_type, biotype=args.biotype, canonical_only=args.canonical_only, write_fasta=args.write_fasta)
|
|
145
|
+
paralogs.write_h5_file(args.output_dir, "test", test_data)
|
|
146
|
+
elif args.chr_split == 'train-test':
|
|
147
|
+
print("> Creating train datafile...")
|
|
148
|
+
train_data = get_sequences_and_labels(db, args.output_dir, seq_dict, TRAIN_CHROM_GROUP, 'train', parse_type=args.parse_type, biotype=args.biotype, canonical_only=args.canonical_only, write_fasta=args.write_fasta)
|
|
149
|
+
print("> Creating test datafile...")
|
|
150
|
+
test_data = get_sequences_and_labels(db, args.output_dir, seq_dict, TEST_CHROM_GROUP, 'test', parse_type=args.parse_type, biotype=args.biotype, canonical_only=args.canonical_only, write_fasta=args.write_fasta)
|
|
151
|
+
if args.remove_paralogs:
|
|
152
|
+
# Remove homologous sequences
|
|
153
|
+
print("> Removing homologous sequences...")
|
|
154
|
+
train_data, test_data = paralogs.remove_paralogous_sequences(train_data, test_data, args.min_identity, args.min_coverage, args.output_dir)
|
|
155
|
+
# Write the filtered data to h5 files
|
|
156
|
+
paralogs.write_h5_file(args.output_dir, "train", train_data)
|
|
157
|
+
paralogs.write_h5_file(args.output_dir, "test", test_data)
|
|
158
|
+
utils.print_motif_counts(donor_motif_counts, acceptor_motif_counts)
|
|
159
|
+
print("--- %s seconds ---" % (time.process_time() - start_time))
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import h5py
|
|
2
|
+
import numpy as np
|
|
3
|
+
from tqdm import tqdm
|
|
4
|
+
import time
|
|
5
|
+
from openspliceai.constants import *
|
|
6
|
+
from openspliceai.create_data.utils import ceil_div, replace_non_acgt_to_n, create_datapoints
|
|
7
|
+
import argparse
|
|
8
|
+
|
|
9
|
+
CHUNK_SIZE = 100 # size of chunks to process data in
|
|
10
|
+
|
|
11
|
+
def create_dataset(args):
|
|
12
|
+
print("--- Step 2: Creating dataset.h5 ... ---")
|
|
13
|
+
start_time = time.process_time()
|
|
14
|
+
|
|
15
|
+
dataset_ls = []
|
|
16
|
+
if args.chr_split == 'test':
|
|
17
|
+
dataset_ls.append('test')
|
|
18
|
+
elif args.chr_split == 'train-test':
|
|
19
|
+
dataset_ls.append('test')
|
|
20
|
+
dataset_ls.append('train')
|
|
21
|
+
for dataset_type in dataset_ls:
|
|
22
|
+
print(("\tProcessing %s ..." % dataset_type))
|
|
23
|
+
if args.biotype =="non-coding":
|
|
24
|
+
input_file = f"{args.output_dir}/datafile_{dataset_type}_ncRNA.h5"
|
|
25
|
+
output_file = f"{args.output_dir}/dataset_{dataset_type}_ncRNA.h5"
|
|
26
|
+
elif args.biotype =="protein-coding":
|
|
27
|
+
input_file = f"{args.output_dir}/datafile_{dataset_type}.h5"
|
|
28
|
+
output_file = f"{args.output_dir}/dataset_{dataset_type}.h5"
|
|
29
|
+
|
|
30
|
+
print(f"\tReading {input_file} ... ")
|
|
31
|
+
with h5py.File(input_file, 'r') as h5f:
|
|
32
|
+
SEQ = h5f['SEQ'][:]
|
|
33
|
+
LABEL = h5f['LABEL'][:]
|
|
34
|
+
STRAND = h5f['STRAND'][:]
|
|
35
|
+
TX_START = h5f['TX_START'][:]
|
|
36
|
+
TX_END = h5f['TX_END'][:]
|
|
37
|
+
|
|
38
|
+
print(f"\tWriting {output_file} ... ")
|
|
39
|
+
with h5py.File(output_file, 'w') as h5f2:
|
|
40
|
+
seq_num = len(SEQ)
|
|
41
|
+
# create dataset
|
|
42
|
+
num_chunks = ceil_div(seq_num, CHUNK_SIZE)
|
|
43
|
+
for i in tqdm(range(num_chunks), desc='Processing chunks...'):
|
|
44
|
+
# each dataset has CHUNK_SIZE genes
|
|
45
|
+
if i == num_chunks - 1: # if last chunk, process remainder or full chunk size if no remainder
|
|
46
|
+
NEW_CHUNK_SIZE = seq_num % CHUNK_SIZE or CHUNK_SIZE
|
|
47
|
+
else:
|
|
48
|
+
NEW_CHUNK_SIZE = CHUNK_SIZE
|
|
49
|
+
X_batch, Y_batch = [], [[] for _ in range(1)]
|
|
50
|
+
for j in range(NEW_CHUNK_SIZE):
|
|
51
|
+
idx = i*CHUNK_SIZE + j
|
|
52
|
+
seq_decode = SEQ[idx].decode('ascii')
|
|
53
|
+
label_decode = LABEL[idx].decode('ascii')
|
|
54
|
+
fixed_seq = replace_non_acgt_to_n(seq_decode)
|
|
55
|
+
X, Y = create_datapoints(fixed_seq, label_decode)
|
|
56
|
+
X_batch.extend(X)
|
|
57
|
+
Y_batch[0].extend(Y[0])
|
|
58
|
+
# Convert batches to arrays and save as HDF5
|
|
59
|
+
X_batch = np.asarray(X_batch).astype('int8')
|
|
60
|
+
Y_batch[0] = np.asarray(Y_batch[0]).astype('int8')
|
|
61
|
+
|
|
62
|
+
h5f2.create_dataset('X' + str(i), data=X_batch)
|
|
63
|
+
h5f2.create_dataset('Y' + str(i), data=Y_batch)
|
|
64
|
+
print("--- %s seconds ---" % (time.process_time() - start_time))
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import mappy as mp
|
|
2
|
+
import numpy as np
|
|
3
|
+
import logging
|
|
4
|
+
from Bio import SeqIO
|
|
5
|
+
import h5py
|
|
6
|
+
import tempfile
|
|
7
|
+
import os
|
|
8
|
+
|
|
9
|
+
def remove_paralogous_sequences(train_data, test_data, min_identity, min_coverage, output_dir):
|
|
10
|
+
"""
|
|
11
|
+
Remove paralogous sequences between train and test datasets using mappy.
|
|
12
|
+
|
|
13
|
+
:param train_data: List of lists containing train data (NAME, CHROM, STRAND, TX_START, TX_END, SEQ, LABEL)
|
|
14
|
+
:param test_data: List of lists containing test data (NAME, CHROM, STRAND, TX_START, TX_END, SEQ, LABEL)
|
|
15
|
+
:param min_identity: Minimum identity for sequences to be considered paralogous
|
|
16
|
+
:param min_coverage: Minimum coverage for sequences to be considered paralogous
|
|
17
|
+
:return: Tuple of (filtered_train_data, filtered_test_data)
|
|
18
|
+
"""
|
|
19
|
+
print(f"Starting paralogy removal process...")
|
|
20
|
+
print(f"Initial train set size: {len(train_data[0])}")
|
|
21
|
+
print(f"Initial test set size: {len(test_data[0])}")
|
|
22
|
+
train_seqs = train_data[5] # SEQ is at index 5
|
|
23
|
+
# Create a temporary file with training sequences
|
|
24
|
+
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
|
|
25
|
+
for i, seq in enumerate(train_seqs):
|
|
26
|
+
temp_file.write(f">seq{i}\n{seq}\n")
|
|
27
|
+
temp_filename = temp_file.name
|
|
28
|
+
# Create a mappy index from the training sequences
|
|
29
|
+
print("Creating mappy index from training sequences...")
|
|
30
|
+
try:
|
|
31
|
+
aligner = mp.Aligner(temp_filename, preset="map-ont")
|
|
32
|
+
if not aligner:
|
|
33
|
+
raise Exception("Failed to load/build index")
|
|
34
|
+
except Exception as e:
|
|
35
|
+
logging.error(f"Error creating mappy aligner: {str(e)}")
|
|
36
|
+
os.unlink(temp_filename)
|
|
37
|
+
return train_data, test_data
|
|
38
|
+
filtered_test_data = [[] for _ in range(len(test_data))]
|
|
39
|
+
paralogous_count = 0
|
|
40
|
+
total_count = len(test_data[5])
|
|
41
|
+
fw = open(f"{output_dir}removed_paralogs.txt", "w")
|
|
42
|
+
print("Starting to process test sequences...")
|
|
43
|
+
for i in range(total_count): # Iterate over test sequences
|
|
44
|
+
test_seq = test_data[5][i]
|
|
45
|
+
is_paralogous = False
|
|
46
|
+
for hit in aligner.map(test_seq):
|
|
47
|
+
identity = hit.mlen / hit.blen
|
|
48
|
+
coverage = hit.blen / len(test_seq)
|
|
49
|
+
fw.write(f"{test_data[0][i]}\t{identity}\t{coverage}\n")
|
|
50
|
+
if identity >= min_identity and coverage >= min_coverage:
|
|
51
|
+
# fw.write(f"{test_data[0][i]}\t{identity}\t{coverage}\n")
|
|
52
|
+
print(f"\tParalogs detected: Identity: {identity}, Coverage: {coverage}")
|
|
53
|
+
is_paralogous = True
|
|
54
|
+
paralogous_count += 1
|
|
55
|
+
break
|
|
56
|
+
if not is_paralogous:
|
|
57
|
+
for j in range(len(test_data)):
|
|
58
|
+
filtered_test_data[j].append(test_data[j][i])
|
|
59
|
+
# Log progress every 1000 sequences
|
|
60
|
+
if (i + 1) % 1000 == 0:
|
|
61
|
+
print(f"Processed {i + 1}/{total_count} sequences...")
|
|
62
|
+
print(f"Paralogy removal process completed.")
|
|
63
|
+
print(f"Number of paralogous sequences removed: {paralogous_count}")
|
|
64
|
+
print(f"Final test set size: {len(filtered_test_data[0])}")
|
|
65
|
+
print(f"Percentage of test set removed: {(paralogous_count / total_count) * 100:.2f}%")
|
|
66
|
+
fw.close()
|
|
67
|
+
return train_data, filtered_test_data
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def write_h5_file(output_dir, data_type, data):
|
|
71
|
+
"""
|
|
72
|
+
Write the data to an h5 file.
|
|
73
|
+
"""
|
|
74
|
+
h5fname = output_dir + f'datafile_{data_type}.h5'
|
|
75
|
+
h5f = h5py.File(h5fname, 'w')
|
|
76
|
+
dt = h5py.string_dtype(encoding='utf-8')
|
|
77
|
+
|
|
78
|
+
dataset_names = ['NAME', 'CHROM', 'STRAND', 'TX_START', 'TX_END', 'SEQ', 'LABEL']
|
|
79
|
+
for i, name in enumerate(dataset_names):
|
|
80
|
+
h5f.create_dataset(name, data=np.asarray(data[i], dtype=dt), dtype=dt)
|
|
81
|
+
h5f.close()
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
###############################################################################
|
|
2
|
+
'''The file includes functions to process sequences to/from .h5 datasets.'''
|
|
3
|
+
###############################################################################
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import numpy as np
|
|
7
|
+
import torch
|
|
8
|
+
from math import ceil
|
|
9
|
+
import gffutils
|
|
10
|
+
import random
|
|
11
|
+
from sklearn.metrics import average_precision_score
|
|
12
|
+
from openspliceai.constants import *
|
|
13
|
+
|
|
14
|
+
def check_and_count_motifs(seq, labels, donor_motif_counts, acceptor_motif_counts):
|
|
15
|
+
"""
|
|
16
|
+
Check sequences for donor and acceptor motifs and count their occurrences.
|
|
17
|
+
|
|
18
|
+
Parameters:
|
|
19
|
+
- seq: The DNA sequence (str).
|
|
20
|
+
- labels: Array of labels indicating locations of interest in the sequence.
|
|
21
|
+
"""
|
|
22
|
+
for i, label in enumerate(labels):
|
|
23
|
+
if label == 2: # Donor site
|
|
24
|
+
d_motif = str(seq[i+1:i+3])
|
|
25
|
+
donor_motif_counts[d_motif] = donor_motif_counts.get(d_motif, 0) + 1
|
|
26
|
+
elif label == 1: # Acceptor site
|
|
27
|
+
a_motif = str(seq[i-2:i])
|
|
28
|
+
acceptor_motif_counts[a_motif] = acceptor_motif_counts.get(a_motif, 0) + 1
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def print_motif_counts(donor_motif_counts, acceptor_motif_counts):
|
|
32
|
+
"""
|
|
33
|
+
Print the counts of donor and acceptor motifs.
|
|
34
|
+
"""
|
|
35
|
+
print("*******************")
|
|
36
|
+
print("Splice site motif counts:")
|
|
37
|
+
print("\tDonor motifs:")
|
|
38
|
+
for motif, count in donor_motif_counts.items():
|
|
39
|
+
print(f"\t{motif}: {count}")
|
|
40
|
+
print("\n\tAcceptor motifs:")
|
|
41
|
+
for motif, count in acceptor_motif_counts.items():
|
|
42
|
+
print(f"\t{motif}: {count}")
|
|
43
|
+
print("\nTotal donor motifs: ", sum(donor_motif_counts.values()))
|
|
44
|
+
print("Total acceptor motifs: ", sum(acceptor_motif_counts.values()))
|
|
45
|
+
print("*******************")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
###################################################
|
|
49
|
+
# create_datafile.py functions
|
|
50
|
+
###################################################
|
|
51
|
+
def get_chromosome_lengths(db):
|
|
52
|
+
"""Extract all unique chromosomes and their lengths from the GFF database."""
|
|
53
|
+
chromosomes = {}
|
|
54
|
+
for feature in db.all_features():
|
|
55
|
+
if feature.seqid not in chromosomes:
|
|
56
|
+
chromosomes[feature.seqid] = feature.end
|
|
57
|
+
else:
|
|
58
|
+
chromosomes[feature.seqid] = max(chromosomes[feature.seqid], feature.end)
|
|
59
|
+
return chromosomes
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def split_chromosomes(db, method='random', split_ratio=0.8):
|
|
63
|
+
chromosome_lengths = get_chromosome_lengths(db)
|
|
64
|
+
"""Split chromosomes into training and testing groups."""
|
|
65
|
+
if method == 'random':
|
|
66
|
+
total_length = sum(chromosome_lengths.values())
|
|
67
|
+
target_train_length = total_length * split_ratio
|
|
68
|
+
target_test_length = total_length * (1-split_ratio)
|
|
69
|
+
chromosomes = list(chromosome_lengths.keys())
|
|
70
|
+
random.shuffle(chromosomes)
|
|
71
|
+
train_chroms = {}
|
|
72
|
+
test_chroms = {}
|
|
73
|
+
current_train_length = 0
|
|
74
|
+
current_test_length = 0
|
|
75
|
+
|
|
76
|
+
for chrom in chromosomes:
|
|
77
|
+
if current_test_length < target_test_length:
|
|
78
|
+
test_chroms[chrom] = chromosome_lengths[chrom]
|
|
79
|
+
current_test_length += chromosome_lengths[chrom]
|
|
80
|
+
else:
|
|
81
|
+
train_chroms[chrom] = chromosome_lengths[chrom]
|
|
82
|
+
current_train_length += chromosome_lengths[chrom]
|
|
83
|
+
elif method == 'human':
|
|
84
|
+
# following SpliceAI default splitting for human chromosomes
|
|
85
|
+
train_chroms = {
|
|
86
|
+
'chr2': 0, 'chr4': 0, 'chr6': 0, 'chr8': 0,
|
|
87
|
+
'chr10': 0, 'chr11': 0, 'chr12': 0, 'chr13': 0,
|
|
88
|
+
'chr14': 0, 'chr15': 0, 'chr16': 0, 'chr17': 0,
|
|
89
|
+
'chr18': 0, 'chr19': 0, 'chr20': 0, 'chr21': 0,
|
|
90
|
+
'chr22': 0, 'chrX': 0, 'chrY': 0
|
|
91
|
+
}
|
|
92
|
+
test_chroms = {
|
|
93
|
+
'chr1': 0, 'chr3': 0, 'chr5': 0, 'chr7': 0, 'chr9': 0
|
|
94
|
+
}
|
|
95
|
+
else:
|
|
96
|
+
raise ValueError("Invalid chromosome split method. Use 'random' or 'human'.")
|
|
97
|
+
return train_chroms, test_chroms
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def create_or_load_db(gff_file, db_file='gff.db'):
|
|
101
|
+
"""
|
|
102
|
+
Create a gffutils database from a GFF file, or load it if it already exists.
|
|
103
|
+
|
|
104
|
+
Parameters:
|
|
105
|
+
- gff_file: Path to GFF file
|
|
106
|
+
- db_file: Path to save or load the database file (default: 'gff.db')
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
- db: gffutils FeatureDB object
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
if not os.path.exists(db_file):
|
|
113
|
+
print("Creating new database...")
|
|
114
|
+
db = gffutils.create_db(gff_file, dbfn=db_file, force=True, keep_order=True, merge_strategy='merge', sort_attribute_values=True)
|
|
115
|
+
else:
|
|
116
|
+
print("Loading existing database...")
|
|
117
|
+
db = gffutils.FeatureDB(db_file)
|
|
118
|
+
return db
|
|
119
|
+
|
|
120
|
+
###################################################
|
|
121
|
+
# create_dataset.py functions
|
|
122
|
+
###################################################
|
|
123
|
+
# One-hot encoding of the inputs:
|
|
124
|
+
# 1: A; 2: C; 3: G; 4: T; 0: padding
|
|
125
|
+
IN_MAP = np.asarray([[0, 0, 0, 0],
|
|
126
|
+
[1, 0, 0, 0],
|
|
127
|
+
[0, 1, 0, 0],
|
|
128
|
+
[0, 0, 1, 0],
|
|
129
|
+
[0, 0, 0, 1]])
|
|
130
|
+
|
|
131
|
+
# One-hot encoding of the outputs:
|
|
132
|
+
# 0: no splice; 1: acceptor; 2: donor; -1: padding
|
|
133
|
+
OUT_MAP = np.asarray([[1, 0, 0],
|
|
134
|
+
[0, 1, 0],
|
|
135
|
+
[0, 0, 1],
|
|
136
|
+
[0, 0, 0]])
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def ceil_div(x, y):
|
|
140
|
+
"""
|
|
141
|
+
Calculate the ceiling of a division between two numbers.
|
|
142
|
+
|
|
143
|
+
Parameters:
|
|
144
|
+
- x (int): Numerator
|
|
145
|
+
- y (int): Denominator
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
- int: The ceiling of the division result.
|
|
149
|
+
"""
|
|
150
|
+
return int(ceil(float(x)/y))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def one_hot_encode(Xd, Yd):
|
|
154
|
+
"""
|
|
155
|
+
Perform one-hot encoding on both the input sequence data (Xd) and the output label data (Yd) using
|
|
156
|
+
predefined mappings (IN_MAP for inputs and OUT_MAP for outputs).
|
|
157
|
+
|
|
158
|
+
Parameters:
|
|
159
|
+
- Xd (numpy.ndarray): An array of integers representing the input sequence data where each nucleotide
|
|
160
|
+
is encoded as an integer (1 for 'A', 2 for 'C', 3 for 'G', 4 for 'T', and 0 for padding).
|
|
161
|
+
- Yd (list of numpy.ndarray): A list containing a single array of integers representing the output label data,
|
|
162
|
+
where each label is encoded as an integer (0 for 'no splice', 1 for 'acceptor', 2 for 'donor', and -1 for padding).
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
- numpy.ndarray: the one-hot encoded input sequence data.
|
|
166
|
+
- numpy.ndarray: the one-hot encoded output label data.
|
|
167
|
+
"""
|
|
168
|
+
return IN_MAP[Xd.astype('int8')], [OUT_MAP[Yd[t].astype('int8')] for t in range(1)]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def replace_non_acgt_to_n(input_string):
|
|
172
|
+
"""
|
|
173
|
+
Use a generator expression to go through each character in the input string.
|
|
174
|
+
If the character is in the set of allowed characters, keep it as is.
|
|
175
|
+
Otherwise, replace it with 'N'.
|
|
176
|
+
|
|
177
|
+
Parameters:
|
|
178
|
+
- input_string (str): The nucleotide sequence.
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
- str: The modified sequence with non-ACGT nucleotides replaced by 'N'.
|
|
182
|
+
"""
|
|
183
|
+
# Define the set of allowed characters
|
|
184
|
+
allowed_chars = {'A', 'C', 'G', 'T'}
|
|
185
|
+
return ''.join(char if char in allowed_chars else 'N' for char in input_string)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def reformat_data(X0, Y0):
|
|
189
|
+
"""
|
|
190
|
+
Reformat sequence and label data into fixed-size blocks for processing.
|
|
191
|
+
This function converts X0, Y0 of the create_datapoints function into
|
|
192
|
+
blocks such that the data is broken down into data points where the
|
|
193
|
+
input is a sequence of length SL+CL_max corresponding to SL nucleotides
|
|
194
|
+
of interest and CL_max context nucleotides, the output is a sequence of
|
|
195
|
+
length SL corresponding to the splicing information of the nucleotides
|
|
196
|
+
of interest. The CL_max context nucleotides are such that they are
|
|
197
|
+
CL_max/2 on either side of the SL nucleotides of interest.
|
|
198
|
+
|
|
199
|
+
Parameters:
|
|
200
|
+
- X0 (numpy.ndarray): Original sequence data as an array of integer encodings.
|
|
201
|
+
- Y0 (list of numpy.ndarray): Original label data as a list containing a single array of integer encodings.
|
|
202
|
+
|
|
203
|
+
Returns:
|
|
204
|
+
- numpy.ndarray: Reformatted sequence data.
|
|
205
|
+
- list of numpy.ndarray: Reformatted label data, wrapped in a list.
|
|
206
|
+
"""
|
|
207
|
+
# Calculate the number of data points needed
|
|
208
|
+
num_points = ceil_div(len(Y0[0]), SL)
|
|
209
|
+
# Initialize arrays to hold the reformatted data
|
|
210
|
+
Xd = np.zeros((num_points, SL + CL_max))
|
|
211
|
+
Yd = [-np.ones((num_points, SL)) for _ in range(1)]
|
|
212
|
+
# Pad the sequence and labels to ensure divisibility
|
|
213
|
+
X0 = np.pad(X0, (0, SL), 'constant', constant_values=0)
|
|
214
|
+
Y0 = [np.pad(Y0[t], (0, SL), 'constant', constant_values=-1) for t in range(1)]
|
|
215
|
+
# Fill the initialized arrays with data in blocks
|
|
216
|
+
for i in range(num_points):
|
|
217
|
+
Xd[i] = X0[SL * i : SL * (i + 1) + CL_max]
|
|
218
|
+
Yd[0][i] = Y0[0][SL * i : SL * (i + 1)]
|
|
219
|
+
|
|
220
|
+
return Xd, Yd
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def create_datapoints(seq, label):
|
|
224
|
+
"""
|
|
225
|
+
This function first converts the sequence into an integer array, where
|
|
226
|
+
A, C, G, T, N are mapped to 1, 2, 3, 4, 0 respectively. If the strand is
|
|
227
|
+
negative, then reverse complementing is done. The labels
|
|
228
|
+
are directly used as they are, converted into an array of integers,
|
|
229
|
+
where 0, 1, 2 correspond to no splicing, acceptor, donor
|
|
230
|
+
respectively. It then calls reformat_data and one_hot_encode
|
|
231
|
+
and returns X, Y which can be used by Pytorch Model.
|
|
232
|
+
|
|
233
|
+
Parameters:
|
|
234
|
+
- seq (str): The nucleotide sequence.
|
|
235
|
+
- strand (str): The strand information ('+' or '-').
|
|
236
|
+
- label (str): A string representation of labels for each nucleotide.
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
- tuple: A tuple containing the one-hot encoded sequence and labels.
|
|
240
|
+
"""
|
|
241
|
+
# No need to reverse complement the sequence, as sequence is already reverse complemented from previous step
|
|
242
|
+
seq = 'N' * (CL_max // 2) + seq + 'N' * (CL_max // 2)
|
|
243
|
+
seq = seq.upper().replace('A', '1').replace('C', '2')
|
|
244
|
+
seq = seq.replace('G', '3').replace('T', '4').replace('N', '0')
|
|
245
|
+
|
|
246
|
+
# Convert label string to array of integers
|
|
247
|
+
label_array = np.array(list(map(int, list(label))))
|
|
248
|
+
X0 = np.asarray(list(map(int, list(seq))))
|
|
249
|
+
Y0 = label_array
|
|
250
|
+
Y0 = [Y0]
|
|
251
|
+
Xd, Yd = reformat_data(X0, Y0)
|
|
252
|
+
X, Y = one_hot_encode(Xd, Yd)
|
|
253
|
+
|
|
254
|
+
return X, Y
|