-
Notifications
You must be signed in to change notification settings - Fork 8
/
_collinear_genes.pl
executable file
·2165 lines (1770 loc) · 75.8 KB
/
_collinear_genes.pl
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 perl
use strict;
use warnings;
use Getopt::Long qw(:config no_ignore_case);
use File::Basename qw(basename dirname);
use FindBin '$Bin';
use lib "$Bin/lib";
use pangeneTools qw(calc_median N50 read_FAI_regex2hash);
$|=1;
# Takes two FASTA files with genome sequences and 2 matching GFF files with
# annotated gene models.
# Produces a TSV file with pairs of collinear genes in a format similar to
# Ensembl Compara's, genomic coordinates are 1-based
# Copyright [2021-24]
# EMBL-European Bioinformatics Institute & Estacion Experimental de Aula Dei-CSIC
# Uses external software:
# minimap2 [https://academic.oup.com/bioinformatics/article/34/18/3094/4994778]
# bedtools [https://academic.oup.com/bioinformatics/article/26/6/841/244688]
# samtools [https://academic.oup.com/bioinformatics/article/25/16/2078/204688]
# GSAlign [https://doi.org/10.1186/s12864-020-6569-1]
# wfmash [https://github.com/ekg/wfmash]
# perl _collinear_genes.pl -sp1 oryza_sativa \
# -fa1 Oryza_sativa.IRGSP-1.0.dna.toplevel.fa \
# -gf1 Oryza_sativa.IRGSP-1.0.51.gff3 -sp2 oryza_nivara -fa2 \
# Oryza_nivara.Oryza_nivara_v1.0.dna.toplevel.fa \
# -gf2 Oryza_nivara.Oryza_nivara_v1.0.51.gff3 -r
# collinear | Osativa vs Onivara | Athaliana vs Ahalleri
# 2.17 | 24502 | 10637
# 2.22 | 18770 | 8231
# 2.24 | 25227 | ?
#hardcode different minimap
#$ENV{'EXE_MINIMAP'} = '~/soft/minimap2-2.24_x64-linux/minimap2';
my $MINIMAP2EXE = 'minimap2';
my $MINIMAPTYPE = '-x asm20'; # https://github.com/lh3/minimap2/issues/225
my $MINIMAPPARS = "--secondary=no --cs $MINIMAPTYPE " .
"-r1k,5k"; # https://github.com/lh3/minimap2/issues/813,
# 2949 -> 2956 2.17
# 2956 -> 2951 , 25277 -> 25209 2.24
my $WFMASHEXE = $ENV{'EXE_WFMASH'} || 'wfmash'; # v0.8.1-25-g1344b9e
my $WFMASHPARS = '-p 80 -s 1000'; # -s: median rice gene 2362, barley 1323
# -p: ~ asm20
# -p 90 -s 1000 -> 1652
# -p 80 -s 1000 -> 1793
# -p 80 -s 2000 -> 1528
my $GSALIGNPATH = './';
my $GSAINDXEXE = 'bwt_index';
my $GSALIGNEXE = 'GSAlign';
my $GSALIGNPARS = '-sen -no_vcf -fmt 1';
my $BEDTOOLSEXE = 'bedtools'; # v2.30.0
my $BEDINTSCPAR = '-wo -f XXX -F XXX -e'; # XXX to be replaced with [0-1]
my $SAMTOOLSEXE = 'samtools';
my $THREADS = 4;
my $SORTBIN = $ENV{'EXE_SORT'} || 'sort';
my $SORTPARS = "--buffer-size=1G ";
$ENV{'LC_ALL'} = 'POSIX';
my $GZIPBIN = $ENV{'EXE_GZIP'} || 'gzip';
my $BZIP2BIN = $ENV{'EXE_BZIP2'} ||'bzip2';
my $MINMASKLEN = 1000_000; # mask longer (intergenic, repetitive) fragments with -H
my $GENEMARGIN = 5000; # do not mask gene margins
my $DUMMYSCORE = 9999;
# while parsing PAF
my $MINQUAL = 50; # works well with minimap2
my $MINALNLEN = 100; # min alignment length when transforming gene coords on WGA
my $MINOVERLAP = 0.50;
my $MINPERCID = 95.0; # min %sequence identity of gene alignment extracted from WGA
my $VERBOSE = 0; # values > 1
my ( $help, $do_sequence_check, $reuse, $noheader, $repetitive) = (0, 0, 0, 0, 0);
my ($dowfmash, $dogsalign, $patch, $split_chr_regex, $tmpdir ) = (0, 0, 0, '', '');
my ( $sp1, $fasta1, $gff1, $sp2, $fasta2, $gff2, $index_fasta1 ) =
('', '', '', '', '', '', '');
my ( $fasta1orig, $fasta2orig ) = ('', '');
my ( $chr, $chrfasta1, $chrfasta2, $splitPAF, $ref_chr_pairs, $cmd, $gene, $outfilename );
my ( $indexonly, $no_inversions, $minoverlap, $qual, $min_perc_ident, $alg, $outANIfile ) =
( 0, 0, $MINOVERLAP, $MINQUAL, $MINPERCID, 'minimap2', '' );
my ( $minimap_path, $wfmash_path, $gsalign_path, $bedtools_path, $samtools_path ) =
( $MINIMAP2EXE, $WFMASHEXE, $GSALIGNPATH, $BEDTOOLSEXE, $SAMTOOLSEXE );
my $threads = $THREADS;
GetOptions(
"help|?" => \$help,
"sp1|species1=s" => \$sp1,
"fa1|fasta1=s" => \$fasta1,
"gf1|gff1=s" => \$gff1,
"sp2|species2=s" => \$sp2,
"fa2|fasta2=s" => \$fasta2,
"gf2|gff2=s" => \$gff2,
"out|outfile=s" => \$outfilename,
"ovl|overlap=f" => \$minoverlap,
"p|patch" => \$patch,
"q|quality=i" => \$qual,
"m|minident=f" => \$min_perc_ident,
"s|split=s" => \$split_chr_regex,
"c|check" => \$do_sequence_check,
"r|reuse" => \$reuse,
"i|index" => \$indexonly,
"n|noinvs" => \$no_inversions,
"wf|wfmash" => \$dowfmash,
"gs|gsalign" => \$dogsalign,
"M|minipath=s" => \$minimap_path,
"W|wfpath=s" => \$wfmash_path,
"G|gspath=s" => \$gsalign_path,
"B|btpath=s" => \$bedtools_path,
"S|stpath=s" => \$samtools_path,
"T|tmpath=s" => \$tmpdir,
"t|threads=i" => \$threads,
"H|highrep" => \$repetitive,
"A|ANI=s" => \$outANIfile,
"a|add" => \$noheader
) || help_message();
sub help_message {
print "\nusage: $0 [options]\n\n"
. "-sp1 binomial/trinomial species name (required, example: -sp1 oryza_sativa)\n"
. "-fa1 genome FASTA [.gz] filename (required, example: -fa1 oryza_sativa.fna, use bgzip with -wf)\n"
. "-gf1 GFF [.gz] filename (required, example: -gf1 oryza_sativa.RAPDB.gff)\n"
. "-sp2 binomial/trinomial species name (required, example: -sp2 oryza_nivara_OGE)\n"
. "-fa2 genome FASTA [.gz] filename (required, example: -fa2 oryza_nivara.fna)\n"
. "-gf2 GFF [.gz] filename (required, example: -gf2 oryza_nivara.OGE.gff)\n"
. "-out output filename (TSV format) (optional, by default built from input, example: -out rice.tsv)\n"
. "-p use patched gene models (optional, forces recalculation of gene overlaps)\n"
. "-ovl min overlap of genes (optional, default: -ovl $MINOVERLAP)\n"
. '-s split genome in chrs (optional, requires regex to match chr names ie: -s \'^\d+$\')'. "\n"
. "-n dont map genes in inversions (optional, by default all genes are mapped on WGAs on both strands\n"
. "-wf use wfmash aligner (optional, requires samtools ; by default minimap2 is used)\n"
. "-gs use GSAlign aligner (optional, by default minimap2 is used)\n"
. "-q min mapping quality, minimap2 only (optional, default: -q $MINQUAL)\n"
. "-m min gene %sequence identity (optional, default: -m $MINPERCID)\n"
. "-M path to minimap2 binary (optional, default: -M $MINIMAP2EXE)\n"
. "-W path to wfmash binary (optional, default: -W $WFMASHEXE)\n"
. "-G path to GSAlign bin/ (optional, default: -G $GSALIGNPATH)\n"
. "-B path to bedtools binary (optional, default: -B $BEDTOOLSEXE)\n"
. "-S path to samtools binary (optional, default: -S $SAMTOOLSEXE)\n"
. "-T path for temporary files (optional, default current folder)\n"
. "-t CPU threads to use (optional, default: -t $THREADS)\n"
. "-H highly repetitive genome (optional, masks intergenes >= $MINMASKLEN & tweaks minimap2)\n"
. "-A output ANI filename (optional, requires -gs, example: out.ani)\n"
#. "-c check sequences of collinear genes (optional)\n"
. "-add concat TSV output with no header (optional, example: -add, requires -out)\n"
. "-r re-use previous results & index (optional, partially overriden by -p)\n"
. "-i make index & tmp files, dont align (optional, requires -sp1 -fa1 -gf1)\n";
}
if ( $help
|| (!$sp1 || !$fasta1 || !$gff1 || !$sp2 || !$fasta2 || !$gff2) ) {
help_message();
exit(0);
}
if ( !-s $fasta1 || !-s $gff1 || !-s $fasta2 || !-s $gff2 ) {
print "# ERROR: please make sure all input files exist\n";
exit(0);
}
if ( !$indexonly && $sp1 eq $sp2 ) {
print "# ERROR: please make sure -sp1 and sp2 are different\n";
exit(0);
}
if ( $minoverlap && ( $minoverlap < 0 || $minoverlap > 1 ) ) {
print "# ERROR: option -ovl requires values [0,1]\n";
exit(0);
}
if ( $qual && ( $qual < 0 || $qual > 255 ) ) {
print "# ERROR: option -q requires values [0,255]\n";
exit(0);
}
if ( $min_perc_ident && ( $min_perc_ident < 0 || $min_perc_ident > 100 ) ) {
print "# ERROR: option -m requires values [0,100]\n";
exit(0);
}
# add actual value to dummy values in param string
$BEDINTSCPAR =~ s/XXX/$minoverlap/g;
if ( $noheader && !$outfilename ) {
print "# ERROR: option -add requires -out filename to concat results\n";
exit(0);
}
# check algorithm, reset min mapping quality if wfmash
# https://github.com/ekg/wfmash/issues/96
if ($dowfmash) {
$alg = 'wfmash';
$qual = 1;
} elsif($dogsalign) {
$alg = 'gsalign';
} elsif($repetitive) {
#see https://github.com/lh3/minimap2/issues/813
$MINIMAPPARS .= " -f100 ";
# see also ideas in
# https://github.com/lh3/minimap2/issues/354
}
if(!$dogsalign){
$outANIfile = ''
}
if($tmpdir ne '' && $tmpdir !~ /\/$/){
$tmpdir .= '/'
}
# set default outfile
if ( !$outfilename ) {
$outfilename = ucfirst($alg) . ".homologies.$sp1.$sp2.overlap$minoverlap.id$min_perc_ident.tsv";
if($patch) {
$outfilename = ucfirst($alg) . ".homologies.$sp1.$sp2.overlap$minoverlap.id$min_perc_ident.patch.tsv";
}
if ($split_chr_regex ne '') {
$outfilename = ucfirst($alg) . ".homologies.$sp1.$sp2.overlap$minoverlap.id$min_perc_ident.split.tsv";
if($patch) {
$outfilename = ucfirst($alg) . ".homologies.$sp1.$sp2.overlap$minoverlap.id$min_perc_ident.split.patch.tsv";
}
}
}
print "\n# $0 -sp1 $sp1 -fa1 $fasta1 -gf1 $gff1 "
. "-sp2 $sp2 -fa2 $fasta2 -gf2 $gff2 -out $outfilename -p $patch -a $noheader -m $min_perc_ident "
. "-ovl $minoverlap -q $qual -wf $dowfmash -gs $dogsalign -A $outANIfile -c $do_sequence_check "
. "-s '$split_chr_regex' -M $minimap_path -W $wfmash_path -G $gsalign_path -B $bedtools_path "
. "-T $tmpdir -t $threads -i $indexonly -r $reuse -H $repetitive -n $no_inversions\n\n";
# save names of original input FASTA files as $fasta1/$fasta2 might change with -H
$fasta1orig = $fasta1;
$fasta2orig = $fasta2;
# check binaries
if(`$bedtools_path` !~ 'sage') {
print "# ERROR: cannot find binary file $bedtools_path , exit\n";
exit(-1)
}
if ($dowfmash) {
if(`$wfmash_path` !~ 'OPTIONS') {
print "# ERROR: cannot find binary file $wfmash_path , exit\n";
exit(-2)
} elsif (`$samtools_path 2>&1` !~ 'Usage') {
print "# ERROR: cannot find binary file $samtools_path , exit\n";
exit(-3)
}
} elsif($dogsalign) {
$GSAINDXEXE = "$gsalign_path/$GSAINDXEXE";
$GSALIGNEXE = "$gsalign_path/$GSALIGNEXE";
if(`$GSALIGNEXE 2>&1` !~ 'Usage') {
print "# ERROR: cannot find binary file $GSALIGNEXE , exit\n";
exit(-4)
}
} else {
if(!`$minimap_path 2>&1` || `$minimap_path 2>&1` !~ 'Usage') {
print "# ERROR: cannot find binary file $minimap_path , exit\n";
exit(-5)
}
}
print "# mapping parameters:\n";
if($repetitive) {
print "# \$MINMASKLEN: $MINMASKLEN\n";
}
if ($dowfmash) {
print "# \$WFMASHPARS: $WFMASHPARS\n\n";
} elsif ($dogsalign) {
print "# \$GSALIGNPARS: $GSALIGNPARS\n\n";
} else {
print "# \$MINIMAPPARS: $MINIMAPPARS\n\n";
}
## 1) Parse GFFs and produce BED files with gene coords
my $geneBEDfile1 = $tmpdir . "_$sp1.gene.bed";
my $geneBEDfile2 = $tmpdir . "_$sp2.gene.bed";
if($patch) {
$geneBEDfile1 = $tmpdir . "_$sp1.gene.patch.bed";
$geneBEDfile2 = $tmpdir . "_$sp2.gene.patch.bed";
}
if($reuse && -s $geneBEDfile1 && check_BED_format($geneBEDfile1) &&
(!$patch || !$indexonly) ) {
print "# re-using $geneBEDfile1\n";
} else {
my ( $num_genes1, $mean_gene_len1 ) = parse_genes_GFF( $gff1, $geneBEDfile1 );
if(check_BED_format($geneBEDfile1)) {
printf( "# %d genes parsed in %s mean length=%d\n",
$num_genes1, $gff1, $mean_gene_len1 );
} else {
die "# ERROR: failed parsing genes from $gff1\n";
}
}
if(!$indexonly) {
# $geneBEDfile2 will be re-used if possible even with $patch if !$indexonly,
# as patched BED files are generated earlier with $indexonly
if($reuse && -s $geneBEDfile2 && check_BED_format($geneBEDfile2)) {
print "# re-using $geneBEDfile2\n";
} else {
my ( $num_genes2, $mean_gene_len2 ) = parse_genes_GFF( $gff2, $geneBEDfile2 );
if(check_BED_format($geneBEDfile2)) {
printf( "# %d genes parsed in %s mean length=%d\n",
$num_genes2, $gff2, $mean_gene_len2 );
} else {
die "# ERROR: failed parsing genes from $gff2\n";
}
}
}
# 1.1) if requested (long, repetitive genomes) mask long intergenes of $sp1
if($repetitive) {
my $masked_fasta1 = $tmpdir . "_$sp1.mask.fna";
my $fasta_length1 = $tmpdir . "_$sp1.tsv";
my $maskBEDfile1 = $tmpdir . "_$sp1.mask.bed";
if($reuse && -s $maskBEDfile1) {
print "# re-using $maskBEDfile1\n";
} else {
my ($total_masked1, $median_length1) = mask_intergenic_regions(
$fasta1,$geneBEDfile1,
$masked_fasta1, $fasta_length1, $maskBEDfile1,
$MINMASKLEN,$GENEMARGIN,$bedtools_path);
printf("# %s bases masked=%d median intergene length=%d\n",
$sp1, $total_masked1, $median_length1 );
}
my $masked_fasta2 = $tmpdir . "_$sp2.mask.fna";
my $fasta_length2 = $tmpdir . "_$sp2.tsv";
my $maskBEDfile2 = $tmpdir . "_$sp2.mask.bed";
if(!$indexonly) {
if($reuse && -s $maskBEDfile2) {
print "# re-using $maskBEDfile2\n";
} else {
my ($total_masked2, $median_length2) = mask_intergenic_regions(
$fasta2,$geneBEDfile2,
$masked_fasta2, $fasta_length2, $maskBEDfile2,
$MINMASKLEN,$GENEMARGIN,$bedtools_path);
printf("# %s bases masked=%d median intergene=%d\n",
$sp1, $total_masked2, $median_length2 );
}
$fasta2orig = $fasta2;
$fasta2 = $masked_fasta2;
}
}
## 2) align genome1 vs genome2 (WGA)
# split genome assemblies if required, 1/chr plus 'unplaced'
# Note: reduces complexity (good for large/polyploid genomes) but misses translocations
if ($split_chr_regex ne '') {
print "\n# splitting sequences with regex\n";
# bedtools approach (7m to 4m in wheat), requires .fai index
if(-e $fasta1.'.fai' && -e $fasta2.'.fai') {
$ref_chr_pairs =
split_genome_sequences_per_chr_bedtools($tmpdir, $fasta1, $fasta2,
$split_chr_regex, $bedtools_path, $indexonly, $reuse);
} else {
$ref_chr_pairs =
split_genome_sequences_per_chr($tmpdir, $fasta1, $fasta2,
$split_chr_regex, $indexonly, $reuse);
}
}
else {
# single reference by default
$ref_chr_pairs->{'all'} = [ $fasta1, $fasta2 ]
}
my $PAFfile = $tmpdir . "_$sp2.$sp1.$alg.paf";
if ($split_chr_regex ne '') {
$PAFfile = $tmpdir . "_$sp2.$sp1.$alg.split.paf";
}
if($repetitive) {
$PAFfile =~ s/\.paf$/.highrep.paf/;
}
if($indexonly) {
print "# indexing genome with $alg\n\n";
} else {
print "# computing pairwise genome alignment with $alg\n\n";
}
if ( $reuse && -s $PAFfile ) {
print "# re-using $PAFfile\n";
}
else {
unlink($PAFfile);
unlink($outANIfile) if($dogsalign && $outANIfile);
my (@sorted_chrs,@WGAoutfiles);
# sort chromosomes
foreach $chr (keys(%$ref_chr_pairs)) {
if($chr ne 'unplaced' && $chr ne 'all') {
push(@sorted_chrs,$chr);
}
}
@sorted_chrs = sort @sorted_chrs; # {$a<=>$b} not always numeric
if($ref_chr_pairs->{'unplaced'}) {
push(@sorted_chrs,'unplaced')
} elsif($ref_chr_pairs->{'all'}){
push(@sorted_chrs,'all')
}
foreach $chr (@sorted_chrs) {
$chrfasta1 = $ref_chr_pairs->{$chr}[0];
$chrfasta2 = $ref_chr_pairs->{$chr}[1];
$splitPAF = $tmpdir . "_$sp2.$sp1.$alg.split.$chr.paf";
if($repetitive) {
$splitPAF =~ s/\.paf$/.highrep.paf/;
}
if ( $reuse && -s $splitPAF ) {
print "# re-using $splitPAF\n";
push(@WGAoutfiles, $splitPAF);
next;
}
# create empty PAF file when chr files are empty, and move to next chr
if(!-s $chrfasta1 || !-s $chrfasta2) {
open(EMPTYPAF, ">", $splitPAF);
close(EMPTYPAF);
push(@WGAoutfiles, $splitPAF);
next;
}
if ($dowfmash) {
# usually created in _cut_sequences.pl
$index_fasta1 = dirname($chrfasta1)."/".basename($chrfasta1).".fai";
if ( $reuse && -s $index_fasta1 ) {
if ($split_chr_regex ne '') {
printf("# re-using $index_fasta1, make sure same regex was used\n");
} else {
print "# re-using $index_fasta1\n";
}
} else {
$cmd = "$samtools_path faidx $chrfasta1 -o $index_fasta1 2>&1";
system($cmd);
if ( $? != 0 ) {
die "# ERROR: failed running samtools ($cmd)\n";
}
elsif ( !-s $index_fasta1 ) {
die "# ERROR: failed generating $index_fasta1 file ($cmd)\n";
}
}
next if($indexonly);
$cmd = "$wfmash_path $WFMASHPARS -t $threads $chrfasta1 $chrfasta2 > $splitPAF";
print "# $cmd\n";
system($cmd);
sleep(2);
if ( $? != 0 ) {
die "# ERROR: failed running wfmash (probably ran out of memory, $cmd , $?)\n";
} elsif ( !-e $splitPAF ) {
die "# ERROR: failed generating $splitPAF file ($cmd)\n";
} else {
push(@WGAoutfiles, $splitPAF);
}
} elsif ($dogsalign) {
my $preffix = $tmpdir . "_$sp1.$chr";
my $splitMAFpreffix = $tmpdir . "_$sp2.$sp1.$alg.split.$chr";
my $splitMAF = "$splitMAFpreffix.maf";
$index_fasta1 = "$preffix.sa";
if ( $reuse && -s $index_fasta1 ) {
if ($split_chr_regex ne '') {
printf("# re-using $index_fasta1, make sure same regex was used\n");
} else {
print "# re-using $index_fasta1\n";
}
} else {
$cmd = "$GSAINDXEXE $chrfasta1 $preffix 2>&1";
system($cmd);
if ( $? != 0 ) {
die "# ERROR: failed running bwt_index ($cmd, $?)\n";
}
elsif ( !-s $index_fasta1 ) {
die "# ERROR: failed generating $index_fasta1 file ($cmd)\n";
}
}
next if($indexonly);
$cmd = "$GSALIGNEXE $GSALIGNPARS -t $threads -i $preffix -q $chrfasta2 ".
"-o $splitMAFpreffix 2> $splitMAFpreffix.log";
print "# $cmd\n";
system($cmd);
sleep(2);
if ( $? != 0 ) {
die "# ERROR: failed running GSAlign (probably ran out of memory, $cmd, $?)\n";
} elsif ( !-e $splitMAF ) {
die "# ERROR: failed generating $splitMAF file ($cmd)\n";
} else {
# print ANI estimate
open(ANI,">>",$outANIfile) ||
die "# ERROR: cannot create $outANIfile\n";
open(GSALOG,"<","$splitMAFpreffix.log") ||
die "# ERROR: cannot find previous log $splitMAFpreffix.log\n";
while(<GSALOG>) {
if(/alignment length=(\d+)\)\s+ANI=([^\%]+)/) {
print ANI "$chr\t$2\t$1\n";
last;
}
}
close(GSALOG);
close(ANI);
# convert MAF to PAF alignment format
my $num_align = simpleMAF2PAF($splitMAF,$splitPAF);
if($num_align) {
print("# simpleMAF2PAF : %d alignments\n",$num_align);
push(@WGAoutfiles, $splitPAF);
system("$GZIPBIN -f $splitMAF");
} else {
die "# ERROR: failed converting $splitMAF file\n";
}
}
} else { # default minimap2 index & alignment
$index_fasta1 = $tmpdir . "_$sp1.$chr.mmi";
if($repetitive) {
$index_fasta1 =~ s/\.mmi$/.highrep.mmi/;
}
if ( $reuse && -s $index_fasta1 ) {
if ($split_chr_regex ne '') {
printf("# re-using $index_fasta1, make sure same regex was used\n");
} else {
print "# re-using $index_fasta1\n";
}
} else {
$cmd = "$minimap_path $MINIMAPTYPE -t $threads -d $index_fasta1 $chrfasta1";
print "# $cmd\n";
system($cmd);
if ( $? != 0 ) {
# see https://github.com/lh3/minimap2/issues/755
die "# ERROR: failed running minimap2 (probably ran out of memory, ".
"or chr too large, $cmd, $?)\n";
}
elsif ( !-s $index_fasta1 ) {
die "# ERROR: failed generating $index_fasta1 file ($cmd)\n";
}
}
next if($indexonly);
$cmd = "$minimap_path $MINIMAPPARS -t $threads $index_fasta1 $chrfasta2 -o $splitPAF";
system($cmd);
sleep(2);
if ( $? != 0 ) {
die "# ERROR: failed running minimap2 (probably ran out of memory, $cmd, $?)\n";
}
elsif ( !-e $splitPAF ) {
die "# ERROR: failed generating $splitPAF file ($cmd)\n";
}
else {
push(@WGAoutfiles, $splitPAF);
}
}
}
if(!$indexonly) {
# merge (split) PAF files
$cmd = "cat "; # assumes cat is available
foreach $splitPAF (@WGAoutfiles) {
$cmd .= "$splitPAF ";
}
$cmd .= " > $PAFfile";
system("$cmd");
if( $? != 0 ) {
die "# ERROR: failed merging split PAF files ($cmd)\n";
} else {
print("# WGA finished\n\n");
unlink(@WGAoutfiles);
}
}
}
if($indexonly) {
print "# indexes created, terminate\n";
exit(0);
}
## 3) produce BED-like file of sp2-to-sp1 coords 10 columns
my ($cigar,@tmpBEDfiles, @block_length);
my $wgaBEDfile = $tmpdir . "_$sp2.$sp1.$alg.bed";
# make up also reverse alignment,
# used to find matching sp2 segments for unpaired sp1 genes
my $wgaBEDfilerev = $tmpdir . "_$sp1.$sp2.$alg.rev.bed";
open( PAF, "<", $PAFfile ) || die "# ERROR: cannot read $PAFfile\n";
open( BED, ">", $wgaBEDfile ) || die "# ERROR: cannot create $wgaBEDfile\n";
open( BEDREV, ">", $wgaBEDfilerev ) || die "# ERROR: cannot create $wgaBEDfilerev\n";
while (<PAF>) {
#Note: $F[4] in PAF conveys whether query & ref are on the same strand or not
#Pt 1345257 118 7420 - 1 42845077 35836986 35837288 300 302 60 ... cs:Z::216*tc:69*ga:15
my @F = split( /\t/, $_ );
print BED
"$F[0]\t$F[2]\t$F[3]\t$F[4]\t$F[5]\t$F[7]\t$F[8]\t$F[9]\t$F[11]\t$F[$#F]";
# reverse CIGAR after reversing the alignment
# Note: as we only care about coords, don't do anything with substitutions
$cigar = $F[$#F];
$cigar =~ tr/ID\+\-/DI\-\+/;
print BEDREV
"$F[5]\t$F[7]\t$F[8]\t$F[4]\t$F[0]\t$F[2]\t$F[3]\t$F[9]\t$F[11]\t$cigar";
# record aligned block length
push(@block_length, $F[10]);
}
close(BED);
close(BEDREV);
close(PAF);
push(@tmpBEDfiles, $wgaBEDfile, $wgaBEDfilerev);
printf("# WGA blocks: N50 %d median %1.0f\n",
N50(\@block_length),
calc_median(\@block_length));
@block_length = ();
## 4) intersect gene positions with WGA, sort by gene > cDNA ovlp > genomic matches
my $sp2wgaBEDfile = $tmpdir . "_$sp2.gene.$sp1.$alg.intersect.overlap$minoverlap.bed";
my $sp2wgaBEDfile_sorted = $tmpdir . "_$sp2.gene.$sp1.$alg.intersect.overlap$minoverlap.sort.bed";
my $sp1wgaBEDfile = $tmpdir . "_$sp1.gene.$sp2.$alg.intersect.overlap$minoverlap.rev.bed";
my $sp1wgaBEDfile_sorted = $tmpdir . "_$sp1.gene.$sp2.$alg.intersect.overlap$minoverlap.sort.rev.bed";
$cmd = "$bedtools_path intersect -a $geneBEDfile2 -b $wgaBEDfile " .
"$BEDINTSCPAR > $sp2wgaBEDfile";
system("$cmd");
sleep(2); #latency issues
if ( $? != 0 ) {
die "# ERROR: failed running bedtools (WGA, $cmd)\n";
}
elsif ( !-s $sp2wgaBEDfile ) {
die "# ERROR: failed generating $sp2wgaBEDfile file ($cmd)\n";
}
$cmd = "$SORTBIN $SORTPARS -k4,4 -k5,5nr -k14,14nr $sp2wgaBEDfile > $sp2wgaBEDfile_sorted";
system("$cmd");
if ( $? != 0 ) {
die "# ERROR: failed sorting (WGA, $cmd)\n";
}
elsif ( !-s $sp2wgaBEDfile_sorted ) {
die "# ERROR: failed generating $sp2wgaBEDfile_sorted file ($cmd)\n";
}
# now with reversed WGA alignment
$cmd = "$bedtools_path intersect -a $geneBEDfile1 -b $wgaBEDfilerev " .
"$BEDINTSCPAR > $sp1wgaBEDfile";
system("$cmd");
sleep(2); #latency issues
if ( $? != 0 ) {
die "# ERROR: failed running bedtools (WGArev, $cmd)\n";
}
elsif ( !-s $sp1wgaBEDfile ) {
die "# ERROR: failed generating $sp1wgaBEDfile file ($cmd)\n";
}
$cmd = "$SORTBIN $SORTPARS -k4,4 -k5,5nr -k14,14nr $sp1wgaBEDfile > $sp1wgaBEDfile_sorted";
system("$cmd");
if ( $? != 0 ) {
die "# ERROR: failed sorting (WGArev, $cmd)\n";
}
elsif ( !-s $sp1wgaBEDfile_sorted ) {
die "# ERROR: failed generating $sp2wgaBEDfile_sorted file ($cmd)\n";
}
push(@tmpBEDfiles, $sp2wgaBEDfile, $sp2wgaBEDfile_sorted);
push(@tmpBEDfiles, $sp1wgaBEDfile, $sp1wgaBEDfile_sorted);
# compute coords of mapped genes
my $geneBEDfile2mapped = $tmpdir . "_$sp2.$sp1.$alg.gene.mapped.bed";
my $geneBEDfile1mapped = $tmpdir . "_$sp1.$sp2.$alg.gene.mapped.rev.bed";
my ( $ref_matched, $ref_unmatched, $perc_blocks_3genes ) =
query2ref_coords( "$fasta1orig.fai", $sp2wgaBEDfile_sorted, $geneBEDfile2mapped,
$qual, $MINALNLEN, $no_inversions, $min_perc_ident, $VERBOSE );
printf( "# %d genes mapped (%1.1f%% in 3+blocks) in %s (%d unmapped)\n\n",
scalar(@$ref_matched), $perc_blocks_3genes,
$geneBEDfile2mapped, scalar(@$ref_unmatched) );
if ( scalar(@$ref_matched) == 0 ) {
die "# ERROR: failed mapping $sp2 genes in WGA alignment";
} else {
foreach $gene (@$ref_unmatched) {
print "# unmapped: $gene\n"
}
}
# now with reversed WGA alignment, to find matching sp2 segments for unpaired sp1 genes
my ( $ref_matched1, $ref_unmatched1, $perc_blocks_3genes1 ) =
query2ref_coords( "$fasta2orig.fai", $sp1wgaBEDfile_sorted, $geneBEDfile1mapped,
$qual, $MINALNLEN, $no_inversions, $min_perc_ident, $VERBOSE );
printf( "# %d genes mapped (%1.1f%% in 3+blocks) in %s (reverse, %d unmapped)\n\n",
scalar(@$ref_matched1), $perc_blocks_3genes1,
$geneBEDfile1mapped, scalar(@$ref_unmatched1) );
if ( scalar(@$ref_matched1) == 0 ) {
die "# ERROR: failed mapping $sp1 genes in WGA alignment";
} else {
foreach $gene (@$ref_unmatched1) {
print "# unmapped: $gene\n"
}
}
## 5) produce list of pairs of collinear genes & genomic segments
my $gene_intersectBEDfile =
$tmpdir . "_$sp1.$sp2.$alg.gene.intersect.overlap$minoverlap.bed";
my $segment_intersectBEDfile =
$tmpdir . "_$sp1.$sp2.$alg.segment.intersect.overlap$minoverlap.bed";
my $segment_intersectBEDfile1 =
$tmpdir . "_$sp2.$sp1.$alg.segment.intersect.overlap$minoverlap.bed";
my $intersectBEDfile_sorted =
$tmpdir . "_$sp1.$sp2.$alg.intersect.overlap$minoverlap.sort.bed";
unlink($intersectBEDfile_sorted) if(-e $intersectBEDfile_sorted);
$cmd = "$bedtools_path intersect -a $geneBEDfile1 -b $geneBEDfile2mapped " .
"$BEDINTSCPAR -s > $gene_intersectBEDfile";
system($cmd);
sleep(2);
if ( $? != 0 ) {
die "# ERROR: failed running bedtools (genes, $cmd)\n";
}
elsif ( !-s $gene_intersectBEDfile ) {
die "# ERROR: failed generating $gene_intersectBEDfile file ($cmd)\n";
}
# now add collinear gene-genomic segments pairs
# Note: genes in such pairs can actually be $hom_gene_id
my $num_segments2 = genes_mapped2segments( $geneBEDfile2, $geneBEDfile2mapped,
$gene_intersectBEDfile, $segment_intersectBEDfile, 1 );
my $num_segments1 = genes_mapped2segments( $geneBEDfile1, $geneBEDfile1mapped,
$gene_intersectBEDfile, $segment_intersectBEDfile1, 1 );
$cmd = "$SORTBIN $SORTPARS -k1,1 -k2,2n $gene_intersectBEDfile $segment_intersectBEDfile ".
"$segment_intersectBEDfile1 > $intersectBEDfile_sorted";
system($cmd);
if ( $? != 0 ) {
die "# ERROR: failed sorting (genes, $cmd)\n";
}
elsif ( !-s $intersectBEDfile_sorted ) {
die "# ERROR: failed generating $intersectBEDfile_sorted file ($cmd)\n";
}
push(@tmpBEDfiles, $segment_intersectBEDfile, $segment_intersectBEDfile1);
push(@tmpBEDfiles, $gene_intersectBEDfile, $intersectBEDfile_sorted);
my ($num_pairs, $num_segments, $hits_per_gene) =
bed2compara( $intersectBEDfile_sorted, $geneBEDfile1, $geneBEDfile2,
$outfilename, $sp1, $sp2, $noheader);
printf( "# %d collinear gene pairs , %d collinear segments, %1.3f hits/gene\n",
$num_pairs, $num_segments, $hits_per_gene );
if($num_pairs > 0 && -s $outfilename) {
print "# TSV file: $outfilename\n";
unlink(@tmpBEDfiles);
}
#################################
# Takes string with BED filename (produced with sub parse_genes_GFF)
# and returns 1 if format is OK
sub check_BED_format {
my ( $bedfile ) = @_;
my $formatOK = 1;
open(BED, "<", $bedfile) || die "# ERROR(check_BED_format): cannot read $bedfile\n";
while(<BED>) {
if($_ !~ /^[^\t]+\t[^\t]+\t[^\t]+\t[^\t]+\t[^\t]+\t[^\t]+/) {
$formatOK = 0;
last;
}
}
close(BED);
return $formatOK
}
# Takes i) input GFF filename ii) output BED filename and
# returns i) number and ii) mean length of genes parsed.
# Uses global $DUMMYSCORE as dummy scores, as opposed to cases where
# genes/transcript are actually mapped to genome
sub parse_genes_GFF {
my ( $gff_file, $outBEDfile ) = @_;
my $num_genes = 0;
my $genelength = 0;
my ( $geneid, $magic );
# check input file format and open it accordingly
open( INFILE, $gff_file )
|| die "# ERROR(parse_genes_GFF): cannot read $gff_file, exit\n";
sysread( INFILE, $magic, 2 );
close(INFILE);
if ( $gff_file =~ /\.gz$/ || $magic eq "\x1f\x8b" ) { # GZIP compressed input{
if ( !open( GFF, "$GZIPBIN -dc $gff_file |" ) ) {
die "# ERROR(parse_genes_GFF): cannot read GZIP compressed $gff_file $!\n"
. "# please check gzip is installed\n";
}
} else {
open( GFF, "<", $gff_file )
|| die "# ERROR(parse_genes_GFF): cannot read $gff_file\n";
}
open( BED, ">", $outBEDfile )
|| die "# ERROR(parse_genes_GFF): cannot create $outBEDfile\n";
while (<GFF>) {
my @F = split( /\t/, $_ );
next if ( scalar(@F) < 9 || $F[2] ne "gene" );
# take only genes where ID can be parsed
if ( $F[8] =~ /ID=([^;]+)/ ) {
$geneid = $1;
chomp($geneid);
#$geneid =~ s/gene://; # remove redundant bits
printf( BED "%s\t%d\t%d\t%s\t%s\t%s\n",
$F[0],
$F[3] - 1, # 0-based
$F[4],
$geneid,
$DUMMYSCORE,
$F[6]
);
$num_genes++;
$genelength += ( $F[4] - $F[3] ) + 1;
}
}
close(BED);
close(GFF);
return ( $num_genes, sprintf( "%1.0f", $genelength / $num_genes ) );
}
# Takes 2 strings:
# 1) name of FASTA file
# 2) regex to match chromosome names, applied to first non-blank token (\S+)
# Returns ref to hash with chr and/or 'unplaced' as keys and sequences as value
sub read_FASTA_regex2hash {
my ($fastafile,$regex) = @_;
my ($magic,$seqname,$seq);
my %fasta;
# check input file format and open it accordingly
open(INFILE,$fastafile) || die "# ERROR(read_FASTA_regex2hash): cannot read $fastafile, exit\n";
sysread(INFILE,$magic,2);
close(INFILE);
if($fastafile =~ /\.gz$/ || $magic eq "\x1f\x8b") {
if(!open(FASTA,"$GZIPBIN -dc $fastafile |")) {
die "# ERROR(read_FASTA_regex2hash): cannot read GZIP compressed $fastafile $!\n"
."# please check gzip is installed\n";
}
} elsif($fastafile =~ /\.bz2$/ || $magic eq "BZ") {
if(!open(FASTA,"$BZIP2BIN -dc $fastafile |")){
die "# ERROR(read_FASTA_regex2hash): cannot read BZIP2 compressed $fastafile $!\n"
."# please check bzip2 is installed\n";
}
} else{ open(FASTA,"<$fastafile") ||
die "# ERROR(read_FASTA_regex2hash): cannot read $fastafile $!\n"; }
while (<FASTA>) {
next if(/^\s*$/ || /^#/);
if(/^>/) { # header
if(/^>\s*(\S+)/) {
$seqname = $1;
if($seqname !~ m/^$regex$/) { $seqname = 'unplaced_'.$seqname }
}
} else {
$fasta{$seqname} .= $_;
}
}
close(FASTA);
return \%fasta;
}
# Takes 7 params:
# 1) path to write files to
# 2) name of FASTA file (ref)
# 3) name of FASTA file (query)
# 4) regex to match chromosome names
# 5) bedtools path
# 6) indexing job (boolean)
# 7) reuse (boolean)
# Returns ref to hash with chr and/or 'unplaced' as keys and two FASTA files as value (ref, query)
# Note: 'unplaced' might hold genuine unplaced sequences but also non-shared chr names
# Note: creates FASTA & BED files with prefix _
# Note: if doindex is true only creates files for $fastafile1
sub split_genome_sequences_per_chr_bedtools {
my ($path,$fastafile1,$fastafile2,$regex,$bedtools_path,$doindex,$reuse) = @_;
my ($faifile1, $faifile2) = ( $fastafile1.'.fai' , $fastafile2.'.fai' );
my ($chr,$chrfasta1,$chrfasta2,$unplacedbed1,$unplacedbed2,$cmd);
my (%shared_chrs,%chr_pairs);
my $ref_bed1 = read_FAI_regex2hash($faifile1,$regex);
my $ref_bed2 = read_FAI_regex2hash($faifile2,$regex);
# check chr names found in both files
foreach $chr (keys(%$ref_bed1)){
if(defined($ref_bed2->{$chr}) && $chr !~ 'unplaced'){
$shared_chrs{$chr} = 1;
}
}
# write chr-specific FASTA files
foreach $chr (keys(%shared_chrs)) {
$chrfasta1 = $path . "_".basename($fastafile1).".$chr.fna";
$chrfasta2 = $path . "_".basename($fastafile2).".$chr.fna";
if(!$reuse || !-e $chrfasta1) {
$cmd = "echo '$ref_bed1->{$chr}' | $bedtools_path getfasta -fi $fastafile1 -bed stdin | " .
" perl -lne 's/^>(\\S+?):\\d+-\\d+/>\$1/; print' > $chrfasta1";
system($cmd); #print($cmd);
sleep(2);
if ( $? != 0 ) {
die "# ERROR(split_genome_sequences_per_chr_bedtools): failed running bedtools (chr, $cmd)\n";
} elsif ( !-s $chrfasta1 ) {
die "# ERROR(split_genome_sequences_per_chr_bedtools): failed generating $chrfasta1 file ($cmd)\n";
}