-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathevolclust.py
1703 lines (1607 loc) · 58.7 KB
/
evolclust.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
"""
Evolclust v1.01 - automated pipeline to detect regions of conserved gene
order using comparative genomics.
Copyright (C) 2017 - Marina Marcet-Houben, Toni Gabaldon
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import argparse
import glob
import numpy
import os
from random import randint
from random import shuffle
import subprocess as sp
import sys
import gzip
from datetime import datetime
import itertools
startTime = datetime.now()
########################################################################
# Operational modules
########################################################################
#Checks whether a folder exists or else creates it
def create_folder(name):
if not os.path.exists(name):
cmd = "mkdir "+name
try:
run_command(cmd,False)
except:
print "Unable to create directory ",name
#Run a bash command
def run_command(cmd,ommit):
if ommit:
try: process = sp.Popen(cmd,shell=True)
except: pass
process.communicate("Y\n")
if process.wait() != 0: print "Error ocurred, but you chose to ommit it"
else:
try: process = sp.Popen(cmd,shell=True)
except OSError,e: sys.exit("Error: Execution cmd failed")
process.communicate("Y\n")
if process.wait() != 0: sys.exit("ERROR: Execution cmd failed")
########################################################################
# Load information modules
########################################################################
#Load clusters into memory
def load_clusters(fileName):
refClusters = {}
species = set([])
for line in open(fileName):
line = line.strip()
dades = line.split("\t")
spe = dades[0].split("_")[1]
species.add(spe)
refClusters[dades[0]] = dades[1].split(";")
return refClusters,species
#Load predicted clusters into memory
def load_cluster_families(fileName):
clusters = {}
num = 1
for line in open(fileName):
line = line.strip()
dades = line.split()
if len(dades) > 1:
code = "CF_%.6d" %(num)
num += 1
clusters[code] = {}
for name in dades:
spe = name.split("_")[1]
if spe not in clusters[code]:
clusters[code][spe] = []
clusters[code][spe].append(name)
return clusters
#Load conversion files into memory
def load_conversion(dirName,species):
conversion = {}
for code in species:
fileName = dirName+"/"+code+".txt"
conversion[code] = {}
for line in open(fileName):
line = line.strip()
dades = line.split()
contig = dades[0].split("_")[1]
if contig not in conversion[code]:
conversion[code][contig] = {}
conversion[code][contig][dades[0]] = dades[1]
return conversion
#Load homologous pairs of proteins into memory
def load_pairs(spe1,spe2,outDir):
fileName = outDir+"/"+spe1+"/"+spe2+".txt.gz"
if os.path.exists(fileName):
pairs = []
for line in gzip.open(outDir+"/"+spe1+"/"+spe2+".txt.gz"):
line = line.strip()
dades = line.split()
p = dades[2]+"-"+dades[3]
pairs.append(p)
else:
pairs = []
return pairs
########################################################################
#Build files
########################################################################
#Create the conversion files between the protein names and the number of the family they belong in
def build_conversion_files(fileName,outDir):
info = {}
num = 1
for line in open(fileName):
line = line.strip()
dades = line.split()
for d in dades:
spe = d.split("_")[0]
if d.count("_") != 2:
pass
if spe not in info:
info[spe] = {}
info[spe][d] = str(num)
num += 1
for code in info:
outfile = open(outDir+"/"+code+".txt","w")
genes = info[code].keys()
genes = sorted(genes,key=lambda x: int(x.split("_")[2]))
for gene in genes:
print >>outfile,gene+"\t"+info[code][gene]
outfile.close()
#Creates a list of all the proteins
def build_complete_protein_list(fileName,outfileName):
outfile = open(outfileName,"w")
for line in open(fileName):
line = line.strip()
if ">" in line:
print >>outfile,line.replace(">","")
outfile.close()
#Creates a full list of pairwise homologous genes according to the mcl
def build_pairs(fileName,outDir):
species = {}
info = {}
num = 1
for line in open(fileName):
line = line.strip()
codes = line.split("\t")
if len(codes) > 1:
info[num] = codes
for c in codes:
s = c.split("_")[0]
if s not in species:
species[s] = {}
species[s][c] = num
num += 1
for spe in species:
outfolder = outDir+"/"+spe
create_folder(outfolder)
pairs = {}
for code in species[spe]:
num = species[spe][code]
for name in info[num]:
s = name.split("_")[0]
if s not in pairs:
pairs[s] = set([])
p = code+"-"+name
pairs[s].add(p)
for s in pairs:
outfile = open(outfolder+"/"+s+".txt","w")
for p in pairs[s]:
print >>outfile,spe,s,p.split("-")[0],p.split("-")[1]
outfile.close()
cmd = "gzip "+outfolder+"/"+s+".txt"
run_command(cmd,False)
#Creates jobs list that will automatize the process
def create_jobs(outDir,tagName,thrMode):
#Create folder
outJob = outDir+"/jobs/"
create_folder(outJob)
if tagName == "initial":
#Obtain a list of all the species
species = []
for fileName in glob.glob(outDir+"/pairs_files/*"):
code = fileName.split("/")[-1]
species.append(code)
#For each pair of species
outfile = open(outJob+"jobs.step1.txt","w")
for i in range(0,len(species)):
spe1 = species[i]
for j in range(0,len(species)):
if i != j:
spe2 = species[j]
if i > j:
print >>outfile,"python "+args.pathEvolClust+" -s1 "+spe1+" -s2 "+spe2+" --get_pairwise_clusters -d "+args.outDir+" --threshold "+thrMode
outfile.close()
outfileName = outJob+"jobs.step1.txt"
elif tagName == "comparison":
outfileName = outJob+"jobs.step2.txt"
outfile = open(outJob+"jobs.step2.txt","w")
for fileName in glob.glob(outDir+"/clusters_by_spe/*"):
print >>outfile,"python "+args.pathEvolClust+" -i "+fileName+" -d "+outDir+" --cluster_comparison"
outfile.close()
return outfileName
########################################################################
# Check file presence
########################################################################
def check_files(folderName):
jobs = {}
for line in open(folderName+"/jobs/jobs.step1.txt"):
line = line.strip()
s1 = line.split("-s1 ")[1].split(" ")[0]
s2 = line.split("-s2 ")[1].split(" ")[0]
if s1 not in jobs:
jobs[s1] = {}
jobs[s1][s2] = line
species = [x.split("/")[-1] for x in glob.glob(folderName+"/pairs_files/*")]
ok = True
outfile = open(folderName+"/jobs/jobs.step1.missing.txt","w")
for a in range(0,len(species)):
fileName = folderName+"/clusters_from_pairs/"+species[a]+"/"
for b in range(0,len(species)):
if a != b:
fileName2 = fileName+species[b]+".txt"
if not os.path.exists(fileName2):
if species[a] in jobs:
if species[b] in jobs[species[a]]:
print >>outfile,jobs[species[a]][species[b]]
elif species[b] in jobs:
if species[a] in jobs[species[b]]:
print >>outfile,jobs[species[b]][species[a]]
else:
print "File "+fileName+" not found but jobs command also not found"
ok = False
if not ok:
exit("Some files are missing from the previous step, please check out the file "+folderName+"/jobs/jobs.step1.missing.txt")
########################################################################
# Genome walking - Main script
########################################################################
#Obtain conserved cluster given a pair of homologous proteins
def get_clusters(p1,p2,conversion,set_difference):
spe1 = p1.split("_")[0]
spe2 = p2.split("_")[0]
if spe1 != spe2:
cluster1,cluster2,score = calculate_cluster(p1,p2,conversion,set_difference)
return cluster1,cluster2,score
def calculate_cluster(s1,s2,conversion,set_difference):
#Obtain contigs where the seed is located
spe1,contig1 = s1.split("_")[0],s1.split("_")[1]
#Get all the proteins in the contig
cluster1 = conversion[spe1][contig1].keys()
#Sort them
cluster1 = sorted(cluster1,key=lambda x: int(x.split("_")[2]))
#Convert them into their protein family codes
cluster1Trans = [conversion[spe1][contig1][x] for x in cluster1 if x in conversion[spe1][contig1]]
#Repeat for second contig
spe2,contig2 = s2.split("_")[0],s2.split("_")[1]
cluster2 = conversion[spe2][contig2].keys()
cluster2 = sorted(cluster2,key=lambda x: int(x.split("_")[2]))
cluster2Trans = [conversion[spe2][contig2][x] for x in cluster2 if x in conversion[spe2][contig2]]
#Trim edges according to presence of homologs in both clusters
cluster1 = trim_clusters(cluster1,cluster1Trans,cluster2Trans)
cluster1Trans = [conversion[spe1][contig1][x] for x in cluster1 if x in conversion[spe1][contig1]]
cluster2 = trim_clusters(cluster2,cluster2Trans,cluster1Trans)
cluster2Trans = [conversion[spe2][contig2][x] for x in cluster2 if x in conversion[spe2][contig2]]
#Save current cluster length
size1 = len(cluster1)
size2 = len(cluster2)
continua = True
while continua:
#Delete proteins that are not present in the opposite cluster
cluster1 = delete_non_homologs(cluster1,cluster1Trans,cluster2Trans)
#Cut the cluster if there are stretches of more than three proteins in between, will return the piece where the seed is present as long as it's still larger or equal than the minSize
cluster1 = cut_cluster(cluster1,s1,set_difference)
cluster1Trans = [conversion[spe1][contig1][x] for x in cluster1 if x in conversion[spe1][contig1]]
#If the cluster still exists then the same is done for the opposite cluster
if len(cluster1) != 0:
cluster2 = delete_non_homologs(cluster2,cluster2Trans,cluster1Trans)
cluster2 = cut_cluster(cluster2,s2,set_difference)
cluster2Trans = [conversion[spe2][contig2][x] for x in cluster2 if x in conversion[spe2][contig2]]
else:
#If no piece remains then the clusters will be returned empty
cluster2 = []
cluster2Trans = []
#We check whether we still have two clusters
if len(cluster1) == 0 or len(cluster2) == 0:
continua = False
#We check if the size of the clusters has changed during the last iteration, if not this will finish
elif len(cluster1) == size1 and len(cluster2) == size2:
continua = False
#We continue
if continua:
size1 = len(cluster1)
size2 = len(cluster2)
#If, after the whole process we still have two clusters left then we complete the possible gaps and calculate their score
if len(cluster1) != 0 and len(cluster2) != 0:
cluster1 = complete_cluster(cluster1)
cluster2 = complete_cluster(cluster2)
#print "Complete cluster found, calculating score"
score = calculate_score(cluster1,cluster2,conversion)
else:
cluster1 = []
cluster2 = []
score = 0
return cluster1,cluster2,score
#Fill in non-homologous proteins
def complete_cluster(cluster):
start = int(cluster[0].split("_")[2])
stop = int(cluster[-1].split("_")[2])
base = "_".join(cluster[0].split("_")[:2])
new_cluster = []
for i in range(start,stop+1):
n = "%s_%.5d" % (base,i)
new_cluster.append(n)
return new_cluster
#Delete proteins that don't have homologs in the opposite cluster
def delete_non_homologs(cluster1,cluster1Trans,cluster2Trans):
new_cluster = []
for i in range(0,len(cluster1Trans)):
c = cluster1Trans[i]
if c in cluster2Trans:
new_cluster.append(cluster1[i])
return new_cluster
#Cut the cluster in pieces by parts where more than three non-homologous proteins are found
def cut_cluster(cluster,seed,set_difference):
new_group = [cluster[0]]
group_found = []
for code in cluster[1:]:
p1 = int(new_group[-1].split("_")[2])
p2 = int(code.split("_")[2])
diff = p2 - p1
if diff <= set_difference:
new_group.append(code)
else:
if seed in new_group and len(new_group) >= minSize:
group_found = new_group
new_group = [code]
if seed in new_group and len(new_group) >= minSize:
group_found = new_group
return group_found
#Delete non-homologous edges
def trim_clusters(cluster1,cluster1Trans,cluster2Trans):
trimmed = []
cl1 = set(cluster1Trans)
cl2 = set(cluster2Trans)
common = cl1.intersection(cl2)
if len(common) != 0:
nums = []
for i in range(0,len(cluster1Trans)):
c = cluster1Trans[i]
if c in common:
nums.append(i)
minim = min(nums)
maxim = max(nums)+1
trimmed = cluster1[minim:maxim]
else:
trimmed = []
return trimmed
########################################################################
# Calculate thresholds and clusters
########################################################################
#Calculates all clusters and from there it obtains the thresholds and the list of clusters that pass the filters.
def get_clusters_and_thresholds(pairs,minSize,maxSize,conversion,set_difference,thr_mode):
allClusters = {}
total = len(pairs)
num = 0
thresholds1 = {}
thresholds2 = {}
for a in range(minSize,maxSize+1):
thresholds1[a] = {}
thresholds2[a] = {}
allClusters = {}
for p in pairs:
if num % 1000 == 0:
print "Processed: ",num,"out of",total
num += 1
p1,p2 = p.split("-")
if args.species1 in p1:
pass
else:
p1,p2 = p2,p1
cl1,cl2,score = get_clusters(p1,p2,conversion,set_difference)
allClusters[p] = [cl1,cl2,score]
size1,size2 = len(cl1),len(cl2)
if size1 >= minSize and size2 >= minSize:
thresholds1 = get_threshold_scores(cl1,cl2,conversion,thresholds1,p1)
thresholds2 = get_threshold_scores(cl2,cl1,conversion,thresholds2,p2)
thresholds1 = print_thresholds(args.species1,args.species2,thresholdsPath,thresholds1,all_proteins1,thr_mode)
thresholds2 = print_thresholds(args.species2,args.species1,thresholdsPath,thresholds2,all_proteins2,thr_mode)
#Filter clusters based on thresholds
path = args.outDir+"/clusters_from_pairs/"
pathAll = args.outDir+"/all_cluster_predictions/"
create_folder(path)
create_folder(pathAll)
clusters1 = set([])
clusters2 = set([])
pathAll1 = pathAll+"/"+args.species1+"/"
create_folder(pathAll1)
pathAll2 = pathAll+"/"+args.species2+"/"
create_folder(pathAll2)
outfileAll1 = open(pathAll1+"/"+args.species2+".txt","w")
print >>outfileAll1,"#Code1\tCode2\tClusterSize1\tClusterSize2\tScore\tCluster1\tCluster2"
outfileAll2 = open(pathAll2+"/"+args.species1+".txt","w")
print >>outfileAll2,"#Code1\tCode2\tClusterSize1\tClusterSize2\tScore\tCluster1\tCluster2"
for p in allClusters:
cl1 = allClusters[p][0]
cl2 = allClusters[p][1]
score = allClusters[p][2]
size1 = len(cl1)
size2 = len(cl2)
p1,p2 = p.split("-")
if len(cl1) != 0:
print >>outfileAll1,p1+"\t"+p2+"\t"+str(size1)+"\t"+str(size2)+"\t"+str(score)+"\t"+";".join(cl1)+"\t"+";".join(cl2)
else:
print >>outfileAll1,p1+"\t"+p2+"\tNone"
if len(cl2) != 0:
print >>outfileAll2,p2+"\t"+p1+"\t"+str(size2)+"\t"+str(size1)+"\t"+str(score)+"\t"+";".join(cl2)+"\t"+";".join(cl1)
else:
print >>outfileAll2,p2+"\t"+p1+"\tNone"
if size1 >= minSize and size2 >= minSize:
if size1 > maxSize or size2 > maxSize:
pass
else:
if score > thresholds1[size1] and score > thresholds2[size2]:
cl1 = ";".join(cl1)
cl2 = ";".join(cl2)
clusters1.add(cl1)
clusters2.add(cl2)
outfileAll1.close()
outfileAll2.close()
path1 = path+"/"+args.species1
create_folder(path1)
outfile1 = open(path1+"/"+args.species2+".txt","w")
for cl1 in clusters1:
print >>outfile1,cl1
outfile1.close()
path2 = path+"/"+args.species2
create_folder(path2)
outfile2 = open(path2+"/"+args.species1+".txt","w")
for cl2 in clusters2:
print >>outfile2,cl2
outfile1.close()
#Given two found clusters it obtains the values of the thresholds we're going to use
#It will allways save the best score possible for a given protein, no matter how many homologs
#it has.
def get_threshold_scores(cl1,cl2,conversion,thresholds,prot):
size = len(cl1)
if size > maxSize:
size = maxSize
for s in range(minSize,size+1):
if prot not in thresholds[s]:
vesFent = True
else:
if thresholds[s][prot] == 1.0:
vesFent = False
else:
vesFent = True
if vesFent:
spe1 = cl1[0].split("_")[0]
contig1 = cl1[0].split("_")[1]
spe2 = cl2[0].split("_")[0]
contig2 = cl2[0].split("_")[1]
cl1T = [conversion[spe1][contig1][x] for x in cl1 if x in conversion[spe1][contig1]]
cl2T = [conversion[spe2][contig2][x] for x in cl2 if x in conversion[spe2][contig2]]
current_score = 0.0
for a in range(0,len(cl1)-s+1):
if current_score != 1.0:
if prot in cl1[a:a+s]:
cluster2 = trim_clusters(cl2,cl2T,cl1T[a:a+s])
if len(cluster2) != 0:
score = calculate_score(cl1[a:a+s],cluster2,conversion)
else:
score = 0.0
if score > current_score:
current_score = score
if prot in thresholds[s]:
if current_score > thresholds[s][prot]:
thresholds[s][prot] = current_score
else:
thresholds[s][prot] = current_score
return thresholds
#Summarize and print thresholds in a file for record keeping
def print_thresholds(spe1,spe2,outDir,thresholds,all_proteins,thr_mode):
outDir = outDir+"/"+spe1
create_folder(outDir)
outfile = open(outDir+"/"+spe2+".txt","w")
print >>outfile,"Cluster_size\tThreshold"
sizes = thresholds.keys()
sizes.sort()
thresholds2 = {}
for size in sizes:
values = []
for code in all_proteins:
if code not in thresholds[size]:
values.append(0.0)
else:
values.append(thresholds[size][code])
if thr_mode == "2stdv":
thr = calculate_threshold1(values)
elif thr_mode == "3stdv":
thr = calculate_threshold2(values)
elif thr_mode == "1stdv":
thr = calculate_threshold3(values)
elif thr_mode == "90percent":
thr = calculate_threshold4(values)
elif thr_mode == "75percent":
thr = calculate_threshold5(values)
elif thr_mode == "non_parametric":
thr = calculate_threshold6(values)
print >>outfile,"%d\t%.3f" %(size,thr)
thresholds2[size] = thr
outfile.close()
return thresholds2
#Threshold 1: average + 2stdv
def calculate_threshold1(values):
average = numpy.average(values)
std = numpy.std(values)
thr = average + 2.0*std
if thr > 1.0:
thr = 1.0
return thr
#Threshold 2: average + 3stdv
def calculate_threshold2(values):
average = numpy.average(values)
std = numpy.std(values)
thr = average + 3.0*std
if thr > 1.0:
thr = 1.0
return thr
#Threshold 3: average + 1stdv
def calculate_threshold3(values):
average = numpy.average(values)
std = numpy.std(values)
thr = average + 1*std
if thr > 1.0:
thr = 1.0
return thr
#Threshold 4: takes value below which 90% of the data can be found
def calculate_threshold4(values):
values.sort()
num = int(float(len(values)) * 0.9)
print len(values),num
thr = values[num]
return thr
#Threshold 5: takes value below which 75% of the data can be found
def calculate_threshold5(values):
values.sort()
num = int(float(len(values)) * 0.75)
thr = values[num]
return thr
########################################################################
# Calculate scores
########################################################################
def calculate_score(cluster1,cluster2,conversion):
cl1 = []
cl2 = []
spe1 = cluster1[0].split("_")[0]
contig1 = cluster1[0].split("_")[1]
spe2 = cluster2[0].split("_")[0]
contig2 = cluster2[0].split("_")[1]
missing = 0
if len(conversion) == 0:
cl1 = list(cluster1)
cl2 = list(cluster2)
print "MISSING conversion"
else:
#print "Conversion ok"
for cl in cluster1:
if cl in conversion[spe1][contig1]:
cl1.append(conversion[spe1][contig1][cl])
else:
name = "m_"+str(missing)
missing += 1
cl1.append(name)
for cl in cluster2:
if cl in conversion[spe2][contig2]:
cl2.append(conversion[spe2][contig2][cl])
else:
name = "m_"+str(missing)
missing += 1
cl2.append(name)
common1 = len([x for x in cl1 if x in cl2])
common2 = len([x for x in cl2 if x in cl1])
#print "Number of common proteins:",common1,common2
if common1 < 2 or common2 < 2:
#At least the cluster has to have two homologous proteins for it to be considered
score = 0.0
else:
size = len(cluster1)*len(cluster2)*2
missing1 = len(cluster1)-common1
missing2 = len(cluster2)-common2
missing = missing1*missing1+missing2*missing2
common = common1*common1+common2*common2
score = float(common - missing)/float(size)
if score < 0.0:
score = 0.0
elif score > 1.0:
score = 1.0
return score
#Calculates score between pairs of clusters
def calculate_partial_scores(clustersSpe,clustersAll,conversion,outfileName):
outfile = open(outfileName,"w")
codesSpe = clustersSpe.keys()
codesAll = clustersAll.keys()
for i in range(0,len(codesSpe)):
cluster1 = clustersSpe[codesSpe[i]]
print i,"out of",len(codesSpe)
for j in range(0,len(codesAll)):
cluster2 = clustersAll[codesAll[j]]
score = calculate_score(cluster1,cluster2,conversion)
if score > 0.0:
print >>outfile,codesSpe[i]+"\t"+codesAll[j]+"\t"+str(score)
outfile.close()
########################################################################
# Filter families
########################################################################
def divide_overlaps(families,clusters):
dividedFamilies = {}
for spe in families:
if len(families[spe]) == 1:
dividedFamilies[spe] = families[spe]
else:
fam = families[spe]
fam = sorted(fam,key=lambda x: int(clusters[x][0].split("_")[2]))
all_groups = []
new_group = [fam[0]]
current_proteins = set(clusters[fam[0]])
for f in fam[1:]:
prots = set(clusters[f])
common = current_proteins.intersection(prots)
if len(common) == 0:
all_groups.append(new_group)
new_group = [f]
current_proteins = prots
else:
new_group.append(f)
current_proteins = current_proteins.union(prots)
all_groups.append(new_group)
if len(all_groups) == 1:
dividedFamilies[spe] = new_group
else:
num = 1
for n in all_groups:
name = "%s_%.3d" % (spe,num)
num += 1
dividedFamilies[name] = n
return dividedFamilies
def delete_outliers(family,clusters):
info = {}
for spe in family:
for code in family[spe]:
info[code] = len(clusters[code])
#~ print code,len(clusters[code])
delete = []
#~ print "INITIAL:"
#~ for code in info:
#~ print code,info[code]
average,std,thrUp,thrDown = get_stats(info.values())
size = 0
saved = []
#~ print info.keys()
saved,info = delete_unique(info,saved)
num = 1
if len(info) != 0:
while len(info) != size:
size = len(info)
#~ print num,delete,info.keys()
info,delete = delete_outlier(info,average,thrUp,thrDown,std,delete)
if len(info) != size:
average,std,thrUp,thrDown = get_stats(info.values())
saved,info = delete_unique(info,saved)
#~ print delete
#~ print "TO DELETE:",delete
family2 = {}
for spe in family:
family2[spe] = []
for code in family[spe]:
if code not in delete:
family2[spe].append(code)
return family2
def get_stats(nums):
average = numpy.average(nums)
std = numpy.std(nums)
thrUp = average+(std*2.0)
thrDown = average-(std*2.0)
return average,std,thrUp,thrDown
def delete_unique(info,saved):
counter = {}
info2 = {}
for code in info:
spe = code.split("_")[1]
if spe not in counter:
counter[spe] = []
counter[spe].append(code)
for code in counter:
if len(counter[code]) == 1:
saved.append(counter[code][0])
else:
for name in counter[code]:
info2[name] = info[name]
return saved,info2
def delete_outlier(info,average,thrUp,thrDown,std,delete):
diffUp = 0
chosenUp = None
diffDown = 0
chosenDown = None
for code in info:
val = info[code]
if val > average:
if val > thrUp:
d = val - thrUp
if d > diffUp:
diffUp = d
chosenUp = code
else:
if val < thrDown:
d = thrDown - val
if d > diffDown:
diffDown = d
chosenDown = code
#This is added in case that two codes of the same species are chosen and there were only two codes for this species to begin with
if chosenUp != None and chosenDown != None:
sUp = chosenUp.split("_")[1]
sDown = chosenDown.split("_")[1]
if sUp == sDown:
if diffUp < diffDown:
chosenUp = None
else:
chosenDown = None
if chosenUp != None:
#~ print "CHOSEN OUTLIER UP:",chosenUp,diffUp,info[chosenUp],average,thrUp,std
delete.append(chosenUp)
del info[chosenUp]
if chosenDown != None:
#~ print "CHOSEN OUTLIER DOWN:",chosenDown,diffDown,info[chosenDown],average,thrDown,std
delete.append(chosenDown)
del info[chosenDown]
return info,delete
#Checks that the cluster is not only formed by duplications of the same gene
def delete_multiple_duplications(spe,cl,conversion):
counter = set([])
for code in cl:
contig = code.split("_")[1]
if code in conversion[contig]:
g = conversion[contig][code]
counter.add(g)
if len(counter) >= (minSize-1):
PASS = True
else:
PASS = False
#print spe,PASS,counter
return PASS
########################################################################
# Fuse clusters from the same species
########################################################################
def run_mcl(clusters,clDir,tmpDir,outfileMCL):
clustList = clusters.keys()
outfile = open(tmpDir+"/mcl_list.txt","w")
for a in range(0,len(clustList)):
name1 = clustList[a]
codes1 = set(clusters[name1])
for b in range(0,len(clustList)):
name2 = clustList[b]
codes2 = set(clusters[name2])
common = codes1.intersection(codes2)
overlap = float(len(common)) / (float(len(codes1)+len(codes2))/2.0)
if overlap >= 0.33:
print >>outfile,name1+"\t"+name2+"\t"+str(overlap)
else:
pass
outfile.close()
cmd = "mcl "+tmpDir+"/mcl_list.txt --abc"
run_command(cmd,False)
cmd = "mv out.mcl_list.txt.I20 "+outfileMCL
run_command(cmd,False)
def list_all_genes(clusters):
prots = set([])
for cl in clusters:
for p in clusters[cl]:
prots.add(p)
return prots
def split_in_groups(genes,set_difference):
groups = []
new_group = [genes[0]]
for gene in genes[1:]:
contig1 = new_group[-1].split("_")[1]
contig2 = gene.split("_")[1]
if contig1 != contig2:
groups.append(new_group)
new_group = [gene]
else:
pos1 = int(new_group[-1].split("_")[2])
pos2 = int(gene.split("_")[2])
diff = pos2 - pos1
if diff <= set_difference:
new_group.append(gene)
else:
groups.append(new_group)
new_group = [gene]
groups.append(new_group)
groups = fill_gaps(groups)
return groups
def fill_gaps(groups):
groups2 = []
for group in groups:
start = int(group[0].split("_")[2])
stop = int(group[-1].split("_")[2]) + 1
base = "_".join(group[0].split("_")[:2])
new_group = []
for a in range(start,stop):
name = "%s_%.5d" % (base,a)
new_group.append(name)
groups2.append(new_group)
return groups2
def get_most_representative_clusters(groups,clusters,spe,outfile,set_difference):
numT = 1
taken_genes = set([])
j = 0
for group in groups:
if len(group) == 1:
g = group[0]
if len(clusters[g]) >= minSize and len(clusters[g]) <= maxSize:
name = "FCL_"+spe+"_"+str(numT)
numT += 1
print >>outfile,name+"\t"+";".join(clusters[group[0]])
for a in clusters[g]:
taken_genes.add(a)
else:
#Gather all proteins and count how many times each protein appears in the different clusters
proteins = set([])
counter = {}
for g in group:
for prot in clusters[g]:
proteins.add(prot)
if prot not in counter:
counter[prot] = set([])
counter[prot].add(g)
#Calculate the presence threshold
presence = []
for c in counter:
s = len(counter[c])
presence.append(s)
threshold = int(numpy.average(presence))
if threshold < 1:
threshold = 1
#Gather those proteins that have a presence above the threshold
proteins2 = []
for p in proteins:
a = len(counter[p])
if a >= threshold:
proteins2.append(p)
proteins2 = list(proteins2)
proteins2 = sorted(proteins2,key=lambda x:int(x.split("_")[2]))
groups2 = split_in_groups(proteins2,set_difference)
for g in groups2:
if len(g) >= minSize and len(g) <= maxSize:
name = "FCL_"+spe+"_"+str(numT)
numT += 1
print >>outfile,name+"\t"+";".join(g)
for a in g:
taken_genes.add(a)
return taken_genes
def fishing(lost,clusters,outfileREPR,clDir,tmpDir,set_difference):
a = 0
outfile = open(clDir+"/"+spe+".fishing","w")
clusters2 = {}
for cl in clusters:
genes = set(clusters[cl])
common = genes.intersection(lost)
diff = len(genes) - len(common)
if diff == 0 or diff == 1 or diff == 2:
print >>outfile,cl+"\t"+";".join(clusters[cl])
clusters2[cl] = clusters[cl]
outfile.close()
outfileMCL = clDir+"/"+spe+".out.2.mcl"
run_mcl(clusters2,clDir,tmpDir,outfileMCL)
groups = []
for line in open(outfileMCL):
line = line.strip()
dades = line.split()
groups.append(dades)
taken_genes = get_most_representative_clusters(groups,clusters2,spe,outfileREPR,set_difference)
return taken_genes
########################################################################
# Add clusters that were discarded
########################################################################
#Gather information of all the precomputed clusters
def compile_info(inDirCL,inDirThr):
#Create a single threshold file
species = set([])
outfileTHR = open(inDirThr+"/all_thresholds.txt","w")
species = [x.split("/")[-1] for x in glob.glob(inDirCL+"/*") if ".txt" not in x]
counter = 0
for spe1 in species:
#print counter,len(species)
counter += 1
dirName = inDirCL+"/"+spe1+"/"
#Join all clusters predicted for this species into a single file
outfileCL = open(dirName+"/all_clusters.txt","w")
for spe2 in species:
if spe1 != spe2:
fileName = inDirCL+"/"+spe1+"/"+spe2+".txt"
for line in open(fileName):
line = line.strip()
if "None" not in line and "#" not in line:
print >>outfileCL,line
outfileCL.close()
#Put all thresholds in a file
for spe2 in species:
if spe1 != spe2:
fileName = inDirThr+"/"+spe1+"/"+spe2+".txt"
for line in open(fileName):
line = line.strip()
dades = line.split()
if "Cluster_size" not in line:
print >>outfileTHR,spe1+"\t"+spe2+"\t"+dades[0]+"\t"+dades[-1]
outfileTHR.close()
return species
#Load predicted clusters into memory
def load_cluster_families2(fileName):
clFM = {}
protsCL = set([])
for line in open(fileName):
line = line.strip()
dades = line.split("\t")
if "##" in line:
pass
elif "# " in line:
name = line.split()[1]
clFM[name] = {}
else:
dades = line.split("\t")
clFM[name][dades[0]] = dades[1].split(";")
codes = dades[1].split(";")
for c in codes:
protsCL.add(c)
return clFM,protsCL
#Load thresholds into memory