-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathParseBlast.py
More file actions
executable file
·5149 lines (4539 loc) · 143 KB
/
ParseBlast.py
File metadata and controls
executable file
·5149 lines (4539 loc) · 143 KB
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/local/bin/python
#-------------------------------------------------------------------------------
# Project: pHOG
# Class: ParseBlast.py
# Desc.: This class is responsible for talking to the database for cluster
# related operations
# Modification history
# 25.05,02
# Created
# 03,06,02
# Problem with inconsistent accessions in sputnik and in blast database.
# Sputnik delete "." and "-" in accessions then store in pep_sputnik. This
# created a hugh problem in clustering. Implement check_acc() to check the con-
# sistency of the parsed file. This checking mechanism shold be implemented
# in a planned full blast parser.
# 07.06,02
# Implement get_cluster_scores()
# 15/06,02
# Implement apply_threshold() and modify get_cluster_scores() so it will
# calculate the log value unlike that of tribe-parse.pl. The output of
# get_cluster_score() will be:
# [seq1]\t[seq2]\t[evalue]\t[-log10(evalue)]
# 10.07,02
# Finish get_score_for_npc().
# 18.07,02
# Memory problem for large matrices in get_score_for_npc(). With > 1M scores,
# ca. 750MB memory is taken.
# 25,07,02
# Realize that I got the name wrong. It should be SPC not NPC.
# 02.08,02
# Implement get_selected_scores().
# 08/17,02
# Change back to US-based date system. Implement extract_cds()
# 09/03.02
# Bug in extract_cds(). For mutiple matching area between a query and a subj,
# the different matching areas are merged and the coordinates are wrong. Fixed.
# 09/08,02
# Bug in extract_cds(). There are cases where matches can be found in both
# orientation. In this situation, implement a mechanism that will take only
# the orientation of the majority
# 09/10,02
# Modify parse_blast_file() and symmetrify() to allow the use of percentID
# or percentSIM.
# 09/18,02
# Some names are longer than 10 char. Need to truncate them and generate an
# output for a list of modified genes.
# 09/23,02
# Some self score is less than 100%, somehow I decided that the normalization
# in symmetrify should use the smaller self score of the pair. Don't understand
# the logic behind that... The result is that, some negative scores is present
# due to that after normalization. To eliminate this artifact and to be
# conservative in the estimate, the score used should be the higher one.
# 10/10,02
# Implement parse_alignment
# 10/19,02
# Modify symmetrify, for a pair m,n, the score for (m,n) is found but not (n,m)
# in this case, (n,m) will be set to (m,n) instead of 0.
# 01/15,03
# How do parse_table deal with situations with multiple matches? Actually, it
# is symmetrify who make the decision. It takes the top score.
# 02/25,03
# Bugs in parse_align. Query line disappears. End of line char problem. Fixed.
# Has to make sure that get_qualified still works.
# 06/30,03
# Problem with symmetrify. The paires that do not have score need to be 0.
# 08/08,03
# Implement match_fam
# 08/27,03
# In symmetrifym cases exist where self score is smaller than the default
# cutoff. The self scores were discarded by mistake. Fix this.
# 11/12,03
# Need to deal with WashU blast output for the first time. Accommondate only
# in extract_cds at this point. It seems the major difference is the spacing
# between Sbjct: or Query: to the L coordinates.
# 06/10,04
# A bug in parse_table. The evalue part is not done. And both evalue and ident
# -based filterings doesn't take care of multiple hit problem (ie multiple
# a-b hits). Dealt with.
# 07/09/09
# Gaurav found couple bugs in Chain.
#-------------------------------------------------------------------------------
import sys, math, SingleLinkage, FastaManager, FileUtility, string, os
try:
import DatabaseOp
except ImportError:
print ("\nNOTE: DatabaseOp not imported")
class parser:
def __init__(self, dbtask="", config=""):
self.dbtask = dbtask
self.config = config
def for_mega(self,bdir,fasta):
if bdir[-1] != "/":
bdir += "/"
print ("1. blast...")
#os.system("%sformatdb -i %s" % (bdir,fasta))
#os.system("%sblastall -p blastp -d %s -i %s " % (bdir,fasta,fasta) + \
# "-o %s.out -F F -v 0 -b 5000 -m 8" % fasta)
print ("2. deal with blast score...")
self.parse_table("%s.out" % fasta,"evalue",T=1,wself=1)
self.symmetrify("%s.out_T1_evalue.parse" % fasta)
self.mega_score("%s.out_T1_evalue_c0h0.sym" % fasta)
print ("Done!")
##
# This function checks if subjects are more closely related to members of
# a particular family. Comparison is done based on evalue.
#
# @param blast blast output, tabular format
# @param matrix family assignment with [seq_id][fam]
# @param target the target family
# @param unknown the ones with unknown groups are query[1, default] or
# subj[0]
##
def match_fam(self,blast,matrix,target,unknown=0):
# read matrix into dict
matrix = futil.file_to_dict(matrix,1)
inp = open(blast,"r")
inl = inp.readline()
# first get top matches, subj as key, [query,pid,evalue] as value
# if unknown is set at 0. Other wise, query as key.
sdict = {}
print ("Get top matches...")
while inl != "":
llist = inl.split("\t")
query = llist[0]
subj = llist[1]
pid = float(llist[2])
evalue = llist[-2]
changed = 0
if unknown:
if(not sdict.has_key(query) or
(sdict.has_key(query) and pid > sdict[query][1])):
sdict[query] = [subj,pid,evalue]
changed = 1
else:
if(not sdict.has_key(subj) or
(sdict.has_key(subj) and pid > sdict[subj][1])):
sdict[subj] = [query,pid,evalue]
changed = 1
inl = inp.readline()
# check query group and output subj, query, percentID, evalue
print ("Match targets and generate output...")
oup = open(blast+"."+target,"w")
for i in sdict.keys():
#try:
if matrix[sdict[i][0]] == target:
oup.write("%s\t%s\t%i\t%s\n" % \
(i,sdict[i][0],sdict[i][1],sdict[i][2]))
#except KeyError:
# print "Are you sure you set in unknown flag right??"
# print "QUIT!!"
# sys.exit(0)
print ("Done!")
##
# Format e values for Super-Paramagnetic Clustering (SPC). The input file has
# to conform to the following format:
#
# seq1<space>coord1L<->coord1R<\t>seq2<space>coord2L<->coord2R<\t>e_value
#
# Three output files will be generated. The first is ".spc" or ".spc.h", de-
# pends on whether homogenization is done or notm. It looks the same as input
# except that:
#
# 1. evalue is replaced by normalized, symmetrified score
# 2. the score is stored in matrix-like format, where score for 1-2 is stor-
# ed but not 2-1.
# 3. The seq name is relaced by index numbers
#
# The second file is: seq_name<\t>index
#
# The third file is log file with running parameter and a list for sequences
# not included in the score file due to the rules applied in the codes.
#
# @param outbase output base name
# @param score_dict from the FastaOutIO.get_scores(). This will be based on
# dissimilarity matrix.
# @param per_id number of top score VALUES to retrieve for each gene,
# defailt is 0, which will retrieve all scores. It is
# expected that some will have the same scores.
# @param matrix score output in what kind of matrix
# 0 - dissimilarity matrix, similar from 0 to dissimilar 1
# 1 - similarity matrix, similar from 1 to dissimilar 0
# @param homogenize to make the scores more linearly distributed. At default
# 0 - no homogenization
# 1 - homogenized by applying square of the value
##
def get_scores_for_spc(self,score_file,outbase,per_id=10,homogenize=0):
print ("\nGenerate score file for Non-parametric clustering:")
##
# Set default values
##
MAX_SCORE = 200
MIN_SCORE = 0
if outbase == "":
outbase = score_file
oup3 = open(outbase+"_p%ih%i.log" % (per_id,homogenize),"w")
oup3.write("ParseBlast.py get_score_for_spc")
oup3.write(" score_file= %s\n" % score_file)
oup3.write(" outbase = %s\n" % outbase)
oup3.write(" per_id = %i\n" % per_id)
oup3.write(" homogenize= %i\n\n" % homogenize)
print ("Convert e value, apply threshold...\n")
# convert e value into -log10(e)
inp = open(score_file,"r")
# idx1+" "+idx2 as key, [len1, len2, -log10(e)] as value
score_dict = {}
# idx as key, included in final output [1] or not [0] as value
name_dict = {}
inline = inp.readline()
while inline != "":
llist = inline.split("\t")
idx1 = llist[0]
len1 = int(idx1[idx1.find("-")+1:]) - \
int(idx1[idx1.find(" ")+1:idx1.find("-")]) + 1
idx2 = llist[1]
len2 = int(idx2[idx2.find("-")+1:]) - \
int(idx2[idx2.find(" ")+1:idx2.find("-")]) + 1
if not name_dict.has_key(idx1):
name_dict[idx1] = 0
if not name_dict.has_key(idx2):
name_dict[idx2] = 0
# convert scores to -log10
score = llist[2][:-1]
if score[0] == "e":
try:
score = -math.log10(float("1"+score))
except OverflowError:
print ("OVERFLOW:",idx1,idx2,score)
inline = inp.readline()
continue
elif score == "0.0":
score = MAX_SCORE
else:
try:
score = -math.log10(float(score))
except OverflowError:
print ("OVERFLOW:",idx1,idx2,score)
inline = inp.readline()
continue
except ValueError:
print ("ValueError:",idx1,idx2,score)
inline = inp.readline()
continue
# apply threshold
if score < MIN_SCORE:
inline = inp.readline()
continue
# homogenize score to its square root
if homogenize:
score_dict[idx1+"_"+idx2] = [len1,len2,math.sqrt(score)]
else:
score_dict[idx1+"_"+idx2] = [len1,len2,score]
inline = inp.readline()
print ("Symmetrify and normalize scores...\n")
# symmetrify and normalize score with self score and len of longer entry
# notice that tscore has different format from that of score_dict
tscores = {}
keys = score_dict.keys()
for i in keys:
idx1 = i[:i.find("_")]
idx2 = i[i.find("_")+1:]
# this key may not exist because it is deleted after processing
# idx2_idx1 previously, if so, skip
if score_dict.has_key(idx1+"_"+idx2):
score12 = score_dict[i][2]
else:
continue
# if reciprocal score is not present, this entry is ignored
if score_dict.has_key(idx2+"_"+idx1):
len1 = score_dict[i][0]
len2 = score_dict[i][1]
score21 = score_dict[idx2+"_"+idx1][2]
else:
continue
# symmetrify
score = (score12+score21)/2
# normalize
if len1 >= len2:
selfL = score_dict[idx1+"_"+idx1][2]
else:
selfL = score_dict[idx2+"_"+idx2][2]
score = score/selfL
# delete score_dict element, but don't delete self scores
if idx1 != idx2:
del score_dict[i]
del score_dict[idx2+"_"+idx1]
if score > 1:
print ("Score bigger than 1:",idx1,idx2,score)
score = 1
# construct transformed score dict
if not tscores.has_key(idx1):
tscores[idx1] = [[idx2],[score]]
else:
if not idx2 in tscores[idx1][0]:
tscores[idx1][0].append(idx2)
tscores[idx1][1].append(score)
if not tscores.has_key(idx2):
tscores[idx2] = [[idx1],[score]]
else:
if not idx1 in tscores[idx2][0]:
tscores[idx2][0].append(idx1)
tscores[idx2][1].append(score)
del score_dict
# reconstruct tscores based on per_id if it is bigger than 0. The self
# scores will not be included, which is always 1.
if per_id != 0:
print ("Get top %i scores...\n" % per_id)
for i in tscores.keys(): # match for each index
#print i
# map scores, score as key, index of score in the list as value
map = {}
for j in range(len(tscores[i][1])):
if not map.has_key(tscores[i][1][j]):
map[tscores[i][1][j]] = [j]
else:
map[tscores[i][1][j]].append(j)
#print " map_dict:",map
order = map.keys()
order.sort()
order.reverse()
#print " sorted score:",order
# rank -> order index -> order element -> map key -> map value:
# tscore[0] index
# tscore[1] index
ilist = []
slist = []
for j in range(1,per_id+1):
if j<len(order):
score = order[j]
members = map[score]
for k in members:
ilist.append(tscores[i][0][k])
slist.append(score)
else:
break
tscores[i] = [ilist,slist]
# check reciprocity, build index dict, and generate output
print ("Check reciprocity, generate output...\n")
idx_dict = {}
count = 0
oup1 = open(outbase+"_p%ih%i.idx" % (per_id,homogenize),"w")
oup2 = open(outbase+"_p%ih%i.spc" % (per_id,homogenize),"w")
pairs = {}
for i in tscores.keys():
for j in range(len(tscores[i][0])):
index = tscores[i][0][j]
score = tscores[i][1][j]
# check if tscores[index] has i as a score
if i in tscores[index][0]:
if not idx_dict.has_key(i):
idx_dict[i] = count
name_dict[i] = 1
oup1.write("%s\t%i\n" % (i,count))
count = count +1
if not idx_dict.has_key(index):
idx_dict[index] = count
name_dict[index] = 1
oup1.write("%s\t%i\n" % (index,count))
count = count+1
# Output as full name
#oup2.write("%s\t%s\t%f\n" % (i,
# index,
# score))
# Output as index number and as a matrix
if(not pairs.has_key(i+"_"+index) and
not pairs.has_key(index+"_"+i)):
oup2.write("%i\t%i\t%f\n" % (idx_dict[i],
idx_dict[index],
score))
pairs[i+"_"+index] = 1
else:
continue
del tscores
oup3.write("Singletons:\n")
count = 0
for i in name_dict.keys():
if name_dict[i] == 0:
oup3.write(" "+i+"\n")
count = count+1
oup3.write("Total = %i" % count)
print ("Done!\n")
sys.exit(0)
##
# Take the output of parse_blast_file() or parse_blast_db(), perform some
# operation to get MCL input file. Notice that NO normalization is done over
# here.
#
# @param outbase output base name
# @param score_file from the parse_db() or parse_file.
# @param cutoff evalue cutoff
# @param homogenize to make the scores more linearly distributed. At default
# 0 - no homogenization
# 1 - homogenized by applying square of the value
##
def get_scores_for_mcl(self,score_file,outbase,cutoff=1,homogenize=0):
if outbase == "":
outbase = score_file
inp = open(score_file,"r")
oup = open(outbase+".idx","w")
# construct index
idx = {}
c = 0
o_scores = {}
print ("Construct idx and score dict...")
inline = inp.readline()
countS = 0
while inline != "":
if countS % 100000 == 0:
print (" %i x 100k" % (countS/100000))
countS += 1
lnlist = inline.split("\t")
# check number of column
if len(lnlist) != 3:
print ("Score format problem: should be [query][subj][-log(e)]")
print ("Quit!")
sys.exit(0)
if not idx.has_key(lnlist[0]):
idx[lnlist[0]] = c
oup.write("%i\t%s\n" % (c,lnlist[0]))
c = c+1
if not idx.has_key(lnlist[1]):
idx[lnlist[1]] = c
oup.write("%i\t%s\n" % (c,lnlist[1]))
c = c+1
if not o_scores.has_key(lnlist[0]):
# apply cutoff
if float(lnlist[2]) >= cutoff:
o_scores[lnlist[0]] = {lnlist[1]:float(lnlist[2])}
else:
# apply cutoff
if float(lnlist[2]) >= cutoff:
# more than one scores, take the largest one
if o_scores[lnlist[0]].has_key(lnlist[1]):
if float(lnlist[2]) > o_scores[lnlist[0]][lnlist[1]]:
o_scores[lnlist[0]][lnlist[1]] = float(lnlist[2])
else:
o_scores[lnlist[0]][lnlist[1]] = float(lnlist[2])
inline = inp.readline()
##
# SET DIMENSION
##
D = c
inp.close()
oup.close()
# symmetrify scores
s_scores = {}
okeys = o_scores.keys()
print ("Symmetrify scores...")
countS = 0
for i in okeys:
if countS % 1e4 == 0:
print (" %i x 10k" % (countS/1e4))
countS+= 1
oikeys = o_scores[i].keys()
for j in oikeys:
#print "",idx[j]
# check backward score, if absent, this match will be discarded
score = 0
if o_scores.has_key(j) and o_scores[j].has_key(i):
if o_scores[i][j] == o_scores[j][i]:
score = o_scores[i][j]
else:
score = (o_scores[i][j]+o_scores[j][i])/2.0
del o_scores[j][i]
if i != j:
del o_scores[i][j]
# apply cutoff, homogenize if necessary
if score != 0:
if homogenize:
score = math.sqrt(score)
if s_scores.has_key(idx[i]):
if not s_scores[idx[i]].has_key(idx[j]):
#print " add1:",idx[j],"to",idx[i],score
s_scores[idx[i]][idx[j]] = score
else:
#print " add2:",idx[j],"to",idx[i],score
s_scores[idx[i]] = {idx[j]:score}
if s_scores.has_key(idx[j]):
if not s_scores[idx[j]].has_key(idx[i]):
#print " add3:",idx[i],"to",idx[j],score
s_scores[idx[j]][idx[i]] = score
else:
#print " add4:",idx[i],"to",idx[j],score
s_scores[idx[j]] = {idx[i]:score}
#else:
# print " below_cutoff"
o_scores = {}
#for i in s_scores:
# print i
# print s_scores[i]
# write mcl file
print ("Generate output file...")
oup = open(outbase+".mci","w")
oup.write("(mclheader\nmcltype matrix\ndimensions %ix%i\n)\n" % (D,D))
oup.write("(mclmatrix\nbegin\n")
for i in s_scores.keys():
oup.write("%i " % i)
for j in s_scores[i]:
s = str(s_scores[i][j])
oup.write("%i:%s " % (j,s[:s.find(".")+4]))
#scores = str(s_scores[i][1][j])
#out_str = out_str + "%i:%s " % (s_scores[i][0][j],
# scores[:scores.find(".")+4])
oup.write("$\n")
# add singletons
for i in range(D):
if not s_scores.has_key(i):
score = 200.0
if homogenize:
score = math.sqrt(score)
oup.write("%i %i:%f $\n" % (i,i,score))
oup.write(")")
print ("Close outputstream...")
oup.close()
print ("Done!")
##
# Common operation on scores:
# 1. symmetrification - so Sab = Sba
# 2. cutoff - apply cutoff
# 3. normalization - normalize by smaller self
# 4. homogenization - apply sqare on normalized -log(E) value
#
# Assume the score is in the last token of the line
#
# @param score_file file generated by parse_blast_file or parse_blast_db
# @output xxx_cxhx.sym file name include the cutoff value and homogenization
# option. Contains [seq1][seq2][symmed score]
##
def symmetrify(self,score_file,outbase="",cutoff=0,homogenize=0):
oup_log = open(score_file+"_sym.log","w")
print ("Construct score dict...")
o_scores = {}
inp = open(score_file,"r")
inline = inp.readline()
c = 0
ndict = {}
print ("Processed lines:")
oup_log.write("More than one scores:\n")
while inline != "":
if c % 100000 == 0:
print (" %ix100k" % (c/100000))
c += 1
# [seq1][seq2][E][-log(E)] or [seq1][seq2][-][percentID or SIM]
lnlist = inline.split("\t")
# assuming score is in the last token
lnlist[-1] = self.rmlb(lnlist[-1])
# store id into dict
if not ndict.has_key(lnlist[0]):
ndict[lnlist[0]] = 0
if not ndict.has_key(lnlist[1]):
ndict[lnlist[1]] = 0
if not o_scores.has_key(lnlist[0]):
o_scores[lnlist[0]] = {lnlist[1]:float(lnlist[-1])}
else:
# more than one scores, take the largest one
if o_scores[lnlist[0]].has_key(lnlist[1]):
oup_log.write(" %s,%s %f -> %s\n" % \
(lnlist[0],
lnlist[1],
o_scores[lnlist[0]][lnlist[1]],
lnlist[-1]))
if float(lnlist[-1]) > o_scores[lnlist[0]][lnlist[1]]:
o_scores[lnlist[0]][lnlist[1]] = float(lnlist[-1])
else:
o_scores[lnlist[0]][lnlist[1]] = float(lnlist[-1])
inline = inp.readline()
print ("Apply cutoff...")
okeys = o_scores.keys()
selfC = 0
oup_log.write("\nSelf score below cutoff at %i:\n" % cutoff)
for i in okeys:
jkeys = o_scores[i].keys()
for j in jkeys:
if o_scores[i][j] < cutoff:
# for log
if i == j:
oup_log.write(" %s\t%f\n" % (i,o_scores[i][i]))
selfC += 1
o_scores[i][j] = cutoff
print (" %i self score below cutoff %i" % (selfC,cutoff))
print ("Symmetrify and normalize scores...")
s_scores = {}
print ("Process total %i taxa:" % len(okeys))
c = 0
oup_log.write("\nNot in score dict, most likely not in BLAST file:\n")
for i in okeys:
if c % 10 == 0:
print ("",c+1)
c += 1
oikeys = o_scores[i].keys()
for j in oikeys:
score = 0
if o_scores.has_key(j):
if o_scores[j].has_key(i):
# at the moment, score is -log(E), except if absent
if o_scores[i][j] == o_scores[j][i]:
score = o_scores[i][j]
else:
score = (o_scores[i][j]+o_scores[j][i])/2.0
else:
o_scores[j][i] = o_scores[i][j]
score = o_scores[i][j]
t_score = score
# check if scores are missing, if so, add self score as cutoff
if o_scores.has_key(i):
if o_scores[i].has_key(i):
pass
else:
print ("Self score missing:",i)
print ("Did you parse the table -wself 1? QUIT!")
sys.exit(0)
else:
print (" score dict misses:",i)
oup_log.write(" %i" % i)
o_scores[i] = {i:cutoff}
#print "Quit!"
#sys.exit(0)
if o_scores.has_key(j):
if o_scores[i].has_key(j):
pass
else:
print ("Self score missing:",j)
print ("Did you parse the table -wself 1? QUIT!")
sys.exit(0)
else:
print (" score dict misses:",[j])
oup_log.write(" %s" % j)
o_scores[j] = {j:cutoff}
#print "Quit!"
#sys.exit(0)
# normalize, make sure not divided by zero
if o_scores[i][i] >= o_scores[j][j]:
if o_scores[i][i] == 0:
score = 1.0
else:
score = 1.0 - score/o_scores[i][i]
else:
if o_scores[j][j] == 0:
score = 1.0
else:
score = 1.0 - score/o_scores[j][j]
# homogenize by
if homogenize > 0 and score != 0:
if homogenize == 1:
score = score*score # multiplication
elif homogenize == 2:
score = math.sqrt(score) # square root
if s_scores.has_key(i):
if not j in s_scores[i][0]:
s_scores[i][0].append(j)
s_scores[i][1].append(score)
else:
s_scores[i] = [[j],[score]]
if s_scores.has_key(j):
if not i in s_scores[j][0]:
s_scores[j][0].append(i)
s_scores[j][1].append(score)
else:
s_scores[j] = [[i],[score]]
#print i,j,t_score,score,o_scores[i][i],o_scores[j][j]
if outbase == "":
outbase = score_file[:score_file.rfind(".")]
outbase = "%s_c%ih%i" % (outbase,cutoff,homogenize)
oup = open(outbase+".sym","w")
print ("Generate output: %s" % (outbase+".sym"))
for i in s_scores.keys():
for j in range(len(s_scores[i][0])):
oup.write("%s\t%s\t%f\n" % (i,
s_scores[i][0][j],
s_scores[i][1][j]))
print ("Closing output stream...")
oup.close()
print ("Done!")
def sym2(self,score):
# Not done!
inp = open(score)
inl = inp.readline()
S = {}
while inl != "":
L = inl.split("\t")
if L[0] not in S:
if L[1] not in S:
S[L[0]] = {L[1]:float(L[-1])}
S[L[1]] = {L[0]:float(L[-1])}
elif L[0] not in S[L[1]]:
S[L[0]] = {L[1]:float(L[-1])}
S[L[1]] = {L[0]:float(L[-1])}
else:
S[L[0]][L[1]] = (S[L[0]][L[1]]+ float(L[-1]))/2.0
S[L[1]][L[0]] = (S[L[1]][L[0]]+ float(L[-1]))/2.0
elif L[1] not in S[L[0]]:
S[L[0]][L[1]] = float(L[-1])
if L[1] not in S:
S[L[1]] = {L[0]:float(L[-1])}
elif L[0] not in S[L[1]]:
S[L[1]][L[0]] = float(L[-1])
inl = inp.readline()
##
# This will get the score for use in the neighbor program from Phylip. The
# format is:
#
# number of taxa
# seq1 self S12 S13 S14...
# seq2 S12 self S23 S24...
# ...
#
# The score matrix is similarity matrix. Self is 0. So things need to be
# normalized somehow. The scores also need to be symmetrified. The method
# symmetrify will generate score suitable.
#
# Only the first 6 char of the score will be taken so the precision to: 0.0001
#
# @param sym_score symmetrified score file generated by symmetrify
# @output xxx.neighbor As explained above.
##
def get_scores_for_neighbor(self,sym_score):
# generate a nested dict for score
# generate a dict for index
scores = {}
index = {}
inp = open(sym_score,"r")
inline = inp.readline()
print ("Generate score dict...")
c = 0
while inline != "":
if c % 100000 == 0:
print (" %ix100k" % (c/100000))
c += 1
llist = inline.split("\t")
llist[2] = llist[2][:6]
if not index.has_key(llist[0]):
index[llist[0]] = 1
if not index.has_key(llist[1]):
index[llist[1]] = 1
if not scores.has_key(llist[0]):
scores[llist[0]] = {llist[1]:llist[2]}
else:
scores[llist[0]][llist[1]] = llist[2]
if not scores.has_key(llist[1]):
scores[llist[1]] = {llist[0]:llist[2]}
else:
scores[llist[1]][llist[0]] = llist[2]
inline = inp.readline()
oup = open(sym_score+".neigh","w")
sline = ""
ikeys = index.keys()
oup.write(" %i\n" % len(ikeys))
print ("Write scores...")
for i in index.keys():
#print i
count = 0
for j in ikeys:
count = count + 1
if scores[i].has_key(j):
sline = sline + scores[i][j] + " "
else:
sline = sline + "1.0000 "
if len(i)>10:
print ("The identifier is longer than 10 characters.")
print ("Should run index_names\nExit!")
sys.exit(0)
else:
oup.write(i+(10-len(i))*" "+sline[:-2]+"\n")
sline = ""
print ("Done!")
##
# This will generate a score matrix for MEGA. The format is like:
#
# #mega
# ! Title: something;
# ! Format DataType=distance;
#
# #taxa1
# #taxa2
# #...
#
# d12 d13 d14 ...
# d23 d24 ...
# ...
#
# Input file should have 3 or more columns:
# Seq1<\t>Seq2<\t>....<\t>Distance
# Distance has to be between 0 and 1.
##
def mega_score(self,sym_score):
# generate a nested dict for score
# generate a dict for index
scores = {}
index = {}
inp = open(sym_score,"r")
inline = inp.readline()
print ("Generate score dict...")
c = 0
while inline != "":
if c % 100000 == 0:
print (" %ix100k" % (c/100000))
c += 1
llist = self.rmlb(inline).split("\t")
#llist[2] = llist[2][:6]
if not index.has_key(llist[0]):
index[llist[0]] = 1
if not index.has_key(llist[1]):
index[llist[1]] = 1
if not scores.has_key(llist[0]):
scores[llist[0]] = {llist[1]:llist[-1]}
else:
scores[llist[0]][llist[1]] = llist[-1]
if not scores.has_key(llist[1]):
scores[llist[1]] = {llist[0]:llist[-1]}
else:
scores[llist[1]][llist[0]] = llist[-1]
inline = inp.readline()
oup = open(sym_score+".meg","w")
oup.write("#mega\n!Title %s;\n"%sym_score + \
"!format DataType=distance DataFormat=upperright;\n\n")
print ("Write taxa...")
ikeys = index.keys()
ikeys.sort()
for i in ikeys:
oup.write("#%s\n" % i)
oup.write("\n")
# don't need self, only upper half matrix
print ("Write scores...")
sline = ""
for i in range(len(ikeys)):
#print i
for j in range(i+1,len(ikeys)):
if scores[ikeys[i]].has_key(ikeys[j]):
sline = sline + scores[ikeys[i]][ikeys[j]] + " "
else:
sline = sline + "1.0000 "
oup.write(" "+sline[:-2]+"\n")
sline = ""
print ("Close output stream...")
oup.close()
print ("Done!" )
#
# Take symmetrified score file and generate a score matrix.
#
def score_matrix(self, score):
print ("Read scores into a dictionary...")
D = {} #{id1:{id2:score}}
inp = open(score)
inl = inp.readline()
while inl != "":
[id1,id2,S] = inl.strip().split("\t")
if id1 not in D:
D[id1] = {id2:S}
elif id2 not in D[id1]:
D[id1][id2] = S
if id2 not in D:
D[id2] = {id1:S}