-
Notifications
You must be signed in to change notification settings - Fork 1
/
carnelian.py
1345 lines (1193 loc) · 55.1 KB
/
carnelian.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 python
'''
Runs the Carnelian framework for functional binning of metagenomic sequences
using LDPC k-mer hash based features. Based of the paper "Improved functional
binning of metagenomic sequences in clinical studies" by Sumaiya Nazeen and
Bonnie Berger.
This is written by Sumaiya Nazeen <[email protected]> and is based off of the
python wrapper of Opal tool originally written by Yun William Yu.
Carnelian uses an adapted version of the implementation of the metagenomic
binning from the source code of K. Vervier, P. Mahe, M. Tournoud, J.-B.
Veyrieras, and J.-P. Vert. Large-scale Machine Learning for Metagenomics
Sequence Classification, Technical report HAL-01151453, May, 2015.
This code is included in the util/ directory, with modifications to enable
using Carnelian's (originally used in Opal framework) Gallagher code based
hashes in util/ldpc.py.
The code from Verview, et al, requires the Genetic Data Analysis Library,
which we have included a copy of under util/ext/ for ease of installation.
This pipeline depends on Python scikit-learn, numpy, pandas, and on Vowpal Wabbit.
Vowpal Wabbit must be properly installed in the system path. It also assumes a working
R installation (version >= 3.3.2) to be available.
'''
# import required packages
from __future__ import print_function
__version__ = "1.0.0"
import os
from os import path, mkdir
from os.path import isdir
import glob
import argparse
import sys
import subprocess
import random
import time
import threading
import pandas as pd
import numpy as np
import csv
import shutil
import operator
from shutil import copyfile
from multiprocessing.dummy import Pool
from sklearn.metrics import precision_score, recall_score
from datetime import datetime
from collections import Counter
from Bio import SeqIO
script_loc = os.path.realpath(__file__)
sys.path.append(os.path.join(os.path.dirname(script_loc),'util'))
import ldpc
import sequtil
# Setting up environment variables
my_env = os.environ.copy()
my_env["PATH"]=(
os.path.join(os.path.dirname(script_loc),'util') + ":" +
os.path.join(os.path.dirname(script_loc),'util','ext','gdl-1.1','GDL','bin') + ":" +
os.path.join(os.path.dirname(script_loc),'util','ext','gdl-1.1','GDL','include') + ":" +
my_env.get("PATH", ""))
my_env["LD_LIBRARY_PATH"]=(
os.path.join(os.path.dirname(script_loc),'util','ext','gdl-1.1','GDL','lib') + ":" +
my_env.get("LD_LIBRARY_PATH", ""))
# Utility classes and functions
class ArgClass:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
class LabelProb:
def __init__(self, label, prob):
self.label = label
self.prob = prob
def __getitem__(self,label):
return self.label
def __getitem__(self,prob):
return self.prob
def __setitem__(self,label,value):
self.label = value
def __setitem__(self,prob,value):
self.prob = value
def __lt__(self,other):
return self.prob < other.prob
def __le__(self,other):
return self.prob <= other.prob
def __gt__(self,other):
return self.prob > other.prob
def __ge__(self,other):
return self.prob >= other.prob
def __eq__(self,other):
return self.prob == other.prob
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def unique_lines(file):
'''gets number of unique lines in file'''
seen = set()
with open(file) as f:
for line in f:
seen.add(line)
return len(seen)
def safe_makedirs(directory):
if not os.path.exists(directory):
os.makedirs(directory)
else:
print("Directory already exists!!")
return 1
return 0
def get_fasta_and_label(directory):
'''finds the 'first' fasta file in directory, and returns a tuple with
it and the matching named label file in the directory if both exist'''
try:
fasta = glob.glob(directory + "/*.fasta")[0]
except IndexError:
raise RuntimeError("Could not find fasta file in:" + directory)
labels = os.path.splitext(fasta)[0] + ".label"
if not os.path.isfile(labels):
print("Couldn't find matching labels ... creating labels ...")
name = os.path.splitext(os.path.basename(fasta))[0]
path = os.path.join(directory,name+'.label')
cmd = "grep '>' "+ fasta + " > " + path
print(cmd)
os.system(cmd)
labels = glob.glob(directory + "/*.label")[0]
return [fasta, labels]
def merge_dico(old_dico,new_dico):
''' merges old dictionary and new dictionary files while retraining'''
dold = [line.strip() for line in open(old_dico)]
dnew = [line.strip() for line in open(new_dico)]
m = {}
cur_max = -1
for l in dold:
x = l.split('\t')
key = x[0]
val = int(x[1])
m[key] = val
if val > cur_max:
cur_max = val
for l in dnew:
x = l.split('\t')
if x[0] not in m.keys():
cur_max += 1
m[x[0]] = cur_max
out_file = open(new_dico,'w')
for k in m.keys():
s = k + '\t' + str(m[k]) + '\n'
out_file.write(s)
out_file.close()
def parse_extra(parser, namespace):
namespaces = []
extra = namespace.extra
while extra:
n = parser.parse_args(extra)
extra = n.extra
namespaces.append(n)
return namespaces
def extract_column_two(infile, outfile):
"""cut -f2 infile > outfile"""
with open(infile, 'r') as inf:
with open(outfile, 'w') as outf:
for line in inf:
parts = line.split()
if len(parts) > 1:
print(parts[1], file=outf)
else:
print('',file=outf)
def vw_class_to_label(inputfile, dicofile, outputfile):
'''Converts vw IDs in a newline delimited list (inputfile) to
outputfile using the mapping specified in dicofile'''
dico = {}
with open(dicofile, "r") as fin:
for line in fin:
txid, vwid = line.strip().split()[:2]
dico[vwid] = txid
predout = open(outputfile, "w")
with open(inputfile, "r") as fin:
for line in fin:
#print(dico[line.strip()])
predout.write("%s\n"%(dico[str(int(float(line.strip().split(' ')[0])))]))
predout.close()
def vw_class_to_label2(inputfile, dicofile, outputfile, cutoff):
'''Converts vw IDs and probabilities in a newline delimited list (inputfile) to outputfile using the mapping specified in dicofile'''
dico = {}
with open(dicofile, "r") as fin:
for line in fin:
txid, vwid = line.strip().split()[:2]
dico[vwid] = txid
predout = open(outputfile, "w")
probfile = os.path.join(os.path.dirname(outputfile),'label-probabilities.tsv')
probout = open(probfile,'w')
i = 1
with open(inputfile, "r") as fin:
for line in fin:
x = line.strip().split(' ')
lp_arr = []
for k in x:
y = k.split(':')
lp_arr.append(LabelProb(y[0],float(y[1])))
lp_arr.sort(key=operator.attrgetter('prob'),reverse=True)
if lp_arr[0].prob >= cutoff:
s = dico[lp_arr[0].label] + '\t' + str(lp_arr[0].prob) + '\n'
probout.write(s)
predout.write(str(i)+'\t' + dico[lp_arr[0].label]+'\n')
else:
s = dico[lp_arr[0].label] + '\t' + str(lp_arr[0].prob)+ '\t' + dico[lp_arr[1].label] + '\t' + str(lp_arr[1].prob) + '\t' + dico[lp_arr[2].label] + '\t' + str(lp_arr[2].prob) + '\n'
probout.write(s)
i += 1
predout.close()
probout.close()
def majority_voting(L):
counts = dict((x,L.count(x)) for x in set(L))
sorted_counts = sorted(counts.items(), key=operator.itemgetter(1), reverse=True)
if len(sorted_counts) == 1:
return sorted_counts[0][0]
else:
if sorted_counts[0][1] > sorted_counts[1][1]:
return sorted_counts[0][0]
else:
return 'N.N.N.N'
def resolve_label(out_dir, orf_seq_file, orf_label_file, args):
orf_labels = [line.strip() for line in open(orf_label_file)]
read_labels = []
id_list = []
with open(orf_seq_file, mode='r') as handle:
for record in SeqIO.parse(handle,'fasta'):
id_list.append(record.id.split('_')[0])
m = {}
for i in xrange(len(orf_labels)):
k = id_list[i]
if k not in m.keys():
m[k] = [orf_labels[i]]
else:
m[k].append(orf_labels[i])
for k in m.keys():
if len(m[k]) == 1:
read_labels.append(m[k][0])
else:
read_labels.append(majority_voting(m[k]))
safe_makedirs(out_dir)
read_label_path = os.path.join(out_dir,"reads.label")
of = open(read_label_path,'w')
for l in read_labels:
of.write(l+'\n')
of.close()
return read_label_path
def resolve_label_wrt_ref(out_dir, orf_seq_file, orf_label_file, read_seq_file, args):
orf_labels = [line.strip() for line in open(orf_label_file)]
print(orf_labels)
ref_id_list = []
with open(read_seq_file, mode='r') as handle:
for record in SeqIO.parse(handle,'fasta'):
ref_id_list.append(record.id)
read_labels = ['N.N.N.N' for _ in ref_id_list]
orf_id_list = []
with open(orf_seq_file, mode='r') as handle:
for record in SeqIO.parse(handle,'fasta'):
orf_id_list.append(record.id.split('_')[0])
from collections import Counter
z = Counter(orf_id_list)
for i in xrange(len(orf_id_list)):
id = orf_id_list[i]
ind = ref_id_list.index(id)
if z[id] == 1:
read_labels[ind] = orf_labels[i]
else:
oi = [j for j,val in enumerate(orf_id_list) if val == id]
labels = [orf_labels[j] for j in oi]
read_labels[ind] = majority_voting(labels)
#m = {}
#for i in xrange(len(orf_labels)):
# k = orf_id_list[i]
# if k not in m.keys():
# m[k] = [orf_labels[i]]
# else:
# m[k].append(orf_labels[i])
#for k in m.keys():
# if k in ref_id_list:
# ind = ref_id_list.index(k)
# if len(m[k]) == 1:
# read_labels[ind] = m[k][0]
# else:
# read_labels[ind] = majority_voting(m[k])
safe_makedirs(out_dir)
read_label_path = os.path.join(out_dir,"reads_wrt_ref.label")
of = open(read_label_path,'w')
for l in read_labels:
of.write(l+'\n')
of.close()
return read_label_path
def get_final_model(directory):
'''gets a 'final' model from a directory. Note, will match the first
file ending in _final.model'''
try:
model = glob.glob(directory + "/*_final.model")[0]
except IndexError:
raise RuntimeError("Could not find final model file in: " + directory)
return model
def getAbundance(pred_labels, gs_file, mean_read_length, out_dir):
''' Calculate raw and effective counts from the predicted
labels for a given sample
pred_labels (string): path to a file containing the functional
labels predicted by Carnelian
gs_file (string): must be the name of the file with gold standard label with
full path specification
mean_read_length (int): mean read length in base pairs
out_dir (string): path to the output directory where abundance files
will be written
'''
lines = [line.strip() for line in open(gs_file)]
labels = [x.split('\t')[0] for x in lines[1:]]
lengths = [(float(x.split('\t')[1])-(mean_read_length/3.0)+1)/1000 for x in lines[1:]]
lengths2 = [float(x.split('\t')[1]) for x in lines[1:]]
labels = list(set(labels))
flines = [line.strip() for line in open(pred_labels)]
counts = Counter(flines)
raw_counts = [0 for _ in labels]
eff_counts = [0 for _ in labels]
rpk_counts = [0 for _ in labels]
for k in counts.keys():
if k != "N.N.N.N":
r = labels.index(k)
raw_counts[r] = counts[k]
eff_counts[r] = counts[k]/lengths[r]
rpk_counts[r] = counts[k]*1000000000/(lengths2[r]*len(flines))
N = sum(eff_counts)
#print(N)
eff_counts2 = [1000000*r/N for r in eff_counts]
of = open(os.path.join(out_dir,'raw_counts.tsv'),'w')
of2 = open(os.path.join(out_dir,'effective_counts.tsv'),'w')
of2.write('EC Label\tRPKM\tTPM\n')
for i in xrange(len(labels)):
if raw_counts[i] != 0:
of.write(labels[i]+'\t'+str(raw_counts[i])+'\n')
of2.write(labels[i]+'\t'+str(rpk_counts[r])+'\t'+str(eff_counts2[i])+'\n')
of.close()
of2.close()
def createAbundanceMatrix(predict_dir, aa_dir, gs_file):
'''creates a samples x predicted_labels abundance matrix for downstream
analyses given all the label prediction files in predict_dir
predict_dir (string): must be a path to the input directory containing label
predictions (.label and .vw) files for each sample in its
own sub-directory. If paired end reads, both predictions files
should be in the corresponding sample's subdirectory.
aa_dir (string): must be a path to an output directory where the abundance
matrix will be written. It should not be nested within predict_dir.
gs_file(string): must be the name of the file with gold standard label with
full path specification
'''
#samples = os.listdir(predict_dir)
samples = next(os.walk(predict_dir))[1]
#print(samples)
samples.sort()
lines = [line.strip() for line in open(gs_file)]
labels = [x.split('\t')[0] for x in lines[1:]]
labels = list(set(labels))
#print(labels[0:4])
ncol = len(samples)
nrow = len(labels)
#print(nrow)
#print(ncol)
abmat = np.zeros((nrow,ncol))
for c in xrange(ncol):
fpath = os.path.join(predict_dir,samples[c])
filelist = glob.glob(fpath+'/*.label')
for f in filelist:
flines = [line.strip() for line in open(f)]
counts = Counter(flines)
for k in counts.keys():
if k != "N.N.N.N":
r = labels.index(k)
abmat[r,c] += counts[k]
df = pd.DataFrame(abmat, index=labels, columns=samples)
fname = os.path.join(aa_dir,'raw_counts.tsv')
df.to_csv(fname,sep='\t',index=True,header=True)
return 0
# Carnelian features
#def translateOne(argument):
# '''Subroutine for translating one sample on one cpu using transeq'''
# #print("in translate one")
# os.system('transeq -frame 6 ' + argument)
def translateSeqs(seq_dir, out_dir, fgsp_loc, args):
'''
Find genes in the input reads and translate the coding sequences to ORFs using FragGeneScan
using n cpus.
seq_dir (string): must be a path to a directory with a nucleotide fasta file
out_dir (string): must be a path to an output directory where ORFs will be written
fgsp_loc(string): must be a path to the directory where FragGeneScan is installed
Unpacking args:
ncpus (int): number of cpus to be used to parallelize the translation
'''
ncpus = args.ncpus
#p=Pool(args.ncpus)
#my_env["PATH"]=(os.path.dirname(fgsp_loc) + ":" + my_env.get("PATH", ""))
os.environ["PATH"]=(fgsp_loc + ":" + my_env.get("PATH", ""))
try:
fpath = os.path.join(seq_dir,'*fasta')
fasta_file = [x for x in glob.glob(fpath)][0]
#name_path = [(name, seq_dir + '/' + name) for name in fasta_filelist]
first_record = SeqIO.parse(fasta_file, "fasta").next()
if not sequtil.check_if_nucl(str(first_record.seq)):
print("Could not find nucleotide fasta file in:" + seq_dir)
return(1)
except IndexError:
raise RuntimeError("Could not find fasta file in:" + seq_dir)
safe_makedirs(out_dir)
out_file = os.path.join(out_dir, os.path.basename(fasta_file).rsplit('.',1)[0])
starttime = datetime.now()
print('''================================================
Predicting ORFs from nucleotide fasta file
{:%Y-%m-%d %H:%M:%S}'''.format(starttime))
sys.stdout.flush()
#cmd = 'FGS+ -s ' + fasta_file + ' -o ' + out_file + ' -w 0 -r ' + os.path.join(fgsp_loc,'train') + ' -t illumina_1 ' + ' -m 20480'
print(os.path.join(fgsp_loc,'train/complete'))
cmd = 'run_FragGeneScan.pl -genome=' + fasta_file + ' -out='+out_file +' -train=complete'+ ' -complete=0'
if ncpus > 1:
#cmd += ' -p ' + str(ncpus)
cmd += ' -thread=' + str(ncpus)
os.system(cmd)
outfile = out_file + '.faa'
os.system('mv ' + outfile + ' ' + out_file + '.fasta')
print('''------------------------------------------------
Total wall clock runtime (sec): {}
================================================'''.format(
(datetime.now() - starttime).total_seconds()))
sys.stdout.flush()
return(0)
def frag(test_dir, frag_dir, args):
'''
Draw fragments of length l from the fasta file found in the test_dir with
coverage c. Note that there must be a label file of the same basename with
matching ids for each of the fasta lines.
test_dir (string): must be a path to a directory with a single fasta
and label file
frag_dir (string): must be a path to an output directory
Unpacking args:
frag_length (int): length of fragments to be drawn
coverage (float): fraction of times each location is to be covered
by drawn fragments
'''
# Unpack args
frag_length = args.frag_length
coverage = args.coverage
# Finish unpacking args
fasta, labels = get_fasta_and_label(test_dir)
safe_makedirs(frag_dir)
fasta_out = os.path.join(frag_dir, 'test.fragments.fasta')
gi2label_out = os.path.join(frag_dir, 'test.fragments.gi2label')
label_out = os.path.join(frag_dir, 'test.fragments.label')
starttime = datetime.now()
print('''================================================
Drawing fragments
{:%Y-%m-%d %H:%M:%S}
'''.format(starttime) + '''
frag_length = {frag_length}
coverage = {coverage}
------------------------------------------------
Fasta input: {fasta}
labels input: {labels}
Fasta output: {fasta_out}
gi2label output:{gi2label_out}
labels output: {label_out}'''.format(
frag_length=frag_length, coverage=coverage, fasta=fasta,
labels=labels, fasta_out=fasta_out, gi2label_out=gi2label_out,
label_out=label_out)
)
sys.stdout.flush()
# set seed (for reproducibility)
seed = 42
# draw fragments
subprocess.check_call(["drawfrag",
"-i", fasta,
"-t", labels,
"-l", str(frag_length),
"-c", str(coverage),
"-o", fasta_out,
"-g", gi2label_out,
"-s", str(seed)],
env=my_env)
# extract labels
extract_column_two(gi2label_out, label_out)
print('''------------------------------------------------
Total wall clock runtime (sec): {}
================================================'''.format(
(datetime.now() - starttime).total_seconds()))
sys.stdout.flush()
return 0
def train(ref_dir, model_dir, args):
'''Draws fragments from the fasta file found in ref_dir. Note that
there must be a label file of the same basename with matching ids for
each of the fasta lines.
ref_dir (string): must be a path to a directory with a single fasta
and label file
model_dir (string): must be a path to an output directory
Unpacking args:
frag_length (int): length of fragments to be drawn
coverage (float): fraction of times each location is to be covered
by drawn fragments
kmer_length (int): size of k-mers used
rweight (int): how many positions will be randomly chosen in the
contiguous k-mer (k-mer length should be multiple
of row_weight)
num_hash (int): number of hashing functions
num_batches (int): number of times to run vowpal_wabbit
num_passes (int): number of passes within vowpal_wabbit
precise (flag): if set trained model will store probabilities for labels
'''
# Unpack args
frag_length = args.frag_length
coverage = args.coverage
kmer = args.kmer_length
row_weight = args.rweight
hierarchical = args.hweight # only comes into play if > 0
num_hash = args.num_hash
num_batches = args.num_batches
num_passes = args.num_passes
bits = args.bits
lambda1 = args.lambda1
lambda2 = args.lambda2
# Finish unpacking args
fasta, labels = get_fasta_and_label(ref_dir)
starttime = datetime.now()
if kmer % row_weight != 0:
raise ValueError("Row weight [{}] must divide into k-mer length [{}].".format(row_weight, kmer))
if (hierarchical > 0):
if kmer % hierarchical != 0:
raise ValueError("Hierarchy middle level [{}] must divide into k-mer length [{}].".format(hierarchical, kmer))
if hierarchical % row_weight != 0:
raise ValueError("Row weight[{}] must divide into middle hierarchical structure weight [{}].".format(row_weight, hierarchical))
print(
'''================================================
Training using Carnelian + vowpal-wabbit
{:%Y-%m-%d %H:%M:%S}
'''.format(starttime) + '''
frag_length = {frag_length}
coverage: {coverage}
k-mer length: {kmer}'''.format(
frag_length=frag_length,
coverage=coverage,
kmer=kmer))
if hierarchical > 0:
print('''hierarchical: {}'''.format(hierarchical))
print('''row weight: {row_weight}
num hashes: {num_hash}
num batches: {num_batches}
num passes: {num_passes}
------------------------------------------------
Fasta input: {fasta}
labels input: {labels}
------------------------------------------------'''.format(
row_weight=row_weight,
num_hash=num_hash,
num_batches=num_batches,
num_passes=num_passes,
fasta=fasta,
labels=labels)
)
sys.stdout.flush()
num_labels = unique_lines(labels)
print("Number labels: {}".format(num_labels))
sys.stdout.flush()
safe_makedirs(model_dir)
# define output "dictionary" : label <--> vw classes
dico = os.path.join(model_dir, "vw-dico.txt")
# define model prefix
model_prefix = os.path.join(model_dir, "vw-model")
# generate LDPC spaced pattern
pattern_file = os.path.join(model_dir, "patterns.txt")
ldpc.ldpc_write(k=kmer, t=row_weight, _m=num_hash, d=pattern_file)
seed = 42
for i in range(num_batches):
seed = seed + 1
batch_prefix = os.path.join(model_dir, "train.batch-{}".format(i))
fasta_batch = batch_prefix + ".fasta"
gi2label_batch = batch_prefix + ".gi2label"
label_batch = batch_prefix + ".label"
# draw fragments
subprocess.check_call(["drawfrag",
"-i", fasta,
"-t", labels,
"-l", str(frag_length),
"-c", str(coverage),
"-o", fasta_batch,
"-g", gi2label_batch,
"-s", str(seed)],
env=my_env)
# extract labels
extract_column_two(gi2label_batch, label_batch)
#cherry = [line.strip() for line in open(label_batch)]
#print(len(cherry))
print("calling fasta2skm for batch {}".format(i))
# learn model
fasta2skm_param_list = ["fasta2skm",
"-i", fasta_batch,
"-t", label_batch,
"-k", str(kmer),
"-d", dico,
"-p", pattern_file]
print("Getting training set ...")
sys.stdout.flush()
training_list = subprocess.check_output(
fasta2skm_param_list, env=my_env).splitlines()
print("Shuffling training set ...")
sys.stdout.flush()
random.shuffle(training_list)
curr_model = model_prefix + "_batch-{}.model".format(i)
prev_model = model_prefix + "_batch-{}.model".format(i-1) # May not exist if first run
vw_param_base = ["vw",
"--random_seed", str(seed),
"-f", curr_model,
"--cache_file", batch_prefix + ".cache",
"--passes", str(num_passes),
"--save_resume"]
if args.precise:
vw_param_base += ["--loss_function=logistic", "--probabilities"]
vw_param_firstrun = [
"--oaa", str(num_labels),
"--bit_precision", str(bits),
"--l1", str(lambda1),
"--l2", str(lambda2)]
if i > 0:
vw_param_list = vw_param_base + ["-i", prev_model]
else:
vw_param_list = vw_param_base + vw_param_firstrun
print(vw_param_list)
sys.stdout.flush()
vwps = subprocess.Popen(vw_param_list, env=my_env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
gsp = vwps.communicate(input='\n'.join(training_list))
print(gsp)
while vwps.poll() is None:
l = vwps.stdout.readline()
sys.stdout.write(l)
sys.stdout.flush()
# thread.join() # This shouldn't be necessary, but just being safe.
if i > 0:
os.remove(prev_model)
if i == num_batches - 1:
os.rename(curr_model, model_prefix + "_final.model")
os.remove(batch_prefix + ".cache")
os.remove(fasta_batch)
os.remove(label_batch)
os.remove(gi2label_batch)
print("Finished batch {}".format(i))
print('''------------------------------------------------
Total wall clock runtime (sec): {}
================================================'''.format(
(datetime.now() - starttime).total_seconds()))
sys.stdout.flush()
return 0
def retrain(old_model_dir, new_model_dir, new_examples_dir, args):
'''Draws fragments from the fasta file found in ref_dir. Note that
there must be a label file of the same basename with matching ids for
each of the fasta lines.
old_model_dir (string): must be a path to a directory with old vowpal wabbit model
new_model_dir (string): must be a path to a directory that will contain the new model
new_examples_dir (string): must be a path to a directory containing the new training samples and labels
Unpacking args:
frag_length (int): length of fragments to be drawn
coverage (float): fraction of times each location is to be covered
by drawn fragments
kmer_length (int): size of k-mers used
row_weight (int): how many positions will be randomly chosen in the
contiguous k-mer (k-mer length should be multiple
of row_weight)
num_hash (int): number of hashing functions
num_batches (int): number of times to run vowpal_wabbit
num_passes (int): number of passes within vowpal_wabbit
precise (flag): if set trained model will store probabilities for labels
'''
frag_length = args.frag_length
coverage = args.coverage
kmer = args.kmer_length
num_batches = args.num_batches
num_passes = args.num_passes
fasta, labels = get_fasta_and_label(new_examples_dir)
starttime = datetime.now()
print('''================================================
Retraining using Carnelian + vowpal-wabbit
{:%Y-%m-%d %H:%M:%S}
'''.format(starttime) +
'''num batches: {num_batches}
num passes: {num_passes}
------------------------------------------------
Fasta input: {fasta}
labels input: {labels}
------------------------------------------------'''.format(
num_batches=num_batches,
num_passes=num_passes,
fasta=fasta,
labels=labels)
)
sys.stdout.flush()
num_labels = unique_lines(labels)
print("Number labels: {}".format(num_labels))
sys.stdout.flush()
safe_makedirs(new_model_dir)
old_dico = os.path.join(old_model_dir,"vw-dico.txt")
dico = os.path.join(new_model_dir, "vw-dico.txt")
# define model prefix
prev_model = os.path.join(old_model_dir,"vw-model_final.model")
model_prefix = os.path.join(new_model_dir, "vw-model")
# copy previously used LDPC spaced pattern
old_pattern_file = os.path.join(old_model_dir, "patterns.txt")
pattern_file = os.path.join(new_model_dir, "patterns.txt")
copyfile(old_pattern_file, pattern_file)
seed = 42
for i in range(num_batches):
seed = seed + 1
batch_prefix = os.path.join(new_model_dir, "train.batch-{}".format(i))
fasta_batch = batch_prefix + ".fasta"
gi2label_batch = batch_prefix + ".gi2label"
label_batch = batch_prefix + ".label"
# draw fragments
subprocess.check_call(["drawfrag",
"-i", fasta,
"-t", labels,
"-l", str(frag_length),
"-c", str(coverage),
"-o", fasta_batch,
"-g", gi2label_batch,
"-s", str(seed)],
env=my_env)
# extract labels
extract_column_two(gi2label_batch, label_batch)
# learn model
fasta2skm_param_list = ["fasta2skm",
"-i", fasta_batch,
"-t", label_batch,
"-k", str(kmer),
"-d", dico,
"-p", pattern_file]
print("Getting new training examples ...")
sys.stdout.flush()
training_list = subprocess.check_output(
fasta2skm_param_list, env=my_env).splitlines()
#print(training_list)
print("Shuffling training set ...")
sys.stdout.flush()
random.shuffle(training_list)
curr_model = model_prefix + "_batch-{}.model".format(i)
if i > 0:
prev_model = model_prefix + "_batch-{}.model".format(i-1) # May not exist if first run
vw_param_base = ["vw",
"--random_seed", str(seed),
"-f", curr_model,
"--cache_file", batch_prefix + ".cache",
"--passes", str(num_passes),
"--save_resume"]
if args.precise:
vw_param_base += ["--loss_function=logistic", "--probabilities"]
vw_param_list = vw_param_base + ["-i", prev_model]
print(vw_param_list)
sys.stdout.flush()
vwps = subprocess.Popen(vw_param_list, env=my_env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
gsp = vwps.communicate(input='\n'.join(training_list))
print(gsp)
while vwps.poll() is None:
l = vwps.stdout.readline()
sys.stdout.write(l)
sys.stdout.flush()
#thread.join() # This shouldn't be necessary, but just being safe.
if i > 0:
os.remove(prev_model)
if i == num_batches - 1:
os.rename(curr_model, model_prefix + "_final.model")
os.remove(batch_prefix + ".cache")
os.remove(fasta_batch)
os.remove(label_batch)
os.remove(gi2label_batch)
merge_dico(old_dico,dico)
print('''------------------------------------------------
Total wall clock runtime (sec): {}
================================================'''.format(
(datetime.now() - starttime).total_seconds()))
sys.stdout.flush()
return 0
def predict(model_dir, test_dir, predict_dir, args):
'''Predicts functional labels for each record in fasta file found in test_dir
using the vowpal-wabbit model. Note that there must be a label file of the
same basename with matching ids for each of the fasta lines.
test_dir (string): must be a path to a directory with a single fasta
and label file
model_dir (string): must be a path to a directory with a vw model file
predict_dir (string):output directory of predictions
Unpacking args:
kmer_length (int): size of k-mers used
ncpus (int): number of cpus to be used
precise (flag): if set, two prediction files will be generated -- one with read
ids and labels that have probabilities above cutoff, other with
label probabilities for strong predictions and three top possible
labels with probabilities for weak predictions
cutoff (float): user-defined probability cut off for precise mode
Returns a tuple with (reffile, predicted_labels_file) for easy input
into evaluate_predictions.
'''
# Unpack args
kmer = args.kmer_length
ncpus = args.ncpus
cutoff = 0.0
if args.precise:
cutoff = args.cutoff
try:
fasta = [os.path.basename(x) for x in glob.glob(os.path.join(test_dir,'*.fasta'))][0]
except IndexError:
raise RuntimeError("Could not find fasta file in:" + test_dir)
safe_makedirs(predict_dir)
starttime = datetime.now()
print(
'''================================================
Predicting using Carnelian + vowpal-wabbit
{:%Y-%m-%d %H:%M:%S}
'''.format(starttime) + '''
k-mer length: {kmer}
------------------------------------------------
Fasta input: {fasta}
------------------------------------------------'''.format(
kmer=kmer,
fasta=fasta))
sys.stdout.flush()
if ncpus > 1:
p=Pool(ncpus)
tmp_path = os.path.join(predict_dir, 'tmp')
safe_makedirs(tmp_path)
infastapath = os.path.join(test_dir, fasta)
splits = sequtil.split_fasta2(infastapath, tmp_path, ncpus, my_env)
#splits = sequtil.split_fasta(infastapath, tmp_path, ncpus)
print(splits)
test_dirlist = [os.path.dirname(x) for x in glob.glob(os.path.join(tmp_path,'*/*.fasta'))]
pred_dirlist = [os.path.join(f,'predict') for f in test_dirlist]
arglist=[model_dir+'|'+test_dirlist[i]+'|'+pred_dirlist[i]+'|'+str(kmer) for i in range(ncpus)]
if args.precise:
arglist = [x+'|'+str(args.precise)+'|'+str(cutoff) for x in arglist]
p.map(predict_unpack, arglist)
filelist = [glob.glob(os.path.join(d,'*.label'))[0] for d in pred_dirlist]
#print(filelist)
prefix = sequtil.merge_files2(filelist,predict_dir,fasta,'label', my_env)
vw_prefix = sequtil.merge_files2(filelist,predict_dir,fasta,'vw', my_env)
if args.precise:
filelist = [glob.glob(os.path.join(d,'*.tsv'))[0] for d in pred_dirlist]
prob_file = sequtil.merge_files2(filelist,predict_dir,fasta,'tsv',my_env)
shutil.rmtree(tmp_path, ignore_errors=True)
else:
prefix = predictOne(model_dir, test_dir, predict_dir, kmer, args.precise, cutoff)
pred_file = os.path.join(os.path.dirname(prefix),fasta.split('.')[0]+'.label')
os.system("mv "+prefix+' '+pred_file)
orig_file = prefix.rsplit('.',1)[0]+'.vw'
vw_file = os.path.join(os.path.dirname(prefix),fasta.split('.')[0]+'.vw')
os.system("mv "+orig_file+' '+vw_file)
if args.precise:
prob_file = os.path.join(os.path.dirname(prefix),fasta.split('.')[0]+'.tsv')
orig_file = os.path.join(os.path.dirname(prefix),'label-probabilities.tsv')
os.system("mv "+orig_file+' '+prob_file)
prefix = pred_file
print('''------------------------------------------------
Predicted labels: {pl}
Total wall clock runtime (sec): {s}
================================================'''.format(
pl=prefix,
s=(datetime.now() - starttime).total_seconds()))
sys.stdout.flush()
return (prefix.strip())
def predict_unpack(args):
s = args.split('|')
model_dir = s[0]
test_dir = s[1]
predict_dir = s[2]
k = int(s[3])
precise = False
cutoff=0.0
if len(s) > 5:
precise = bool(s[4])
cutoff = float(s[5])
predictOne(model_dir, test_dir, predict_dir, k, precise, cutoff)
def predictOne(model_dir, test_dir, predict_dir, kmer, precise, cutoff=0.0):
# Don't need to get labels until eval
#fasta, labels = get_fasta_and_label(test_dir)
try:
fasta = glob.glob(test_dir + "/*.fasta")[0]
except:
raise RuntimeError("No fasta file found in: " + test_dir)
model = get_final_model(model_dir)
dico = os.path.join(model_dir, "vw-dico.txt")
pattern_file = os.path.join(model_dir, "patterns.txt")
safe_makedirs(predict_dir)
prefix = os.path.join(predict_dir, "test.fragments-db")
# get vw predictions
fasta2skm_param_list = ["fasta2skm",
"-i", fasta,
"-k", str(kmer),
"-p", pattern_file]
vw_param_list = ["vw", "-t",
"-i", model,
"-p", prefix + ".preds.vw"]
if precise:
vw_param_list.append("--probabilities")
ps = subprocess.Popen(fasta2skm_param_list, env=my_env,
stdout=subprocess.PIPE)
vwps = subprocess.Popen(vw_param_list, env=my_env,
stdin=ps.stdout, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while vwps.poll() is None:
l = vwps.stdout.readline()
sys.stdout.write(l)