forked from parklab/NGSCheckMate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ncm.py
1490 lines (1238 loc) · 56.3 KB
/
ncm.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
import os
import math
import subprocess, time
import argparse
from argparse import RawTextHelpFormatter
from subprocess import call
global bed_file
global outdir
global outfilename
global temp_out
global testsamplename
global SAMTOOLS
global BCFTOOLS
global REF
global bam_list
glob_scores = dict() #Whole score
feature_list = dict() #Each Feature List
label = [] #Samples
features = [] #dbSNP features
mean_depth = dict()
real_depth = dict()
real_count = dict()
sum_file = dict()
out_tag = ""
pdf_tag = ""
Family_flag = False
Nonzero_flag = False
#Calculation of AVerages
def average(x):
assert len(x) > 0
return float(sum(x)) / len(x)
#Calulation of Pearson Correlation
def pearson_def(x, y):
assert len(x) == len(y)
n = len(x)
## Need to be checked , n==0 case
if n == 0 :
return 0
assert n > 0
avg_x = average(x)
avg_y = average(y)
diffprod = 0
xdiff2 = 0
ydiff2 = 0
for idx in range(n):
xdiff = x[idx] - avg_x
ydiff = y[idx] - avg_y
diffprod += xdiff * ydiff
xdiff2 += xdiff * xdiff
ydiff2 += ydiff * ydiff
sqrt_xdiff2_ydiff2 = math.sqrt(xdiff2 * ydiff2)
return diffprod / sqrt_xdiff2_ydiff2 if sqrt_xdiff2_ydiff2 != 0.0 else 0.0
# createDataSet
# base_dir : directory of files, bedFile: name of the bedFile
def createDataSetFromDir(base_dir, bedFile):
for root, dirs, files in os.walk(base_dir):
for file in files:
if not file.endswith(".vcf"):
continue
link = root + '/' + file
f = open(link, "r")
dbsnpf= open(bedFile,"r")
depth = dict()
depth[file] = 0
real_count[file] = 0
count = 0
sum=dict()
sum[file] = 0
scores = dict() # Scores of B-allel Frequencies
#DBSNP ID collecting system
for i in dbsnpf.readlines():
temp = i.strip().split('\t')
if temp[0].find("chr")!= -1:
ID = str(temp[0][3:]) + "_" + str(temp[2])
else:
ID = str(temp[0]) + "_" + str(temp[2])
scores[ID] = 0
count = count + 1
## 0618_samtools and haplotyper
vcf_flag = 0
# feature_list[file] = []
score_set = dict()
#VCF file PROCESSING and Generation of features
total = 0
GVCF_samples = dict()
for i in f.readlines():
if i.startswith("#"):
if i.find("DP4") != -1:
vcf_flag = 1
if i.find("#CHROM") != -1:
temp = i.strip().split('\t')
total=len(temp) - 9
if total != 1:
for sample_idx in range(0,total):
file = temp[sample_idx + 9]
GVCF_samples[temp[sample_idx + 9]] = []
score_set[temp[sample_idx + 9]] = dict()
depth[temp[sample_idx + 9]] = 0
real_count[temp[sample_idx + 9]] = 0
sum[temp[sample_idx + 9]] =0
feature_list[temp[sample_idx + 9]] = []
if total == 1:
feature_list[file] = []
continue
temp = i.strip().split('\t')
## ID in BED file only
if temp[0].find("chr")!= -1:
ID = str(temp[0][3:]) + "_" + str(temp[1])
else:
ID = str(temp[0]) + "_" + str(temp[1])
if ID not in scores:
continue
if vcf_flag == 1:
values = temp[7].split(';')
if values[0].startswith("INDEL"):
continue
for j in values:
if j.startswith("DP4"):
readcounts = j.split(',')
readcounts[0] = readcounts[0][4:]
total_reads =(float(readcounts[0]) + float(readcounts[1]) + float(readcounts[2]) + float(readcounts[3]))
score = 0
if total_reads > 0:
score = (float(readcounts[2]) + float(readcounts[3])) / total_reads
real_count[file] = real_count[file] + 1
depth[file] = depth[file] + total_reads
if ID in scores:
feature_list[file].append(ID)
scores[ID]= score
sum[file] = sum[file] + float(readcounts[2]) + float(readcounts[3])
elif total == 1 and vcf_flag == 0:
format = temp[8].split(':') ##Format
AD_idx = -1
DP_idx = -1
for idx in range(0,len(format)):
if format[idx] == "AD":
AD_idx = idx
elif format[idx] == "DP":
DP_idx = idx
if AD_idx == -1:
continue
if DP_idx == -1:
continue
idx = 9
values = temp[idx].split(":")
readcounts = values[AD_idx].split(',')
if float(readcounts[0]) + float(readcounts[1]) < 0.5:
score =0
else:
score = float(readcounts[1])/ (float(readcounts[0]) + float(readcounts[1]))
depth[file] = depth[file] + float(values[DP_idx])
if float(values[DP_idx]) > 0:
real_count[file] = real_count[file] + 1
if ID in scores:
feature_list[file].append(ID)
scores[ID]= score ##from here!
sum[file] = sum[file] + float(readcounts[1])
else: ###### Haplotyper or other VCF
format = temp[8].split(':') ##Format
AD_idx = -1
DP_idx = -1
for idx in range(0,len(format)):
if format[idx] == "AD":
AD_idx = idx
elif format[idx] == "DP":
DP_idx = idx
if AD_idx == -1:
continue
if DP_idx == -1:
continue
idx = 9
for file in GVCF_samples:
values = temp[idx].split(":")
if len(values) < len(format):
score = 0
idx = idx + 1
continue
readcounts = values[AD_idx].split(',')
if float(readcounts[0]) + float(readcounts[1]) < 0.5:
score =0
else:
score = float(readcounts[1])/ (float(readcounts[0]) + float(readcounts[1]))
depth[file] = depth[file] + float(values[DP_idx])
if float(values[DP_idx]) > 0:
real_count[file] = real_count[file] + 1
if ID in scores:
feature_list[file].append(ID)
score_set[file][ID]= score ##from here!
sum[file] = sum[file] + float(readcounts[1])
idx = idx + 1
## TOTAL is not 1 or total is 1 cases
if total == 1:
mean_depth[file] = depth[file] / float(count)
real_depth[file] = depth[file] / float(real_count[file])
sum_file[file] = sum[file]
for key in features:
if glob_scores.has_key(file):
glob_scores[file].append(scores[key])
else:
glob_scores[file] = [scores[key]]
else:
for file in GVCF_samples:
mean_depth[file] = depth[file] / float(count)
real_depth[file] = depth[file] / float(real_count[file])
sum_file[file] = sum[file]
for key in features:
if key not in score_set[file]:
score_set[file][key] = 0
if glob_scores.has_key(file):
glob_scores[file].append(score_set[file][key])
else:
glob_scores[file] = [score_set[file][key]]
dbsnpf.close()
f.close()
for key in sorted(glob_scores):
label.append(key)
#create dataset from the VCF list files
def createDataSetFromList(base_list, bedFile):
base_F = open(base_list,'r')
for line in base_F.readlines():
link = line.strip()
f = open(link, "r")
dbsnpf= open(bedFile,"r")
file = os.path.basename(link)
depth = dict()
depth[file] = 0
real_count[file] = 0
count = 0
sum=dict()
sum[file] = 0
scores = dict() # Scores of B-allel Frequencies
#DBSNP ID collecting system
for i in dbsnpf.readlines():
temp = i.strip().split('\t')
if temp[0].find("chr")!= -1:
ID = str(temp[0][3:]) + "_" + str(temp[2])
else:
ID = str(temp[0]) + "_" + str(temp[2])
scores[ID] = 0
count = count + 1
## 0618_samtools and haplotyper
vcf_flag = 0
# feature_list[file] = []
score_set = dict()
#VCF file PROCESSING and Generation of features
total = 0
GVCF_samples = dict()
for i in f.readlines():
if i.startswith("#"):
if i.find("DP4") != -1:
vcf_flag = 1
if i.find("#CHROM") != -1:
temp = i.strip().split('\t')
total=len(temp) - 9
if total != 1:
for sample_idx in range(0,total):
file = temp[sample_idx + 9]
GVCF_samples[temp[sample_idx + 9]] = []
score_set[temp[sample_idx + 9]] = dict()
depth[temp[sample_idx + 9]] = 0
real_count[temp[sample_idx + 9]] = 0
sum[temp[sample_idx + 9]] =0
feature_list[temp[sample_idx + 9]] = []
if total == 1:
feature_list[file] = []
continue
temp = i.strip().split('\t')
## ID in BED file only
if temp[0].find("chr")!= -1:
ID = str(temp[0][3:]) + "_" + str(temp[1])
else:
ID = str(temp[0]) + "_" + str(temp[1])
if ID not in scores:
continue
if vcf_flag == 1:
values = temp[7].split(';')
if values[0].startswith("INDEL"):
continue
for j in values:
if j.startswith("DP4"):
readcounts = j.split(',')
readcounts[0] = readcounts[0][4:]
total_reads =(float(readcounts[0]) + float(readcounts[1]) + float(readcounts[2]) + float(readcounts[3]))
score = 0
if total_reads > 0:
score = (float(readcounts[2]) + float(readcounts[3])) / total_reads
real_count[file] = real_count[file] + 1
depth[file] = depth[file] + total_reads
if ID in scores:
feature_list[file].append(ID)
scores[ID]= score
sum[file] = sum[file] + float(readcounts[2]) + float(readcounts[3])
elif total == 1 and vcf_flag == 0:
format = temp[8].split(':') ##Format
AD_idx = -1
DP_idx = -1
for idx in range(0,len(format)):
if format[idx] == "AD":
AD_idx = idx
elif format[idx] == "DP":
DP_idx = idx
if AD_idx == -1:
continue
if DP_idx == -1:
continue
idx = 9
values = temp[idx].split(":")
readcounts = values[AD_idx].split(',')
if float(readcounts[0]) + float(readcounts[1]) < 0.5:
score =0
else:
score = float(readcounts[1])/ (float(readcounts[0]) + float(readcounts[1]))
depth[file] = depth[file] + float(values[DP_idx])
if float(values[DP_idx]) > 0:
real_count[file] = real_count[file] + 1
if ID in scores:
feature_list[file].append(ID)
scores[ID]= score ##from here!
sum[file] = sum[file] + float(readcounts[1])
else: ###### Haplotyper or other VCF
format = temp[8].split(':') ##Format
AD_idx = -1
DP_idx = -1
for idx in range(0,len(format)):
if format[idx] == "AD":
AD_idx = idx
elif format[idx] == "DP":
DP_idx = idx
if AD_idx == -1:
continue
if DP_idx == -1:
continue
idx = 9
for file in GVCF_samples:
values = temp[idx].split(":")
if len(values) < len(format):
score = 0
idx = idx + 1
continue
readcounts = values[AD_idx].split(',')
if float(readcounts[0]) + float(readcounts[1]) < 0.5:
score =0
else:
score = float(readcounts[1])/ (float(readcounts[0]) + float(readcounts[1]))
depth[file] = depth[file] + float(values[DP_idx])
if float(values[DP_idx]) > 0:
real_count[file] = real_count[file] + 1
if ID in scores:
feature_list[file].append(ID)
score_set[file][ID]= score ##from here!
sum[file] = sum[file] + float(readcounts[1])
idx = idx + 1
## TOTAL is not 1 or total is 1 cases
if total == 1:
mean_depth[file] = depth[file] / float(count)
real_depth[file] = depth[file] / float(real_count[file])
sum_file[file] = sum[file]
for key in features:
if glob_scores.has_key(file):
glob_scores[file].append(scores[key])
else:
glob_scores[file] = [scores[key]]
else:
for file in GVCF_samples:
mean_depth[file] = depth[file] / float(count)
real_depth[file] = depth[file] / float(real_count[file])
sum_file[file] = sum[file]
for key in features:
if key not in score_set[file]:
score_set[file][key] = 0
if glob_scores.has_key(file):
glob_scores[file].append(score_set[file][key])
else:
glob_scores[file] = [score_set[file][key]]
dbsnpf.close()
f.close()
for key in sorted(glob_scores):
label.append(key)
def createDataSetFromDir_TEST(base_dir, bedFile,order):
for root, dirs, files in os.walk(base_dir):
for file in files:
if not file.endswith(".vcf"):
continue
link = root + '/' + file
f = open(link, "r")
dbsnpf= open(bedFile,"r")
depth = 0
count = 0
sum = 0
scores = dict() # Scores of B-allel Frequencies
#DBSNP ID collecting system
for i in dbsnpf.readlines():
temp = i.strip().split('\t')
ID = str(temp[0])+"_"+str(temp[2])
scores[ID] = 0
count = count + 1
file = file + "_" + order
feature_list[file] = []
#VCF file PROCESSING and Generation of features
for i in f.readlines():
if i.startswith("#"):
continue
temp = i.split('\t')
values = temp[7].split(';')
if values[0].startswith("INDEL"):
continue
for j in values:
if j.startswith("DP4"):
readcounts = j.split(',')
readcounts[0] = readcounts[0][4:]
score = (float(readcounts[2]) + float(readcounts[3])) / (float(readcounts[0]) + float(readcounts[1]) + float(readcounts[2]) + float(readcounts[3]))
depth = depth + (float(readcounts[0]) + float(readcounts[1]) + float(readcounts[2]) + float(readcounts[3]))
ID = str(temp[0]) + "_" + str(temp[1])
feature_list[file].append(ID)
scores[ID]= score
sum = sum + float(readcounts[2]) + float(readcounts[3])
mean_depth[file] = depth / count
sum_file[file] = sum
for key in features:
if glob_scores.has_key(file):
glob_scores[file].append(scores[key])
else:
glob_scores[file] = [scores[key]]
dbsnpf.close()
f.close()
for key in sorted(glob_scores):
label.append(key)
#create dataset from the VCF list files
def createDataSetFromList_TEST(base_list, bedFile,order):
base_F = open(base_list,'r')
for line in base_F.readlines():
link = line.strip()
f = open(link, "r")
dbsnpf= open(bedFile,"r")
file = link[link.rindex("/")+1:]
depth = 0
count = 0
sum = 0
scores = dict() # Scores of B-allel Frequencies
#DBSNP ID collecting system
for i in dbsnpf.readlines():
temp = i.strip().split('\t')
ID = str(temp[0])+"_"+str(temp[2])
scores[ID] = 0
count = count + 1
file = file + "_" + order
feature_list[file] = []
#VCF file PROCESSING and Generation of features
for i in f.readlines():
if i.startswith("#"):
continue
temp = i.split('\t')
values = temp[7].split(';')
if values[0].startswith("INDEL"):
continue
for j in values:
if j.startswith("DP4"):
readcounts = j.split(',')
readcounts[0] = readcounts[0][4:]
score = (float(readcounts[2]) + float(readcounts[3])) / (float(readcounts[0]) + float(readcounts[1]) + float(readcounts[2]) + float(readcounts[3]))
depth = depth + (float(readcounts[0]) + float(readcounts[1]) + float(readcounts[2]) + float(readcounts[3]))
ID = str(temp[0]) + "_" + str(temp[1])
feature_list[file].append(ID)
scores[ID]= score
sum = sum + float(readcounts[2]) + float(readcounts[3])
mean_depth[file] = depth / count
sum_file[file] = sum
for key in features:
if glob_scores.has_key(file):
glob_scores[file].append(scores[key])
else:
glob_scores[file] = [scores[key]]
dbsnpf.close()
f.close()
for key in sorted(glob_scores):
label.append(key)
# kNN based classification
def clustering(K):
altFreqList = []
keyList = []
Pos_count = 0
for key in sorted(glob_scores):
altFreqList.append(glob_scores[key])
keyList.append(key)
dataSetSize = len(altFreqList)
sum = 0
othersum = 0
for target in range(0,dataSetSize):
dist = []
pheno = []
# comparison to the other samples based on BASE sample
base = altFreqList[target]
tempA = set(feature_list[keyList[target]])
# calculate eucladian distance between two samples
for i in range(0, dataSetSize):
# IsdiffPhenotype = 0.0
comparison = altFreqList[i]
tempB = set(feature_list[keyList[i]])
selected_feature = tempA.intersection(tempB)
# IsdiffPhenotype = (2*len(selected_feature))/(len(tempA) + len(tempB))
vecA = []
vecB = []
idx = 0
for k in features:
if k in selected_feature:
vecA.append(base[idx])
vecB.append(comparison[idx])
idx = idx + 1
distance = pearson_def(vecA, vecB)
dist.append(distance)
# pheno.append(IsdiffPhenotype)
orderCount = 0
while (orderCount < K):
max_value = sorted(dist)[-2-orderCount]
max_indice = dist.index(max_value)
sum = sum + max_value
Pos_count = Pos_count + 1
outPOS=str(label[target]) + "\tmatched to\t" + str(label[max_indice])+ "\tscore=\t" + str(max_value)
print outPOS
#POS_F.write(outPOS + "\n")
orderCount = orderCount + 1
# print sum/Pos_count
#OLD version
def classify(T):
altFreqList = []
keyList = []
Pos_count = 0
Neg_count = 0
POS_F = open("/data/users/sjlee/valid_qc/WGS/SNP/results/TEST2_POS_SNP.txt",'w')
NEG_F = open("/data/users/sjlee/valid_qc/WGS/SNP/results/TEST2_NEG_SNP.txt",'w')
for key in sorted(glob_scores):
altFreqList.append(glob_scores[key])
keyList.append(key)
dataSetSize = len(altFreqList)
sum = 0
othersum = 0
for target in range(0,dataSetSize):
dist = []
pheno = []
# comparison to the other samples based on BASE sample
base = altFreqList[target]
tempA = set(feature_list[keyList[target]])
# calculate eucladian distance between two samples
for i in range(0, dataSetSize):
IsdiffPhenotype = 0.0
comparison = altFreqList[i]
tempB = set(feature_list[keyList[i]])
selected_feature = tempA.intersection(tempB)
IsdiffPhenotype = (2*len(selected_feature))/(len(tempA) + len(tempB))
vecA = []
vecB = []
idx = 0
for k in features:
if k in selected_feature:
vecA.append(base[idx])
vecB.append(comparison[idx])
idx = idx + 1
distance = pearson_def(vecA, vecB)
dist.append(distance)
pheno.append(IsdiffPhenotype)
for value in sorted(dist)[0:-2]:
if abs((Tmean-value)/Tstd) < abs((Fmean-value)/Fstd):
max_value = value
max_indice = dist.index(max_value)
td = array(dist)
sum = sum + max_value
Pos_count = Pos_count + 1
outPOS=str(label[target]) + "\tmatched to\t" + str(label[max_indice])+ "\tscore=\t" + str(max_value) + "\tdiff=\t" + str(pheno[max_indice])
POS_F.write(outPOS + "\n")
else:
max_value = value
max_indice = dist.index(max_value)
othersum = othersum + max_value
Neg_count = Neg_count + 1
outNEG=str(label[target]) + "\tmatched to\t" + str(label[max_indice])+ "\tscore=\t" + str(max_value) + "\tdiff=\t" + str(pheno[max_indice])
NEG_F.write(outNEG + "\n")
print sum/Pos_count
print othersum/Neg_count
POS_F.close()
NEG_F.close()
def classifyNV(vec2Classify, p0Vec, p0S, p1Vec, p1S):
if abs(p0Vec - vec2Classify) - p0S > abs(p1Vec - vec2Classify) - p1S:
return abs((abs(p0Vec - vec2Classify) - p0S )/ (abs(p1Vec - vec2Classify) - p1S )), 1
else:
return abs((abs(p0Vec - vec2Classify) - p0S) / (abs(p1Vec - vec2Classify) - p1S)), 0
# if depth < 5:
# if (vec2Classify >= (p1Vec - p1S)):
# return (abs(p0Vec - vec2Classify) / p0S )/ (abs(p1Vec - vec2Classify)/ p1S ), 1
# else:
# return (abs(p0Vec - vec2Classify) / p0S) / (abs(p1Vec - vec2Classify)/ p1S), 0
# else:
# if (abs(p0Vec - vec2Classify) / p0S > abs(p1Vec - vec2Classify)/ p1S):
# return (abs(p0Vec - vec2Classify) / p0S )/ (abs(p1Vec - vec2Classify)/ p1S ), 1
# else:
# return (abs(p0Vec - vec2Classify) / p0S) / (abs(p1Vec - vec2Classify)/ p1S), 0
def trainNV(trainMatrix,trainCategory):
numTrainDocs = len(trainMatrix) # #of traning samples
p1List = []
p0List = []
for i in range(numTrainDocs):
if trainCategory[i] == 1:
p1List.append(trainMatrix[i])
else:
p0List.append(trainMatrix[i])
return mean(p1List),std(p1List), mean(p0List),std(p0List)
def calAUC(predStrengths, classLabels):
ySum = 0.0 #variable to calculate AUC
cur = (1.0,1.0) #cursor
numPosClas = sum(array(classLabels)==1.0)
yStep = 1/float(numPosClas); xStep = 1/float(len(classLabels)-numPosClas)
sortedIndicies = predStrengths.argsort()#get sorted index, it's reverse
#loop through all the values, drawing a line segment at each point
for index in sortedIndicies.tolist()[0]:
if classLabels[index] == 1:
delX = 0; delY = yStep;
else:
delX = xStep; delY = 0;
ySum += cur[1]
cur = (cur[0]-delX,cur[1]-delY)
return ySum*xStep
#def plotROC(predStrengths, classLabels):
# import matplotlib.pyplot as plt
# cur = (1.0,1.0) #cursor
# ySum = 0.0 #variable to calculate AUC
# numPosClas = sum(array(classLabels)==1.0)
# yStep = 1/float(numPosClas); xStep = 1/float(len(classLabels)-numPosClas)
# sortedIndicies = predStrengths.argsort()#get sorted index, it's reverse
# fig = plt.figure()
# fig.clf()
# ax = plt.subplot(111)
# #loop through all the values, drawing a line segment at each point
# for index in sortedIndicies.tolist()[0]:
# if classLabels[index] == 1:
# delX = 0; delY = yStep;
# else:
# delX = xStep; delY = 0;
# ySum += cur[1]
# #draw line from cur to (cur[0]-delX,cur[1]-delY)
# ax.plot([cur[0],cur[0]-delX],[cur[1],cur[1]-delY], c='b')
# cur = (cur[0]-delX,cur[1]-delY)
# ax.plot([0,1],[0,1],'b--')
# plt.xlabel('False positive rate'); plt.ylabel('True positive rate')
# plt.title('ROC curves')
# ax.axis([0,1,0,1])
# plt.show()
# print "the Area Under the Curve is: ",ySum*xStep
def getPredefinedModel(depth):
if Family_flag:
if depth > 10:
return 0.874611,0.022596,0.644481,0.020908
elif depth > 5:
return 0.785312,0.021318,0.596133,0.022502
elif depth > 2:
return 0.650299,0.019252,0.5346,0.020694
elif depth > 1:
return 0.578582,0.018379,0.495017,0.021652
elif depth > 0.5:
return 0.524757,0.023218,0.465653,0.027378
else:
# print "Warning: Sample region depth is too low < 1"
return 0.524757,0.023218, 0.465653, 0.027378
else:
if depth > 10:
return 0.874546, 0.022211, 0.310549, 0.060058
elif depth > 5:
return 0.785249,0.021017, 0.279778, 0.054104
elif depth > 2:
return 0.650573, 0.018699,0.238972, 0.047196
elif depth > 1:
return 0.578386,0.018526, 0.222322, 0.041186
elif depth > 0.5:
return 0.529327,0.025785, 0.217839, 0.040334
else:
# print "Warning: Sample region depth is too low < 1"
return 0.529327,0.025785, 0.217839, 0.040334
# if depth > 30:
# return 0.874546, 0.022211, 0.310549, 0.060058
# elif depth > 10:
# return 0.785249,0.021017, 0.279778, 0.054104
# elif depth > 5:
# return 0.650573, 0.018699,0.238972, 0.047196
# elif depth > 2:
# return 0.578386,0.018526, 0.222322, 0.041186
# elif depth > 1:
# return 0.529327,0.025785, 0.217839, 0.040334
# else:
# print "Warning: Sample region depth is too low < 1"
# return 0.529327,0.025785, 0.217839, 0.040334
# if depth > 0.1:
# return 0.0351* depth + 0.5538, 0.02, 0.009977*depth + 0.216978, 0.045
# else:
# print "too low depth"
# return 0.529327,0.025785, 0.217839, 0.040334
# if depth > 0.5:
# return 0.06315* (math.log(depth)) + 0.64903, 0.046154, 0.0005007*depth + 0.3311504,0.12216
# else:
# return 0.62036, 0.046154, 0.31785, 0.12216
def getPredefinedModel_F(depth):
if depth > 10:
return 0.874546, 0.022211, 0.620549, 0.060058
elif depth > 5:
return 0.785249,0.021017, 0.609778, 0.054104
elif depth > 2:
return 0.650573, 0.018699,0.548972, 0.047196
elif depth > 1:
return 0.578386,0.018526, 0.502322, 0.041186
elif depth > 0.5:
return 0.529327,0.025785, 0.457839, 0.040334
else:
# print "Warning: Sample region depth is too low < 1"
return 0.529327,0.025785, 0.457839, 0.040334
# if depth > 30:
# return 0.874546, 0.022211, 0.310549, 0.060058
# elif depth > 10:
# return 0.785249,0.021017, 0.279778, 0.054104
# elif depth > 5:
# return 0.650573, 0.018699,0.238972, 0.047196
# elif depth > 2:
# return 0.578386,0.018526, 0.222322, 0.041186
# elif depth > 1:
# return 0.529327,0.025785, 0.217839, 0.040334
# else:
# print "Warning: Sample region depth is too low < 1"
# return 0.529327,0.025785, 0.217839, 0.040334
# if depth > 0.1:
# return 0.0351* depth + 0.5538, 0.02, 0.009977*depth + 0.216978, 0.045
# else:
# print "too low depth"
# return 0.529327,0.025785, 0.217839, 0.040334
# if depth > 0.5:
# return 0.06315* (math.log(depth)) + 0.64903, 0.046154, 0.0005007*depth + 0.3311504,0.12216
# else:
# return 0.62036, 0.046154, 0.31785, 0.12216
def classifying():
AUCs =[]
wholeFeatures = 50
temp =[]
altFreqList = []
keyList = []
for key in sorted(glob_scores):
altFreqList.append(glob_scores[key])
keyList.append(key)
dataSetSize = len(altFreqList)
filter_list = []
for i in range(0, dataSetSize):
for j in range(0, dataSetSize):
if i!=j:
if keyList[j] not in filter_list:
temp.append([keyList[i],keyList[j]])
filter_list.append(keyList[i])
for iterations in range(49,wholeFeatures):
samples = []
numFeatures = iterations
count = 0
for i in range(0,len(temp)):
tempA = set(feature_list[temp[i][0].strip()])
tempB = set(feature_list[temp[i][1].strip()])
selected_feature = tempA.intersection(tempB)
vecA = []
vecB = []
idx = 0
for k in features:
if k in selected_feature:
vecA.append(glob_scores[temp[i][0].strip()][idx])
vecB.append(glob_scores[temp[i][1].strip()][idx])
idx = idx + 1
distance = pearson_def(vecA, vecB)
samples.append(distance)
predStrength = []
training_flag =0
####0715 Append
output_matrix_f = open(outdir + "/" + out_tag + "_output_corr_matrix.txt","w")
output_matrix = dict()
if out_tag!="stdout":
out_f = open(outdir + "/" + out_tag + "_all.txt","w")
out_matched = open(outdir + "/" + out_tag + "_matched.txt","w")
for i in range(0, len(keyList)):
output_matrix[keyList[i]] = dict()
for j in range(0,len(keyList)):
output_matrix[keyList[i]][keyList[j]] = 0
if training_flag == 1:
#make training set
for i in range(0,len(samples)):
trainMatrix= []
trainCategory = []
for j in range(0, len(samples)):
if i==j:
continue
else:
trainMatrix.append(samples[j])
trainCategory.append(classLabel[j])
#training samples in temp
#p0V, p1V, pAb = trainNB0(array(trainMatrix),array(trainCategory))
p1V,p1S, p0V, p0S = trainNV(array(trainMatrix),array(trainCategory))
result = classifyNV(samples[i],p0V,p0S, p1V, p1S)
if result[1] == 1:
print str(temp[i][0]) + '\tsample is matched to\t',str(temp[i][1]),'\t', samples[i]
predStrength.append(result[0])
else :
for i in range(0,len(samples)):
depth = 0
if Nonzero_flag:
depth = min(real_depth[temp[i][0].strip()],real_depth[temp[i][1].strip()])
else:
depth = min(mean_depth[temp[i][0].strip()],mean_depth[temp[i][1].strip()])
p1V,p1S, p0V, p0S = getPredefinedModel(depth)
result = classifyNV(samples[i],p0V,p0S, p1V, p1S)
if result[1] ==1:
output_matrix[temp[i][0].strip()][temp[i][1].strip()] = samples[i]
output_matrix[temp[i][1].strip()][temp[i][0].strip()] = samples[i]
if out_tag=="stdout":
print str(temp[i][0]) + '\tmatched\t',str(temp[i][1]),'\t', round(samples[i],4),'\t',round(depth,2)
else :
out_f.write(str(temp[i][0]) + '\tmatched\t' + str(temp[i][1]) + '\t'+ str(round(samples[i],4)) + '\t' + str(round(depth,2)) + '\n')
out_matched.write(str(temp[i][0]) + '\tmatched\t' + str(temp[i][1]) + '\t'+ str(round(samples[i],4)) + '\t' + str(round(depth,2)) + '\n')
else:
if out_tag=="stdout":
print str(temp[i][0]) + '\tunmatched\t',str(temp[i][1]),'\t', round(samples[i],4),'\t',round(depth,2)
else :
out_f.write(str(temp[i][0]) + '\tunmatched\t' + str(temp[i][1]) + '\t'+ str(round(samples[i],4)) + '\t' + str(round(depth,2)) + '\n')
predStrength.append(result[0])
#testing sample is samples
output_matrix_f.write("sample_ID")
for key in output_matrix.keys():
if key.find(".vcf") != -1:
output_matrix_f.write("\t" + key[0:key.index('.vcf')])
else:
output_matrix_f.write("\t" + key)
output_matrix_f.write("\n")
# for key in output_matrix.keys():
# for otherkey in output_matrix[key].keys():
# if output_matrix[key][otherkey] != 0:
# output_matrix[otherkey][key] = output_matrix[key][otherkey]
for key in output_matrix.keys():
if key.find(".vcf") != -1:
output_matrix_f.write(key[0:key.index('.vcf')])
else:
output_matrix_f.write(key)
for otherkey in output_matrix.keys():
output_matrix_f.write("\t" + str(output_matrix[key][otherkey]))
output_matrix_f.write("\n")
output_matrix_f.close()
if out_tag!="stdout":
out_f.close()
out_matched.close()
def classifying_test():
AUCs =[]