-
Notifications
You must be signed in to change notification settings - Fork 8
/
deeplexicon_sub.py
executable file
·1437 lines (1256 loc) · 54.9 KB
/
deeplexicon_sub.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# coding: utf-8
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
import argparse
import sys
import os
from copy import deepcopy
import re
import csv
import time
import configparser
import h5py
import traceback
import math
import numpy as np
# from PIL import Image
import pyts
from pyts.image import MarkovTransitionField, GramianAngularField, RecurrencePlot
import tensorflow as tf
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras.callbacks import ReduceLROnPlateau
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import multi_gpu_model
from keras.regularizers import l2
from keras import backend as K
from keras.models import Model
import pandas as pd
from sklearn import datasets, linear_model
from sklearn.model_selection import train_test_split
from tensorflow.python.client import device_lib
from keras.models import load_model
from pathlib import Path
from ont_fast5_api.fast5_interface import get_fast5_file
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.8
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
'''
James M. Ferguson ([email protected])
Genomic Technologies
Garvan Institute
Copyright 2019
Tansel Ersevas ([email protected])
Leszek Pryszcz ([email protected])
script description
Deeplexicon: Demultiplex barcoded ONT direct-RNA sequencing reads
----------------------------------------------------------------------------
version 0.0.0 - initial
version 0.8.0 - CPU version Done
version 0.9.0 - Fixed segment offset
version 0.9.1 - added segment and squiggle output
version 0.9.2 - separate segment output and code clean up
version 1.0.0 - initial release
version 1.1.0 - added submodules, splitting, and trining
version 1.2.0 - segmentation ~10x faster; added multiprocessing via deeplexicon_multi.py (only for multi_fast5 files)
So a cutoff of: 0.4958776 for high accuradef read_config(filename):
config = configparser.ConfigParser()
config.read(filename)
return(config)cy
and another of 0.2943664 for high recovery
TODO:
- Remove leftover libraries
- remove debug plots
- Remove redundant code
- create log files with information *****
- add citation
- create config file, for maintaining parity between training/dmuxing
- load in ^ config for dmuxing
----------------------------------------------------------------------------
MIT License
Copyright (c) 2019 James M. Ferguson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
def print_verbose(message):
'''verbose printing'''
sys.stderr.write('info: %s\n' % message)
def print_err(message):
'''error printing'''
sys.stderr.write('error: %s\n' % message)
def _get_available_devices():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos]
def _check_available_devices():
available_devices = _get_available_devices()
print_verbose(available_devices)
# Make sure requested GPUs are available or at least warn if they aren't
return(TRUE)
def read_model(model_name):
# model = load_model('saved_models/' + model_name)
model = load_model(model_name) # as a path
model.compile(loss='categorical_crossentropy',
optimizer=Adam(),
metrics=['accuracy'])
return(model)
# TODO: this is messy, don't use lame globals like this
squiggle_max = 1199
squiggle_min = 1
input_cut = 72000 #potenitall need to be configurable
image_size = 224
# num_classes = 4 #make this variable to array size/flag
window = 2000
def main():
'''
Main function
'''
VERSION = "1.2.0"
parser = MyParser(
description="DeePlexiCon - Demultiplex barcoded ONT direct-RNA sequencing reads",
epilog="Citation: enter publication here...",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
subcommand = parser.add_subparsers(help='subcommand --help for help messages', dest="command")
# main options for base level checks and version output
parser.add_argument("--version", action='version', version="Deeplexicon version: {}".format(VERSION),
help="Prints version")
parser.add_argument('-v', '--verbose', action='count', default=0,
help="Verbose output [v/vv/vvv]")
# sub-module for dmux command
dmux = subcommand.add_parser('dmux', help='demultiplex dRNA reads',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# dmux sub-module options
dmux.add_argument("-p", "--path", nargs='+',
help="Top path(s) of fast5 files to dmux")
dmux.add_argument("-f", "--form", default="multi", choices=["multi", "single"],
help="Multi or single fast5s")
dmux.add_argument("-s", "--threshold", type=float, default=0.50,
help="probability threshold - 0.5 hi accuracy / 0.3 hi recovery")
dmux.add_argument("-m", "--model",
help="Trained model name to use")
dmux.add_argument('-N', '--Number', type=int, default=4,
help="Number of barcodes to dmux. controls header for custom models")
dmux.add_argument("-g", "--gpu", action="store_true",
help="Use GPU if available - experimental")
dmux.add_argument("--squiggle", default=False,
help="dump squiggle data into this .tsv file")
dmux.add_argument("--segment", default=False,
help="dump segment data into this .tsv file")
dmux.add_argument("-b", "--batch_size", type=int, default=1000,
help="batch size - for single fast5s")
dmux.add_argument('-t', '--test', type=int,
help="test with -t number of reads")
dmux.add_argument('-v', '--verbose', action='count', default=0,
help="Verbose output [v/vv/vvv]")
# sub-module for split command
split = subcommand.add_parser('split', help='split a fastq file into barcode categories',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# split sub-module options
split.add_argument("-i", "--input",
help="deeplexicon dmux output tsv file")
split.add_argument("-q", "--fastq",
help="single combined fastq file")
split.add_argument("-o", "--output",
help="output path")
split.add_argument("-s", "--sample", default="dmux_",
help="sample name to append to file names")
split.add_argument('-v', '--verbose', action='count', default=0,
help="Verbose output [v/vv/vvv]")
# sub-module for train command
train = subcommand.add_parser('train', help='train a demultiplexing model',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# train sub-module options
# take all fast5s, for each read, check train_truth and convert
# repeat for test_truth - could add in validation set too using dmux?
# data, settings, model output, tmp?,
train.add_argument('-p', '--path', nargs='+',
help="Input path(s) of all used fast5s")
train.add_argument('-t', '--train_truth', nargs='+',
help="Traiing truth set(s) in one-hot format eg: readID, 0, 0, 1, 0 for barcode 3 of 4 ")
train.add_argument('-s', '--test_truth', nargs='+',
help="Testing truth set(s) in one-hot format eg: readID, 0, 0, 1, 0 for barcode 3 of 4 ")
train.add_argument('-u', '--val_truth', nargs='+',
help="Validation truth set(s) in one-hot format eg: readID, 0, 0, 1, 0 for barcode 3 of 4 ")
train.add_argument('-N', '--Number', type=int,
help="Number of barcodes to train. Should be auto detected, but set to check")
train.add_argument('-n', '--network', default="ResNet20",
help="Network to use (see table in docs)")
train.add_argument('--net_version', type=int, default=2,
help="Network version to use (see table in docs)")
train.add_argument('-e', '--epochs', type=int, default=40,
help="epochs to run")
train.add_argument('-b', '--batch_size', type=int, default=8,
help="Controls how much data is loaded into the GPU at a time. ~8 for 4GB cards, ~16 for >8GB")
train.add_argument('-x', '--prefix', default="model",
help="prefix used to name model")
train.add_argument('-v', '--verbose', action='count', default=0,
help="Verbose output [v/vv/vvv]")
# sub-module for squig command
squig = subcommand.add_parser('squig', help='extract/segment squiggles - no dmux',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# squig sub-module options
squig.add_argument("-p", "--path", nargs='+',
help="Top path(s) of fast5 files to dmux")
squig.add_argument("-f", "--form", default="multi", choices=["multi", "single"],
help="Multi or single fast5s (multi only for squig module)")
squig.add_argument("--squiggle",
help="dump squiggle data into this .tsv file")
squig.add_argument("--segment",
help="dump segment data into this .tsv file")
squig.add_argument('-v', '--verbose', action='count', default=0,
help="Verbose output [v/vv/vvv]")
# collect args
args = parser.parse_args()
# print help if no arguments given
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
if args.verbose > 0:
print_verbose("Verbose mode active - dumping info to stderr")
print_verbose("DeePlexiCon: {}".format(VERSION))
print_verbose("arg list: {}".format(args))
if tf.test.gpu_device_name():
print_verbose("GPU detected!!!")
print_verbose("Default GPU Device: {}".format(tf.test.gpu_device_name()))
else:
print_verbose("Please install GPU version of TF:")
print_verbose("> pip3 uninstall tensorflow")
print_verbose("> pip3 install tensorflow-gpu=1.13.1")
# Ensure non-command use is exited before this point
# Perfect time to do arg checks before pipeline calls
if args.command == "dmux":
if args.gpu:
if tf.test.gpu_device_name():
print_verbose("GPU detected!!!")
print_verbose("Default GPU Device: {}".format(tf.test.gpu_device_name()))
else:
print_verbose("GPU not detected, please ensure Drivers/CUDA/cuDNN/tf-gpu are set up properly")
print_verbose("Continuing with CPU")
args.gpu = False
dmux_pipeline(args)
elif args.command == "split":
split_pipeline(args)
elif args.command == "train":
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']
gpu_list = get_available_gpus()
if len(gpu_list) < 1:
print("No GPU detected. Please ensure CUDA and cuDNN are set up")
sys.exit(1)
print("Num GPUs Available: ", len(gpu_list))
print("Only single GPU mode available, using device: {}".format(gpu_list[0]))
train_pipeline(args)
print("Training complete, models available in ./saved_models/")
elif args.command == "squig":
squig_pipeline(args)
else:
print_err("command: {} not recognised".format(args.command))
parser.print_help(sys.stderr)
sys.exit(1)
# done!
# # TODO: sub-module
# Globals
# TODO: sub-module
# if args.config:
# config = read_config(args.config) #TODO check config read error
# gpu settings
# Devices
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = config[deeplexicon][gpu_list] if args.config else args.gpu_list
# do check devices are available, else throw and error
# DMUX sub-module
# main logic
def dmux_pipeline(args):
'''
pipeline for dmuxing fast5 files
'''
# read model
if not args.model:
print_err("dmux requires a trained model file path")
sys.exit(1)
model = read_model(args.model)
# make this an optional config input for custom barcode sets
# make this dynamic
# barcode_out = {0: "bc_1",
# 1: "bc_2",
# 2: "bc_3",
# 3: "bc_4",
# None: "unknown"
# }
# if someone does more than 50 samples I will skull a beer cause that's awesome!
# left here to remind me when I have to make the update
barcode_out = {i: "bc_{}".format(i+1) for i in range(0, 50)}
barcode_out[None] = "unknown"
labels = []
images = []
fast5s = {}
stats = ""
seg_dic = {}
if args.squiggle:
squig_file = args.squiggle
with open(squig_file, 'a') as f:
f.write("{}\t{}\n".format("ReadID", "signal_pA"))
else:
squig_file = ''
# TODO: sub-module
if args.segment:
seg_file = args.segment
with open(seg_file, 'a') as f:
f.write("{}\t{}\t{}\n".format("ReadID", "start", "stop"))
else:
seg_file = ""
# make this dynamic for number of barcodes
print("{}\t{}\t{}\t{}\t{}".format("fast5", "ReadID", "Barcode", "Confidence Interval", "\t".join(["P_bc_{}".format(i) for i in range(1,args.Number+1)])))
# for file in input...
# TODO: sub-module
fnames = []
for path in args.path:
fnames += list(sorted(map(str, Path(path).rglob('*.fast5'))))
for fi, fast5_file in enumerate(fnames, 1):
# get fname
fast5 = os.path.basename(fast5_file)
sys.stderr.write("%s / %s %s\n"%(fi, len(fnames), fast5_file))
if args.form == "single":
#everthing below this, send off in batches of N=args.batch_size
# The signal extraction and segmentation can happen in the first step
# read fast5 files
# make generator to speed up real time results
readID, seg_signal = get_single_fast5_signal(fast5_file, window, squig_file, seg_file)
if not seg_signal:
print_err("Segment not found for:\t{}\t{}".format(fast5_file, readID))
continue
# convert
sig = np.array(seg_signal, dtype=float)
img = convert_to_image(sig)
labels.append(readID)
fast5s[readID] = fast5
images.append(img)
# classify
if len(labels) >= args.batch_size:
C = classify(model, labels, np.array(images), False, args.threshold)
# save to output
for readID, out, c, P in C:
prob = [round(float(i), 6) for i in P]
cm = round(float(c), 4)
if args.verbose:
print_verbose("cm is: {}".format(cm))
# make this dynamic
print("{}\t{}\t{}\t{}\t{}".format(fast5s[readID], readID, barcode_out[out], cm, "\t".join(["{:.5f}".format(prob[i]) for i in range(0,len(prob))])))
labels = []
images = []
fast5s = {}
# TODO: sub-module
elif args.form == "multi":
#everthing below this, send off in batches of N=args.batch_size
# The signal extraction and segmentation can happen in the first step
# read fast5 files
seg_signal = get_multi_fast5_signal(fast5_file, window, squig_file, seg_file, test=args.test)
sig_count = 0
for readID in seg_signal:
# convert
img = convert_to_image(np.array(seg_signal[readID], dtype=float))
labels.append(readID)
images.append(img)
fast5s[readID] = fast5
sig_count += 1
# TODO: sub-module
if len(labels) >= args.batch_size:
C = classify(model, labels, np.array(images), False, args.threshold)
# save to output
for readID, out, c, P in C:
prob = [round(float(i), 6) for i in P]
cm = round(float(c), 4)
if args.verbose:
print_verbose("cm is: {}".format(cm))
# make this dynamic
print("{}\t{}\t{}\t{}\t{}".format(fast5s[readID], readID, barcode_out[out], cm, "\t".join(["{:.5f}".format(prob[i]) for i in range(0,len(prob))])))
labels = []
images = []
fast5s = {}
elif args.verbose:
print_verbose("analysing sig_count: {}/{}".format(sig_count, len(seg_signal)))
else:
blah = 0 # clean
#finish up
# TODO: sub-module
C = classify(model, labels, np.array(images), False, args.threshold)
# save to output
for readID, out, c, P in C:
prob = [round(float(i), 6) for i in P]
cm = round(float(c), 4)
if args.verbose:
print_verbose("cm is: {}".format(cm))
# Make this dynamic
print("{}\t{}\t{}\t{}\t{}".format(fast5s[readID], readID, barcode_out[out], cm, "\t".join(["{:.5f}".format(prob[i]) for i in range(0,len(prob))])))
images = []
fast5s = {}
# final report/stats
# print stats
return
def split_pipeline(args):
'''
split fastq file using dmux file
'''
def _get_reads(filename):
'''
Build dmux dic
'''
dic = {}
bc_set = set()
head = True
with open(filename, 'rt') as f:
for l in f:
if head:
head = False
continue
l = l.strip('\n')
l = l.split('\t')
dic[l[1]] = l[2]
if l[2] not in bc_set:
bc_set.add(l[2])
return dic, bc_set
def _split_fastq(read_bcs, bc_set, fastq, output, sample):
'''
split fastq into multiple fastq
'''
dic = {}
c = 0
P = False
for i in bc_set:
file = os.path.join(output, "{}_{}.fastq".format(sample, i))
dic[i] = open(file, 'w')
with open(fastq, 'rt') as f:
for l in f:
c += 1
ln = l.strip('\n')
if c == 1:
ln = ln.split(' ')
readID = ln[0][1:]
if readID in read_bcs:
bc = read_bcs[readID]
P = True
dic[bc].write(l)
elif c < 5 and P:
dic[bc].write(l)
if c >= 4:
P = False
c = 0
for i in list(dic.keys()):
dic[i].close
return
# run split pipeline
read_bcs, bc_set = _get_reads(args.input)
_split_fastq(read_bcs, bc_set, args.fastq, args.output, args.sample)
return
# file handling and segmentation
def get_single_fast5_signal(read_filename, w, squig_file, seg_file):
'''
open sigle fast5 file and extract information
'''
# get readID and signal
f5_dic = read_single_fast5(read_filename)
if not f5_dic:
print_err("Signal not extracted from: {}".format(read_filename))
return 0, 0
# segment on raw
readID = f5_dic['readID']
signal = f5_dic['signal']
seg = dRNA_segmenter(readID, signal, w)
if not seg:
print_verbose("No segment found - skipping: {}".format(readID))
return 0, 0
# convert to pA
##this is slooow & useless since gasf will norm the values anyway
pA_signal = signal #convert_to_pA(f5_dic)
if squig_file:
with open(squig_file, 'a') as f:
f.write("{}\t{}\n".format(readID, "\t".join(pA_signal)))
if seg_file:
with open(seg_file, 'a') as f:
f.write("{}\t{}\t{}\n".format(readID, seg[0], seg[1]))
# return signal/signals
return readID, pA_signal[seg[0]:seg[1]]
def get_multi_fast5_signal(read_filename, w, squig_file, seg_file, train=False, test=False):
'''
open multi fast5 files and extract information
'''
test_state = False
if test:
test_state = True
pA_signals = {}
seg_dic = {}
seg = 0
sig_count = 0
for sig_count, read in enumerate(read_multi_fast5(read_filename, reads=train), 1):
if test_state:
if sig_count > test:
continue
if not sig_count%10: sys.stderr.write(" %s \r"%sig_count)
# get readID and signal
readID = read['readID']
signal = read['signal']
# segment on raw
seg = dRNA_segmenter(readID, signal, w)
if not seg:
seg = 0
continue
# convert to pA
##this is slooow & useless since gasf will norm the values anyway
pA_signal = signal #convert_to_pA(read)
if squig_file:
with open(squig_file, 'a') as f:
f.write("{}\t{}\n".format(readID, "\t".join(pA_signal)))
if seg_file:
with open(seg_file, 'a') as f:
f.write("{}\t{}\t{}\n".format(readID, seg[0], seg[1]))
pA_signals[readID] = pA_signal[seg[0]:seg[1]]
seg_dic[readID] = seg
# return signal/signals
return pA_signals
def read_single_fast5(filename):
'''
read single fast5 file and return data
'''
f5_dic = {'signal': [], 'readID': '', 'digitisation': 0.0,
'offset': 0.0, 'range': 0.0, 'sampling_rate': 0.0}
# open fast5 file
try:
hdf = h5py.File(filename, 'r')
except:
traceback.print_exc()
print_err("extract_fast5():fast5 file failed to open: {}".format(filename))
f5_dic = {}
return f5_dic
try:
c = list(hdf['Raw/Reads'].keys())
# for col in hdf['Raw/Reads/'][c[0]]['Signal'][()]:
# f5_dic['signal'].append(int(col))
f5_dic['signal'] = hdf['Raw/Reads/'][c[0]]['Signal']#[()] # much faster
f5_dic['readID'] = hdf['Raw/Reads/'][c[0]].attrs['read_id'].decode()
f5_dic['digitisation'] = hdf['UniqueGlobalKey/channel_id'].attrs['digitisation']
f5_dic['offset'] = hdf['UniqueGlobalKey/channel_id'].attrs['offset']
f5_dic['range'] = float("{0:.2f}".format(hdf['UniqueGlobalKey/channel_id'].attrs['range']))
f5_dic['sampling_rate'] = hdf['UniqueGlobalKey/channel_id'].attrs['sampling_rate']
except:
traceback.print_exc()
print_err("extract_fast5():failed to extract events or fastq from: {}".format(filename))
f5_dic = {}
return f5_dic
def read_multi_fast5(filename, reads=False):
'''read multifast5 file efficiently and return data'''
with h5py.File(filename, 'r') as hdf:
for readid in hdf:
try:
r = hdf[readid]
if reads and readid not in reads: continue
read = {'signal': r['Raw/Signal'],
'readID': readid,
'digitisation': r['channel_id'].attrs['digitisation'],
'offset': r['channel_id'].attrs['offset'],
'range': float("{0:.2f}".format(r['channel_id'].attrs['range'])),
'sampling_rate': r['channel_id'].attrs['sampling_rate'],
}
yield read
except:
traceback.print_exc()
print_err("extract_fast5():failed to read readID: {}".format(readid))
def read_multi_fast5(filename, reads=False, scale=False):
'''read multifast5 file efficiently and return data'''
with get_fast5_file(filename, mode="r") as f5:
for r in f5.get_reads():
readid = r.read_id
try:
if reads and readid not in reads: continue
channel_info = r.get_channel_info()
read = {'signal': r.get_raw_data(scale=scale),
'readID': readid,
'digitisation': channel_info['digitisation'],
'offset': channel_info['offset'],
'range': round(channel_info['range'], 2),
'sampling_rate': channel_info['sampling_rate'],
}
yield read
except:
traceback.print_exc()
print_err("extract_fast5():failed to read readID: {}".format(readid))
def dRNA_segmenter(readID, signal, w):
'''
segment signal/s and return coords of cuts
'''
def _scale_outliers(squig):
''' Scale outliers to within m stdevs of median '''
k = (squig > 0) & (squig < 1200)
return squig[k]
sig = _scale_outliers(np.array(signal, dtype=int))
s = pd.Series(sig)
t = s.rolling(window=w).mean()
# This should be done better, or changed to median and benchmarked
# Currently trained on mean segmented data
# Make it an argument for user to choose in training/dmux and config
mn = t.mean()
std = t.std()
# Trained on 0.5
bot = mn - (std*0.5)
# main algo
# TODO: add config for these for users to fiddle with
begin = False
# max distance for merging 2 segs
seg_dist = 1500
# max length of a seg
hi_thresh = 200000
# min length of a seg
lo_thresh = 2000
start = 0
end = 0
segs = []
count = -1
for i in t:
count += 1
if i < bot and not begin:
start = count
begin = True
elif i < bot:
end = count
elif i > bot and begin:
if segs and start - segs[-1][1] < seg_dist:
segs[-1][1] = end
else:
segs.append([start, end])
start = 0
end = 0
begin = False
else:
continue
# offset = -1050
# buff = 150
# half the window - probs should be offset = w / 2
offset = -1000
buff = 0
x, y = 0, 0
for a, b in segs:
if b - a > hi_thresh:
continue
if b - a < lo_thresh:
continue
x, y = a, b
# to be modified in next major re-training
return [x+offset-buff, y+offset+buff]
break
print_verbose("dRNA_segmenter: no seg found: {}".format(readID))
return 0
def pyts_transform(transform, data, image_size, show=False, cmap='rainbow', img_index=0):
try:
t_start=time.time()
X_transform = transform.fit_transform(data)
if (show):
plt.figure(figsize=(4, 4))
plt.grid(b=None)
plt.imshow(X_transform[0], cmap=cmap, origin='lmtfower')
plt.savefig(transform.__class__.__name__ + "_image_" + str(img_index) + ".svg", format="svg")
plt.show()
return(X_transform)
except Exception as e:
print_err(str(e))
return([])
def mtf_transform(data, image_size=500, show=False, img_index=0):
transform = MarkovTransitionField(image_size)
return(pyts_transform(transform, data, image_size=image_size, show=show, cmap='rainbow', img_index=img_index))
def rp_transform(data, image_size=500 ,show=False ,img_index=0):
# RP transformationmtf
transform = RecurrencePlot(dimension=1,
threshold='percentage_points',
percentage=30)
return(pyts_transform(transform, data, image_size=image_size, show=show, cmap='binary', img_index=img_index))
def gasf_transform(data, image_size=500, show=False, img_index=0):
# GAF transformation
transform = GramianAngularField(image_size, method='summation')
return(pyts_transform(transform, data, image_size=image_size, show=show, cmap='rainbow', img_index=img_index))
def gadf_transform(data, image_size=500, show=False ,img_index=0):
# GAF transformation
transform = GramianAngularField(image_size, method='difference')
return(pyts_transform(transform, data, image_size=image_size, show=show, cmap='rainbow', img_index=img_index))
def labels_for(a_file_name):
segments=re.split(r'[_\-\.]+', a_file_name)
return(segments)
def max_in_sequence(sequence):
return(max(np.amax([list(d.values()) for d in sequence]), 0.01))
def compress_squiggle(squiggle, compress_factor):
squiggle_len = len(squiggle)
rem = squiggle_len % compress_factor
if rem > 0:
return(np.mean(squiggle[0:squiggle_len - rem].reshape(-1,compress_factor), axis=1))
return(squiggle)
def convert_to_image(signal):
transformed_squiggle = gasf_transform(signal.reshape(1,-1), image_size=image_size, show=False)
return(transformed_squiggle)
def confidence_margin(npa):
sorted = np.sort(npa)[::-1] #return sort in reverse, i.e. descending
# sorted = np.sort(npa) #return sort in reverse, i.e. descending
d = sorted[0] - sorted[1]
return(d)
def classify(model, labels, image, subtract_pixel_mean, threshold):
input_shape = image.shape[1:]
# x = image.astype('float32') / 255
x = image.astype('float32') + 1
x = x / 2
# If subtract pixel mean is enabled
if subtract_pixel_mean:
x_mean = np.mean(x, axis=0)
x -= x_mean
x=[x]
y = model.predict(x, verbose=0)
res = []
for i in range(len(y)):
cm = confidence_margin(y[i])
if y[i][np.argmax(y[i])] >= threshold:
res.append([labels[i], np.argmax(y[i]), cm, y[i]])
else:
res.append([labels[i], None, cm, y[i]])
return res
def train_pipeline(args):
'''
train a new dmux model
Defines a ResNet on the nanopore dataset.
ResNet v1
[a] Deep Residual Learning for Image Recognition
https://arxiv.org/pdf/1512.03385.pdf
ResNet v2
[b] Identity Mappings in Deep Residual Networks
https://arxiv.org/pdf/1603.05027.pdf
Usage
from resnet import train_model #and optional resnet_package_versions
# train_model(run_name, net_type,version, epochs, x_train, y_train, x_test, y_test,
# gpus=1,per_gpu_batch_size=16,tensorboard_output=None, data_augmentation = False, subtract_pixel_mean = False, verbose=0)
history=train_model(run, "ResNet20",2, epochs, x_train, y_train, x_test, y_test,
gpus=gpus,per_gpu_batch_size=16
'''
def resnet_package_versions():
print("Tensorflow version :",tf.__version__)
print("Keras version :",keras.__version__)
def lr_schedule(epoch):
"""Learning Rate Schedule
Learning rate is scheduled to be reduced after 10, 20, 30, 50 epochs.
Called automatically every epoch as part of callbacks during training.
# Arguments
epoch (int): The number of epochs
# Returns
lr (float32): learning rate
"""
lr = 1e-3
if epoch > 50:
lr *= 0.5e-3
elif epoch > 45:
lr *= 1e-3
elif epoch > 30:
lr *= 1e-2
elif epoch > 15:
lr *= 1e-1
print('Learning rate: ', lr)
return lr
# Training parameters
def depth_for(nn_name, version):
# Model version
# Orig paper: version = 1 (ResNet v1), Improved ResNet: version = 2 (ResNet v2)
# Model parameter
# ----------------------------------------------------------------------------
# | | 200-epoch | Orig Paper| 200-epoch | Orig Paper| sec/epoch
# Model | n | ResNet v1 | ResNet v1 | ResNet v2 | ResNet v2 | GTX1080Ti
# |v1(v2)| %Accuracy | %Accuracy | %Accuracy | %Accuracy | v1 (v2)
# ----------------------------------------------------------------------------
# ResNet20 | 3 (2)| 92.16 | 91.25 | ----- | ----- | 35 (---)
# ResNet32 | 5(NA)| 92.46 | 92.49 | NA | NA | 50 ( NA)
# ResNet44 | 7(NA)| 92.50 | 92.83 | NA | NA | 70 ( NA)
# ResNet56 | 9 (6)| 92.71 | 93.03 | 93.01 | NA | 90 (100)
# ResNet110 |18(12)| 92.65 | 93.39+-.16| 93.15 | 93.63 | 165(180)
# ResNet164 |27(18)| ----- | 94.07 | ----- | 94.54 | ---(---)
# ResNet1001| (111)| ----- | 92.39 | ----- | 95.08+-.14| ---(---)
# ---------------------------------------------------------------------------
nn_table={'ResNet20':[3,2],'ResNet32':[5,None],'ResNet44':[7,None],'ResNet56':[9,6],
'ResNet110':[18,12],'ResNet164':[27,18],'ResNet1001':[None,111]}
n = nn_table[nn_name][version-1]
# Computed depth from supplied model parameter n
if version == 1:
depth = n * 6 + 2
elif version == 2:
depth = n * 9 + 2
return(depth)
def resnet_layer(inputs,
num_filters=16,
kernel_size=3,
strides=1,
activation='relu',
batch_normalization=True,
conv_first=True):
"""2D Convolution-Batch Normalization-Activation stack builder
# Arguments
inputs (tensor): input tensor from input image or previous layer
num_filters (int): Conv2D number of filters
kernel_size (int): Conv2D square kernel dimensions
strides (int): Conv2D square stride dimensions
activation (string): activation name
batch_normalization (bool): whether to include batch normalization
conv_first (bool): conv-bn-activation (True) or
bn-activation-conv (False)
# Returns
x (tensor): tensor as input to the next layer
"""
conv = Conv2D(num_filters,
kernel_size=kernel_size,
strides=strides,
padding='same',
kernel_initializer='he_normal',
data_format='channels_first',
kernel_regularizer=l2(1e-4))
x = inputs
if conv_first:
x = conv(x)
print("Convolution name= ",x.name, " numfilters=", num_filters, " kernel_size=", kernel_size, " strides=", strides)
if batch_normalization:
x = BatchNormalization()(x)
print("Batch normalisation")
if activation is not None:
x = Activation(activation)(x)
print("Activation")
else:
if batch_normalization:
x = BatchNormalization()(x)
print("Batch normalisation")
if activation is not None:
x = Activation(activation)(x)
print("Activation")
x = conv(x)
print("Convolution name= ",x.name, " numfilters=", num_filters, " kernel_size=", kernel_size, " strides=", strides)
conv.name=conv.name+'_'+str(kernel_size)+'x'+str(kernel_size)+'_'+str(num_filters)+'_'+str(strides)
return x
def resnet_v1(input_shape, depth, num_classes=4):
"""ResNet Version 1 Model builder [a]
Stacks of 2 x (3 x 3) Conv2D-BN-ReLU
Last ReLU is after the shortcut connection.
At the beginning of each stage, the feature map size is halved (downsampled)
by a convolutional layer with strides=2, while the number of filters is
doubled. Within each stage, the layers have the same number filters and the
same number of filters.
Features maps sizes:
stage 0: 32x32, 16
stage 1: 16x16, 32
stage 2: 8x8, 64
The Number of parameters is approx the same as Table 6 of [a]:
ResNet20 0.27M
ResNet32 0.46M
ResNet44 0.66M
ResNet56 0.85M
ResNet110 1.7M
# Arguments
input_shape (tensor): shape of input image tensor