forked from DessimozLab/esprit2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline.sh
executable file
·2002 lines (1639 loc) · 63.6 KB
/
pipeline.sh
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
#!/bin/bash
usage(){
cat << EOF
$0 - find split genes using Esprit 2.0
$0 [options] gene_prefix gene_family_folder orthoxml
This program computes split genes in a given genome using the methodoly
described in http://doi.org/...
The program currently requires a SGE (Sun Grid Engine) environment
to run properly. This might still change in the future.
The following options and parameters can be set.
Parameters:
-----------
gene_prefix a prefix of the gene identifiers that indicates possible
split genes, i.e. a prefix of the genes in the genome
you want to search for split genes. This argument is
required.
Example: "Traes_1DS" will search for split genes in the
wheat 1DS chomosome (all ids start with this prefix)
gene_family_folder
A folder that contains one fasta file per gene family. The
files in there should be sequencially nummered and having
a HOG prefix, e.g. HOG00001.fa
If it is not provided, it defaults to ./HOGFasta
orthoxml the file that contains the HOGs for all genomes in the
analysis. This file should match the data in the gene
family folder.
If not set, it defaults to ./HierarchicalGroups.orthoxml
Options:
--------
-l minimum length of candidate genes, defaults to 50 if not set.
Shorter genes will be excluded.
-o maximum overlap in the alignment, defaults to 0.1 if not set.
This refers to the maximum possible overlap that two fragments
might have in the alignment to still be considered a possible
split gene.
-s min size of the gene family including the fragements, defaults
to 5 if not set. This means, a family must have at least 3
reference sequences and 2 fragments.
-b number of bootstrap replicates, defaults to 100 if not set.
-c threshold for collapsing, defaults to 0.95 if not set. This
refers to the number of bootstrap replicates that need to
contain a certain split in order to not be collapsed.
-a significance of the likelihood ratio test, defaults to 0.01.
-g filename of gff input file. IDs of gene features need to match
those of the input sequences. By default the merged output
gff file will be named same as input + '.merged'. Use the -w
to overwrite.
-w filename of gff output file. Only affects if -g is specified.
EOF
}
min_len="50"
ovlp_len="0.1"
family_size="5"
n_samples="100"
col_thr="95"
lrt_sign="0.01"
gff=""
gff_out=""
while getopts "hvl:o:s:b:c:a:g:w:" opt; do
case $opt in
h) usage
exit 0
;;
v) echo "Esprit 2.0"
exit 0
;;
l) min_len="$OPTARG"
if ! [[ $min_len =~ ^[1-9][0-9]*$ ]] ; then
echo "-$opt requires positive integer argument"
usage
exit 1
fi
;;
o) ovlp_len="$OPTARG"
;;
s) family_size="$OPTARG"
;;
b) n_samples="$OPTARG"
;;
c) col_thr="$OPTARG"
;;
a) lrt_sign="$OPTARG"
;;
g) gff="$OPTARG"
;;
w) gff_out="$OPTARG"
;;
esac
done
shift $((OPTIND-1))
unique_str="$1"
gene_fam_dir="${2:-./HOGFasta}"
orthoxml="${3:-./HierarchicalGroups.orthoxml}"
if [ -z "$unique_str" ] || [ ! -f "$orthoxml" ] || [ ! -d "$gene_fam_dir" ] ; then
>&2 usage
>&2 echo "invalid parameters: \"$unique_str\" \"$gene_fam_dir\" \"$orthoxml\""
exit 1
fi
source ./load_env
pip install -r ./requirements.txt
if [ "$?" != "0" ] ; then
>&2 echo "failed to install python dependencies."
exit 1
fi
# check that mafft, phyml and fasttree are installed and in PATH
allok="true"
for prog in mafft FastTree ; do
if [ ! $(which ${prog} 2>/dev/null) ] ; then
>&2 echo "Could not detect \"$prog\" in PATH. Please make sure \"$prog\" is "
>&2 echo "installed and accessible from the PATH."
allok="false"
fi
done
if [ "$allok" != "true" ] ; then
exit 1
fi
#go to the working directory, put HierarchicalGroups.orthoxml there
#get OMA <-> Ensembl mapping
cat organise_files.txt > mapping.sh
cat >> mapping.sh << EOF
grep "protId=" $orthoxml | grep $unique_str | awk -F\" '{ for(i=2; i<=NF; i=i+2){ a = a"\""\$i"\""",\t";} {print a; a="";}}' | awk '{\$2="";print}'|tr -d '"'| tr -d ',' > mapping.txt
EOF
qsub -N mapping mapping.sh
#get HOGs of interest
cat > orthoxmlquery.py << EOF
#Author: Adrian Altenhoff
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future.builtins import str
from future import standard_library
standard_library.install_hooks()
class ElementError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return str(self.msg)
class OrthoXMLQuery(object):
"""Helper class with predefined queries on an orthoxml tree."""
ns = {"ns0": "http://orthoXML.org/2011/"} # xml namespace
@classmethod
def getToplevelOrthologGroups(cls, root):
"""returns a list with the toplevel orthologGroup elements
of the given root element."""
xquery = ".//{{{ns0}}}groups/{{{ns0}}}orthologGroup".format(**cls.ns)
return root.findall(xquery)
@classmethod
def getTaxRangeNodes(cls, root, recursively=True):
xPrefix = ".//" if recursively else "./"
xquery = '{}{{{}}}property[@name="TaxRange"]'.format(xPrefix,
cls.ns['ns0'])
return root.findall(xquery)
@classmethod
def getGeneRefNodes(cls, root, recursively=True):
iterfn = root.iter if recursively else root.iterchildren
iterator = iterfn('{{{}}}geneRef'.format(cls.ns['ns0']))
return list(iterator)
@classmethod
def getGeneFromId(cls, id_, root):
xquery = ".*//{{{}}}gene[@id='{}']".format(cls.ns['ns0'], id_)
genes = root.findall(xquery)
if len(genes) > 1:
raise ElementError('several gene nodes with id {} '
'exist'.format(id_))
gene = genes[0] if len(genes)>0 else None
return gene
@classmethod
def getGroupsAtLevel(cls, level, root):
"""returns a list with the orthologGroup elements which have a
TaxRange property equals to the requested level."""
xquery = (".//{{{0}}}property[@name='TaxRange'][@value='{1}']/..".
format(cls.ns['ns0'], level))
return root.findall(xquery)
@classmethod
def getSubNodes(cls, targetNode, root, recursively=True):
"""method which returns a list of all (if recursively
is set to true) or only the direct children nodes
having 'targetNode' as their tagname.
The namespace is automatically added to the tagname."""
xPrefix = ".//" if recursively else "./"
xquery = "{}{{{}}}{}".format(xPrefix, cls.ns['ns0'], targetNode)
return root.findall(xquery)
@classmethod
def is_geneRef_node(cls, element):
"""check whether a given element is an instance of a geneRef
element."""
return element.tag == '{{{ns0}}}geneRef'.format(**cls.ns)
@classmethod
def getLevels(cls, element):
"""returns a list of the TaxRange levels associated to the
passed orthologGroup element. If the element does not have
any TaxRange property tags associated, an empty list is
returned."""
propTags = cls.getSubNodes("property", element, recursively=False)
res = [t.get('value') for t in propTags if t.get('name') == 'TaxRange']
return res
@classmethod
def getInputGenes(cls, root, species=None):
"""returns a list of all gene elements in the orthoxml inside
<species><database> tags, i.e. the list of genes prior to running
OMA-HOGS. Optionally filtered by species."""
filter_ = ('[@name="{}"]'.format(species)
if species is not None else '')
if filter_ > '':
xquery = ('/ns:orthoXML/ns:species{}/ns:database/'
'ns:genes//ns:gene'.format(filter_))
else:
xquery = '//ns:gene'
return root.xpath(xquery, namespaces={'ns': cls.ns['ns0']})
@classmethod
def getGroupedGenes(cls, root, species=None):
""" returns a list of all geneRef elements inside <group> tags, i.e.
the list of genes clustered into families after running OMA-HOGS.
Optionally filtered by species."""
filter_ = ('[@name="TaxRange"and@value="{}"]'.format(species)
if species is not None else '')
if filter_ > '':
xquery = ('/ns:orthoXML/ns:groups/ns:orthologGroup//ns:property{}/'
'following-sibling::ns:geneRef'.format(filter_))
else:
xquery = '//ns:geneRef'
return root.xpath(xquery, namespaces={'ns': cls.ns['ns0']})
EOF
cat > get_candidates.py << EOF
# -*- coding: utf-8 -*-
import lxml.etree as etree
import sys, os
import orthoxmlquery as oq
from Bio import SeqIO
import requests, random, subprocess
from xml.dom import minidom
from Bio.Align.Applications import MafftCommandline
from Bio import AlignIO
from Bio.Phylo.Applications import PhymlCommandline
import glob
import os
def read_fasta(loc): #adapted for empty lines in HOGs.fasta
seqs = dict()
tmp = open(loc, 'r')
lines = tmp.readlines()
key = lines[0].split('>')[-1].split()[-2]
value = ''
for i in range(1, len(lines)):
if len(lines[i]) == 1:
seqs[key] = value
elif lines[i].split()[0][0] == '>':
key = lines[i].split('>')[-1].split()[-2]
value = ''
else:
value += lines[i].split()[0]
return seqs
def write_dictionary(d, out):
'''Writes a dictionary (d) to an output file (out) in the following format:
> key
d[key]
>key
d[key]
...'''
f = open(out, 'w')
for key in d.keys():
f.write('>' + key + '\n')
f.write(d[key] + '\n')
f.close()
return
def process_stdout(stdout):
'''Parse MSA from Mafft stdout (stdout),
save all genes to a dictionary (msa),
returns the dictionary (msa)'''
stdout_process = stdout.split(">")
msa = dict()
for i in range(len(stdout_process)):
if len(stdout_process[i]) > 0:
key = stdout_process[i].split('\n')[0].split()[0]
value = ''.join(stdout_process[i].split('\n')[1:])
msa[key] = value
return msa
def check_overlap_length(msa, id1, id2):
''' '''
seq1 = msa[id1].split("-")
lengths1 = [len(i) for i in seq1]
non01 = [i for i,v in enumerate(lengths1) if v > 0]
k11 = non01[0] #index of the 1st residual in seq1
k12 = len(msa[id1])- (len(lengths1)-non01[-1]) #index of the last residual in seq1
seq2 = msa[id2].split("-")
lengths2 = [len(i) for i in seq2]
non02 = [i for i,v in enumerate(lengths2) if v > 0]
k21 = non02[0] #index of the 1st residual in seq2
k22 = len(msa[id2])- (len(lengths2)-non02[-1]) #index of the last residual in seq2
s1 = list(range(k11, k12 + 1))
s2 = list(range(k21, k22 + 1))
intrsc = list(set(s1) & set(s2))
return k11, k12, k21, k22, sorted(intrsc), len(intrsc)/float(len(s1)), len(intrsc)/float(len(s2))
def edit_overlapping_seqs(msa, id1, id2, k11, k21, o_start, o_end):
new_msa = dict()
for key in msa:
new_msa[key] = msa[key]
h = (o_start - 1) + (o_end - o_start + 1)//2 + ((o_end - o_start + 1)%2) * random.randint(0,1)
if k11 < k21:
left = id1
right = id2
else:
left = id2
right = id1
new_msa[left] = new_msa[left][0 : h + 1] + 'X' * (o_end - h) + new_msa[left][o_end + 1 : ]
new_msa[right] = new_msa[right][0 : o_start] + 'X' * (h - o_start + 1) + new_msa[right][h + 1 : ]
return new_msa, h + 1
def concatenate_overlapping_seqs(msa, id1, id2, o_start, o_end):
new_msa = dict()
for key in msa:
new_msa[key] = msa[key]
seq = ''
for i in range(0, o_start):
if new_msa[id1][i] != '-':
seq += new_msa[id1][i]
elif new_msa[id2] != '-':
seq += new_msa[id2][i]
else:
seq += '-'
for i in range(o_start, o_end + 1):
if new_msa[id1][i] != 'X':
seq += new_msa[id1][i]
else:
seq += new_msa[id2][i]
for i in range(o_end + 1, len(new_msa[id1])):
if new_msa[id1][i] != '-':
seq += new_msa[id1][i]
elif new_msa[id2] != '-':
seq += new_msa[id2][i]
else:
seq += '-'
new_msa[id1 + '_' + id2] = seq
new_msa.pop(id1)
new_msa.pop(id2)
return new_msa
def concatenate_nonoverlapping_seqs(msa, id1, id2):
new_msa = dict()
for key in msa:
new_msa[key] = msa[key]
seq = ''
for i in range(len(new_msa[id1])):
if new_msa[id1][i] != '-':
seq += new_msa[id1][i]
elif new_msa[id2] != '-':
seq += new_msa[id2][i]
else:
seq += '-'
new_msa[id1 + '_' + id2] = seq
new_msa.pop(id1)
new_msa.pop(id2)
return new_msa
loc_mapping = os.getcwd() + '/mapping.txt'
mapping = dict()
target_genes = []
tmp = open(loc_mapping, 'r')
lines = tmp.readlines()
for i in range(len(lines)):
temp = lines[i].split()
mapping[temp[0]] = " ".join(temp[1:])
target_genes.append(temp[0])
tmp.close()
XML = "$orthoxml"
doc = etree.parse(XML)
root_XML = doc.getroot()
topLevel_OG = oq.OrthoXMLQuery.getToplevelOrthologGroups(root_XML)
HOGs = dict()
candidates_number = dict()
for OG in topLevel_OG:
OG_genes = [ e.get("id") for e in OG.getiterator() if e.tag == "{http://orthoXML.org/2011/}geneRef" ]
if len(set(OG_genes).intersection(target_genes)) >= 2:
HOGs[OG.get("id")] = OG_genes
candidates_number[OG.get("id")] = list(set(OG_genes).intersection(target_genes))
candidates_id = dict()
for key in candidates_number:
cand = []
for i in range(len(candidates_number[key])):
if ';' in mapping[candidates_number[key][i]]:
cand.append(mapping[candidates_number[key][i]].split(';')[-1][1:])
else:
cand.append(mapping[candidates_number[key][i]])
candidates_id[key] = cand
positions = list()
cuts = list()
lengths = list()
for key in candidates_id:
hog_loc = "$gene_fam_dir" +'/HOG' + key + '.fa'
#hog gene sequences
hog_seqs = read_fasta(hog_loc)
#write fasta
w_temp = os.getcwd() + '/hog_temp/HOG' + key + '.fa'
write_dictionary(hog_seqs, w_temp)
#hog alignment
mafft_cline = MafftCommandline(input=w_temp)
msa_fasta_hog = os.getcwd() + '/hog_aln/HOG' + key + '.aln' #MSA in FASTA format
stdout, stderr = mafft_cline()
with open(msa_fasta_hog, 'w') as handle:
handle.write(stdout)
#
msa = process_stdout(stdout)
if len(msa) >= `echo $family_size`:
for i in range(len(candidates_id[key]) - 1):
for j in range(i + 1, len(candidates_id[key])):
lengths.append((key, candidates_id[key][i], len(hog_seqs[candidates_id[key][i]]), candidates_id[key][j], len(hog_seqs[candidates_id[key][j]])))
if len(hog_seqs[candidates_id[key][i]]) >= `echo $min_len` and len(hog_seqs[candidates_id[key][j]]) >= `echo $min_len`:
k11, k12, k21, k22, intrsc, o1, o2 = check_overlap_length(msa, candidates_id[key][i], candidates_id[key][j])
if o1 < `echo $ovlp_len` and o2 < `echo $ovlp_len`:
name = candidates_id[key][i] + '_' + candidates_id[key][j]
msa_fasta = os.getcwd() + '/aln/' + name + '.aln'
msa_phy = os.getcwd() + '/phy/' + name + '.phy' #MSA in phylip format
out_c = os.getcwd() + '/aln_c/' + name + '_c.aln'
out_c_phy = os.getcwd() + '/phy_c/' + name + '_c.phy'
#convert msa to phylip
#concatenate
if len(intrsc) == 0:
write_dictionary(msa, msa_fasta)
AlignIO.convert(msa_fasta, "fasta", msa_phy, "phylip-relaxed")
msa_fasta_con = concatenate_nonoverlapping_seqs(msa, candidates_id[key][i], candidates_id[key][j])
positions.append((key, candidates_id[key][i], candidates_id[key][j], k11, k12, k21, k22, -1, -1, o1, o2))
n = random.randint(min(k12, k22) + 1, max(k11, k21))
if k21 < k11:
cuts.append((key, candidates_id[key][j], candidates_id[key][i], n))
else:
cuts.append((key, candidates_id[key][i], candidates_id[key][j], n))
write_dictionary(msa_fasta_con, out_c)
AlignIO.convert(out_c, "fasta", out_c_phy, "phylip-relaxed")
else:
msa_edited, n = edit_overlapping_seqs(msa, candidates_id[key][i], candidates_id[key][j], k11, k21, intrsc[0], intrsc[-1])
if k21 < k11:
cuts.append((key, candidates_id[key][j], candidates_id[key][i], n))
else:
cuts.append((key, candidates_id[key][i], candidates_id[key][j], n))
write_dictionary(msa_edited, msa_fasta)
AlignIO.convert(msa_fasta, "fasta", msa_phy, "phylip-relaxed")
msa_fasta_con = concatenate_overlapping_seqs(msa_edited, candidates_id[key][i], candidates_id[key][j], intrsc[0], intrsc[-1])
positions.append((key, candidates_id[key][i], candidates_id[key][j], k11, k12, k21, k22, intrsc[0], intrsc[-1], o1, o2))
write_dictionary(msa_fasta_con, out_c)
AlignIO.convert(out_c, "fasta", out_c_phy, "phylip-relaxed")
hogs_overlap_positions = os.getcwd() + '/alignment_positions.txt'
f = open(hogs_overlap_positions, 'w')
for i in range(len(positions)):
f.write(str(positions[i][0]) + '\t' + str(positions[i][1]) + '\t' + str(positions[i][2]) + '\t' + str(positions[i][3]) + '\t' + str(positions[i][4]) + '\t' + str(positions[i][5]) + '\t' +
str(positions[i][6]) + '\t' + str(positions[i][7]) + '\t' + str(positions[i][8]) + '\t' + str(positions[i][9]) + '\t' + str(positions[i][10]) + '\n')
f.close()
hogs_length_sequences = os.getcwd() + '/sequence_lengths.txt'
f = open(hogs_length_sequences, 'w')
for i in range(len(lengths)):
f.write(lengths[i][0] + '\t' + lengths[i][1] + '\t' + str(lengths[i][2]) + '\t' + lengths[i][3] + '\t' + str(lengths[i][4]) + '\n')
f.close()
hogs_cuts = os.getcwd() + '/cuts.txt'
f = open(hogs_cuts, 'w')
for i in range(len(cuts)):
f.write(cuts[i][0] + '\t' + cuts[i][1] + '\t' + cuts[i][2] + '\t' + str(cuts[i][3]) + '\n')
f.close()
EOF
cat organise_files.txt > get_candidates.sh
cat >> get_candidates.sh << EOF
mkdir -p hog_temp hog_aln aln \
phy aln_c phy_c
source ./load_env
python get_candidates.py
rm -rf hog_temp
EOF
qsub -sync y -N get_cand -hold_jid mapping get_candidates.sh
#computing n-1 trees
cd phy_c
for f in *.phy
do
cat ../one_tree.txt > $f.sh
cat >> $f.sh << EOF
source ../load_env
FastTree $f > ${f}_tree.txt
EOF
done
i=1
for f in *.phy.sh
do
qsub -N job_n_1_$i -cwd $f
((i++))
done
cd ..
cat organise_files.txt > splitting_trees.sh
cat >> splitting_trees.sh << EOF
mkdir -p n_1_trees
find phy_c/ -name "*_tree.txt" -exec mv {} n_1_trees \; &
wait
source ./load_env
python splitting_trees.py n_1_trees/
EOF
cat > splitting_trees.py << EOF
import random
import sys, glob, os
def findName(t, id_f):
id_s = t.index(id_f)
for i in range(id_s, len(t)):
if t[i]==':':
return t[id_s:i]
def splitBr_difid(t, id_old, id1, id2):
to_repl = '(' + id1 + ':0,' + id2 + ':0' + ')' + '0.5'
return t.replace(id_old, to_repl)
folder = os.getcwd() + '/' + sys.argv[1]
files = glob.glob(folder + '*tree.txt')
for file in files:
temp = open(file, 'r')
t = temp.readlines()[0].split()[0]
id_old = file.split('/')[-1].split('_c.')[0]
id1 = id_old.split('_' + '`echo $unique_str`')[0]
id2 = '`echo $unique_str`' + id_old.split('_' + '`echo $unique_str`')[1]
t_s = splitBr_difid(t, id_old, id1, id2)
output_name = file.split('.txt')[0] + '_s.txt'
f = open(output_name, 'w')
f.write(t_s)
f.close()
EOF
qsub -N s_trees -hold_jid "job_n_1_*" splitting_trees.sh
cat organise_files.txt > organise_n_1.sh
cat >> organise_n_1.sh << EOF
mkdir n_1_trees_s
find n_1_trees/ -name "*_s.txt" -exec mv {} n_1_trees_s \; &
wait
tar -zcvf n_1_trees.tar.gz n_1_trees --remove-files
tar -zcvf n_1_trees_s.tar.gz n_1_trees_s --remove-files
mkdir n_1_res
find phy_c/ -name "job*" -exec mv {} n_1_res \; &
wait
tar -zcvf n_1_res.tar.gz n_1_res --remove-files
tar -zcvf phy_c.tar.gz phy_c --remove-files
tar -zcvf hog_aln.tar.gz hog_aln --remove-files
EOF
qsub -N o_n_1 -hold_jid s_trees organise_n_1.sh
#computing n trees - without input topology
cd phy
for f in *.phy
do
cat ../one_tree.txt > $f.notop.sh
cat >> $f.notop.sh << EOF
source ../load_env
FastTree $f > ${f}_tree_notop.txt
EOF
done
i=1
for f in *.phy.notop.sh
do
qsub -N job_n_notop_$i -cwd $f
((i++))
done
cd ..
cat organise_files.txt > organise_n_notop.sh
cat >> organise_n_notop.sh << EOF
mkdir n_trees_notop
find phy/ -name "*_tree_notop.txt" -exec mv {} n_trees_notop \; &
wait
tar -zcvf n_trees_notop.tar.gz n_trees_notop --remove-files
mkdir n_notop_res
find phy/ -name "job_n_notop*" -exec mv {} n_notop_res \; &
wait
tar -zcvf n_notop_res.tar.gz n_notop_res --remove-files
EOF
qsub -N o_n_not -hold_jid "job_n_notop_*" organise_n_notop.sh
#computing n trees - with input topology
#put input trees to the folder
cat organise_files.txt > moving_trees.sh
cat >> moving_trees.sh <<EOF
tar -zxvf n_1_trees_s.tar.gz
find n_1_trees_s/ -name "*.txt" -exec mv {} phy \; &
wait
rmdir n_1_trees_s
EOF
qsub -N move_tr -hold_jid o_n_1 moving_trees.sh
cd phy
for f in *.phy
do
cat ../one_tree.txt > $f.top.sh
cat >> $f.top.sh << EOF
source ../load_env
FastTree -intree ${f%.phy}_c.phy_tree_s.txt $f > ${f}_tree_top.txt
EOF
done
i=1
for f in *.top.sh
do
qsub -N job_n_top_$i -hold_jid move_tr -cwd $f
((i++))
done
cd ..
cat organise_files.txt > organise_n_top.sh
cat >> organise_n_top.sh << EOF
mkdir n_top_res
find phy/ -name "job_n_top*" -exec mv {} n_top_res \; &
wait
tar -zcvf n_top_res.tar.gz n_top_res --remove-files
EOF
qsub -N o_n_top -hold_jid "job_n_top_*" organise_n_top.sh
cat organise_files.txt > organise_n.sh
cat >> organise_n.sh << EOF
tar -zcvf phy.tar.gz phy --remove-files
tar -zcvf aln.tar.gz aln --remove-files
EOF
qsub -N o_n -hold_jid "o_n_*" organise_n.sh
#get bootstrap replicates
cat bootstrap.txt > bootstrap.sh
cat >> bootstrap.sh << EOF
source ./load_env
python bootstrap.py --loc_folder='aln_c/' --num_bootstraps=$n_samples -j 1 --verbose=2
EOF
cat > bootstrap.py << EOF
#Author: Kevin Gori
import sys, os
from ruffus import transform, subdivide, cmdline, suffix, formatter, mkdir
from Bio import AlignIO
from Bio.Seq import Seq, UnknownSeq
from Bio.SeqRecord import SeqRecord
from Bio.Align import MultipleSeqAlignment
from abc import ABCMeta, abstractmethod, abstractproperty
from locale import getpreferredencoding
import shlex
from subprocess import PIPE, Popen
import threading
from collections import defaultdict
import random, glob
IS_PY3 = sys.version_info[0] == 3
POSIX = 'posix' in sys.builtin_module_names
DEFAULT_ENCODING = getpreferredencoding() or "UTF-8"
if IS_PY3:
from queue import Queue
else:
from Queue import Queue
class AbstractWrapper(object):
"""
Abstract Base Class:
Run an external program as a subprocess with non-blocking collection of stdout.
This class uses subprocess.Popen to handle the system call, and threading.Thread
to allow non-blocking reads of stderr and stdout.
Specific program wrappers inherit from this. They should implement two methods:
1: _default_exe and 2: _set_help.
Example:
class SomeProgram(AbstractInternal):
@property
def _default_exe(self):
return 'some_program' # The usual name of the program binary
def _set_help(self):
self('--help', wait=True) # calls 'some_program --help'
self._help = self.get_stdout() # puts the help output into self._help
#### Possible Extra Requirement ####
@property
def _hyphen_policy(self):
return 1 # If some_program arguments take a single leading hyphen
# then set this to 1 (i.e. to the number of leading hyphens)
# This only affects calling some_program using named arguments
That's it!
See blog post: http://www.zultron.com/2012/06/python-subprocess-example-running-a-background-subprocess-with-non-blocking-output-processing/
Also, StackOverflow: https://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python
Keyword handling borrowed from sh: https://amoffat.github.io/sh
"""
__metaclass__ = ABCMeta
def __init__(self, executable=None, verbose=True):
"""
Sets up the wrapper. A custom executable can be passed in, otherwise
it will search the PATH.
:param executable: Path to a custom executable to use
:return:
"""
exe = None
if executable:
exe = self._search_for_executable(executable)
if exe is None:
exe = self._search_for_executable(self._default_exe)
if not exe:
raise IOError(executable if executable else self._default_exe)
self.exe = exe # The wrapped executable
self.verbose = verbose # Controls printing of output
self.stdout_q = Queue() # The output-reading threads pipe output into
self.stderr_q = Queue() # these queues.
self.stdout_l = list() # Queued output gets placed in these lists,
self.stderr_l = list() # making it available to the caller
self.process = None # This holds the running process once the wrapped program is called
self._help = None # A place to hold a help string
def __repr__(self):
return '{}(executable=\'{}\')'.format(self.__class__.__name__, self.exe)
# Private
@abstractproperty
def _default_exe(self):
pass
@property
def _hyphen_policy(self):
"""
Returns 'n', where 'n' is the number of hyphens prepended to commandline flags.
Used internally when constructing command line arguments from parameters
passed to __call__ as keywords.
:return: 2 (as in 2 hyphens, '--')
"""
return 2
@abstractmethod
def _set_help(self):
pass
def _log_thread(self, pipe, queue):
"""
Start a thread logging output from pipe
"""
# thread function to log subprocess output (LOG is a queue)
def enqueue_output(out, q):
for line in iter(out.readline, b''):
q.put(line.rstrip())
out.close()
# start thread
self.t = threading.Thread(target=enqueue_output,
args=(pipe, queue))
self.t.daemon = True # thread dies with the program
self.t.start()
def _search_for_executable(self, executable):
"""
Search for file give in "executable". If it is not found, we try the environment PATH.
Returns either the absolute path to the found executable, or None if the executable
couldn't be found.
"""
if os.path.isfile(executable):
return os.path.abspath(executable)
else:
envpath = os.getenv('PATH')
if envpath is None:
return
for path in envpath.split(os.pathsep):
exe = os.path.join(path, executable)
if os.path.isfile(exe):
return os.path.abspath(exe)
# Public
def __call__(self, cmd=None, wait=False, **flags):
"""
Spawns the subprocess and the threads used to monitor stdout and stderr without blocking.
:param cmd: Pass the command line arguments as a string
:param wait: Block until the process returns
:param flags: Pass the commandline arguments as a dictionary. Will be appended to any content in cmd.
:return:
"""
# Check there is not already a process running
if self.running():
self.kill()
# Wipe any stdout/stderr from previous processes
self.stderr_l = []
self.stdout_l = []
# Assemble command line
if cmd is None:
cmd = ''
if flags:
cmd = ' '.join([cmd.strip(), _kwargs_to_args(flags, self._hyphen_policy)])
self.cmd = '{} {}'.format(self.exe, cmd)
# spawn
self.process = Popen(shlex.split(self.cmd),
shell=False, stdout=PIPE, stderr=PIPE, bufsize=1, close_fds=POSIX)
if self.verbose:
print('Launched {} with PID {}'.format(self.exe, self.process.pid))
# start stdout and stderr logging threads
self._log_thread(self.process.stdout, self.stdout_q)
self._log_thread(self.process.stderr, self.stderr_q)
if wait:
self.process.wait()
@property
def help(self):
"""
Returns a helpful string, preferably derived from the wrapped program
:return:
"""
if self._help is None:
self._set_help()
return self._help
def get_stderr(self, tail=None):
"""
Returns current total output written to standard error.
:param tail: Return this number of most-recent lines.
:return: copy of stderr stream
"""
while not self.stderr_q.empty():
self.stderr_l.append(self.stderr_q.get_nowait())
if tail is None:
tail = len(self.stderr_l)
return _py2_and_3_joiner('\n', self.stderr_l[:tail])
def get_stdout(self, tail=None):
"""
Returns current total output written to standard output.
:param tail: Return this number of most-recent lines.
:return: copy of stdout stream
"""
while not self.stdout_q.empty():
self.stdout_l.append(self.stdout_q.get_nowait())
if tail is None:
tail = len(self.stdout_l)
return _py2_and_3_joiner('\n', self.stdout_l[:tail])
def finished(self):
"""
Check if the running process is finished. Raises an exception if no process has ever been launched.
:return: bool
"""
if self.process is None:
raise ExternalProcessError('No process has been launched from this instance')
return self.process.poll() is not None
def kill(self):
"""
Kill the running process (if there is one)
:return: void
"""
if self.running():
if self.verbose:
print('Killing {} with PID {}'.format(self.exe, self.process.pid))
self.process.kill()
# Thread *should* tidy up itself, but we do it explicitly
if self.t.is_alive():
self.t.join(1)
def running(self):
"""
True if there is a running process. False if either no process is associated with this instance,
or if the associated process has finished.
:return: bool
"""
if self.process is None:
return False
return self.process.poll() is None
class Mafft(AbstractWrapper):
@property
def _default_exe(self):
return 'mafft'
def _set_help(self):
self(help=True, wait=True)
self._help = self.get_stdout()
def bootstrap(alignment):
length = alignment.get_alignment_length()
columns = [alignment[:,n] for n in range(length)]