-
Notifications
You must be signed in to change notification settings - Fork 8
/
_cluster_analysis.pl
executable file
·1553 lines (1197 loc) · 54.5 KB
/
_cluster_analysis.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 FindBin '$Bin';
use lib "$Bin/lib";
use pangeneTools qw(parse_sequence_FASTA_file);
# Makes pan-gene analysis based on clusters of collinear genes shared by
# species in a pre-computed Minimap2/GSAlign synteny TSV file, produced by
# _collinear_genes.pl
# Adapted from https://github.com/eead-csic-compbio/get_homologues
# Copyright [2021-2024]
# EMBL-European Bioinformatics Institute & Estacion Experimental Aula Dei-CSIC
# ./_cluster_analysis.pl -T rices4_pangenes/tmp/mergedpairs.tsv -f folder \
# -s rices4_pangenes/ -r Oryza_sativa.IRGSP-1.0 -g 8 -t 3
my $BEDTOOLSEXE = 'bedtools';
my $TRANSPOSEXE =
'perl -F\'\t\' -ane \'$F[$#F]=~s/\n//g;$r++;for(1 .. @F){$m[$r][$_]=$F[$_-1]};'
. '$mx=@F;END{for(1 .. $mx){for $t(1 .. $r){print"$m[$t][$_]\t"}print"\n"}}\'';
# these globals match sequence type to extension
my @SEQTYPE = qw( cds pep cdna );
my %SEQEXT = (
'gdna' => '.gdna.fna',
'cdna' => '.cdna.fna',
'cds' => '.cds.fna',
'pep' => '.cds.faa'
);
# cluster quality control
my $MAXDISTNEIGHBORS = 2; # neighbor genes in a cluster cannot be more than N genes away
my $MINEDGESTOMERGE = 0.75;# ratio of edges connecting two clusters so they can be merged
# genome composition report
my $RNDSEED = 12345;
my $NOFSAMPLESREPORT = 5;
my ( $ref_genome, $seqfolder, $clusterdir ) = ( '', '', '' );
my ( $outfolder, $params, $bedtools_path) = ('', '', '');
my ( $help, $sp, $sp2, $show_supported, $seed );
my ( $infile, $filename, $cdsfile, $pepfile, $gdnafile );
my ( $n_core_clusters, $n_cluster_sp, $n_cluster_seqs ) = ( 0, 0, 0 );
my ( $maxdistneigh ) = ( $MAXDISTNEIGHBORS );
my ( $NOSINGLES, $dogrowth, $patch, $chregex ) = ( 0, 0, 0, '' );
my ( $n_of_species, $verbose, $min_taxa, $nointerv ) = ( 0, 0, 0, 0);
my ( @infiles, @supported_species, @ignore_species);
my ( %species, %ignore, %supported );
GetOptions(
"help|?" => \$help,
"verbose|v" => \$verbose,
"supported|l" => \$show_supported,
"TSV|T=s" => \@infiles,
"reference|r=s" => \$ref_genome,
"ignore|i=s" => \@ignore_species,
"S|S" => \$NOSINGLES,
"growth|g=i" => \$dogrowth,
"folder|f=s" => \$outfolder,
"seq|s=s" => \$seqfolder,
"mintaxa|t=i" => \$min_taxa,
"maxdist|m=i" => \$maxdistneigh,
"regex|x=s" => \$chregex,
"nointerv|n" => \$nointerv,
"patch|p" => \$patch,
#"soft|z" => \$dosoft,
"seed|R=i" => \$seed,
"bedtools|B=s" => \$bedtools_path
) || help_message();
sub help_message {
print "\nusage: $0 [options]\n\n"
. "-T input collinear TSV file(s) (required, example: -T Minimap2.homologies.rice.overlap0.5.tsv -T ...)\n"
. "-f output folder (required, example: -f myfolder)\n"
. "-r reference species_name to name clusters (required, example: -r arabidopsis_thaliana)\n"
. "-l list supported species in -T file (optional, example: -l)\n"
. "-i ignore species_name(s) (optional, example: -i selaginella_moellendorffii -i ...)\n"
. "-g do pangene set growth simulations (optional, example: -g 10; makes [core|pan_gene]*.tab files, ignores -t)\n"
. "-S skip singletons (optional, by default unclustered sequences are taken)\n"
. "-s folder with gene seqs of species in TSV (optional, default _pangenes folder, files created by _cut_sequences.pl)\n"
. "-t consider only clusters with -t taxa (optional, by default all clusters are taken)\n"
. "-m max distance among neighbor genes (optional, example: -m 10, default: $maxdistneigh)\n"
. "-x regex to match chromosomes in genome (optional, ie: -x '^\\d+\$')\n"
. "-n dont intervine non-ref pangenes with -x (optional, by default tentatively placed among ref pangenes)\n"
. "-p use patched sequences (optional, expects patch.SEQEXT extension)\n"
. "-R random seed for genome growth analysis (optional, requires -g, example -R 1234)\n"
. "-B path to bedtools binary (optional, default: -B bedtools)\n"
#. "-z add soft-core to genome growth analysis (optional)\n"
. "-v verbose (optional, example: -v)\n";
exit(0);
}
if ($help) { help_message() }
if ($show_supported) {
print "# $0 -l \n\n";
}
else {
if ( scalar(@infiles) < 1 ) {
print "# ERROR: need at least one valid input TSV file\n\n";
exit;
}
else {
$clusterdir = $ref_genome;
$clusterdir =~ s/_//g;
}
if($seqfolder && $seqfolder !~ /\/$/){
$seqfolder .= '/';
}
if($maxdistneigh < 0) {
print "# ERROR: -m must be a natural number\n\n";
exit;
} else {
$maxdistneigh = int($maxdistneigh);
}
if ($NOSINGLES) {
$params .= "_nosingles";
}
#if ($patch) { $params .= "_patch" }
if(!$ref_genome) {
die "# ERROR: please set -r reference_genome\n";
}
if ( $dogrowth && $dogrowth > 0) {
$NOFSAMPLESREPORT = $dogrowth;
if($seed) { $RNDSEED = $seed }
}
if ($outfolder) {
if ( -e $outfolder ) {
print "\n# WARNING : folder '$outfolder' exists, files might be overwritten\n\n";
} else {
if ( !mkdir($outfolder) ) {
die "# ERROR: cannot create $outfolder\n";
}
}
# save list of input file names for future reference
open(INLOG,">","$outfolder/input.log") ||
die "# ERROR: cannot create $outfolder/input.log\n";
foreach $infile (@infiles) {
print INLOG "$infile\n";
}
close(INLOG);
# create $clusterdir with $params
$clusterdir .= $params;
if ( !-e "$outfolder/$clusterdir" ) {
if ( !mkdir("$outfolder/$clusterdir") ) {
die "# ERROR: cannot create $outfolder/$clusterdir\n";
}
}
}
else {
print
"# ERROR: need a valid output folder, such as -f Brassicaceae\n\n";
exit;
}
print "# $0 -r $ref_genome -f $outfolder -g $dogrowth -S $NOSINGLES -m $maxdistneigh ".
"-v $verbose -t $min_taxa -x $chregex -p $patch -R $RNDSEED -B $bedtools_path\n";
print "# ";
foreach $infile (@infiles) {
print "-T $infile ";
} print "\n";
if (@ignore_species) {
print "# ";
foreach $sp (@ignore_species) {
$ignore{$sp} = 1;
print "-i $sp ";
} print "\n";
}
print "\n";
}
# check binaries
if(!$bedtools_path) {
$bedtools_path = $BEDTOOLSEXE
}
if(`$bedtools_path` !~ 'sage') {
print "# ERROR: cannot find binary file $bedtools_path , exit\n";
exit(-1)
}
## 1) check (supported) species in TSV file(s)
foreach $infile (@infiles){
open(TSV,"<",$infile) || die "# ERROR: cannot read $infile\n";
while(<TSV>){
my @F = split(/\t/,$_);
($sp, $sp2) = ($F[2], $F[7]);
$species{$sp} = 1;
$species{$sp2} = 1;
}
close(TSV);
}
# add species but skip ignored ones and ref
for $sp (keys(%species)) {
next if( $ignore{$sp} || $sp eq 'species' || $sp eq 'homology_species');
$n_of_species++;
$supported{ $sp } = $n_of_species;
if ( !$ref_genome || $sp ne $ref_genome ) {
push( @supported_species, $sp );
}
}
# check reference genome is supported
if ( $ref_genome && !$supported{$ref_genome} ) {
die "# ERROR: cannot find $ref_genome in input TSV file(s)\n";
}
else {
# ref genome is first in array
unshift( @supported_species, $ref_genome );
if ($verbose) {
foreach $sp (@supported_species) {
print "# $sp $supported{ $sp }\n";
}
}
}
if($show_supported) {
foreach $sp (@supported_species) {
print "$sp\n";
}
exit(0);
}
print "\n# clustering parameters:\n";
print "# \$MAXDISTNEIGHBORS: $MAXDISTNEIGHBORS\n";
print "# \$MINEDGESTOMERGE: $MINEDGESTOMERGE\n\n";
print "# total selected species : $n_of_species\n\n";
## 2) parse pairs of collinear genes and make up clusters
my ( $chr, $cluster_id, $cluster_id2, $seqtype, $coords_id ) = ( '', 0 );
my ( $line, $stable_id, $segment_species, $coords, $segment_coords );
my ( $ref_geneid, $ref_fasta, $ref_coords, $segment_cluster, $num_segments );
my ( @sorted_chrs, %sorted_cluster_ids, %segment_species );
my ( %incluster, %cluster, %sequence, %segment, %segment_sequence );
my ( %totalgenes, %totalclusters, %totaloverlap, %POCS_matrix );
my ( %unclustered, %sorted_ids, %id2coords );
my ( %cluster_links, %toremove, @tmp_cluster_ids, @cluster_ids );
my (
$gene_stable_id, $prot_stable_id, $species,
$overlap, $homology_type, $hom_gene_stable_id,
$hom_prot_stable_id, $hom_species, $hom_identity,
$dn, $ds, $goc_score,
$wga_coverage, $high_confidence,
$coordinates
);
# 2.1) Parse FASTA files to get main cluster sequences (@SEQTYPE),
# cDNA file is is where genes get their genomic coordinates
# Note1: if a gene lacks a cDNA will be skipped
# Note2: there might be 1+ sequences for the same gene, same species in GFF
foreach $species (@supported_species) {
# init, see below
$unclustered{$species} = 0;
foreach $seqtype (@SEQTYPE) {
$filename = "$seqfolder$species$SEQEXT{$seqtype}";
if($patch) {
$filename = "$seqfolder$species.patch$SEQEXT{$seqtype}";
}
if(!-s $filename){
die "# ERROR: cannot find sequence file $filename, set path with -seq\n";
}
( $ref_geneid, $ref_fasta, $ref_coords ) = parse_sequence_FASTA_file( $filename );
# save these sequences
foreach $gene_stable_id ( @$ref_geneid ) {
$sequence{$species}{$gene_stable_id}{$seqtype} = $ref_fasta->{$gene_stable_id};
}
# log
open(INLOG,">>","$outfolder/input.log") ||
die "# ERROR: cannot create $outfolder/input.log\n";
print INLOG "$filename\n";
close(INLOG);
# take gene coordinates only once,
# only genes with cDNA sequences are considered.
# WARNING: rRNA, tRNA genes don't have cDNA features
if($seqtype eq 'cdna') {
$sorted_ids{$species} = $ref_geneid;
$id2coords{$species} = $ref_coords;
# count number of genes in this species
$totalgenes{$species} = scalar(@$ref_geneid);
}
}
}
# 2.2) actually parse pairs of collinear genes to grow clusters
# columns of TSV file as produced by get_collinear_genes.pl:
#gene:BGIOSGA002571 gene:BGIOSGA002571 Oryza_indica.ASM465v1.chr1 2418 ortholog_collinear
# gene:ONIVA01G00120 gene:ONIVA01G00120 Oryza_nivara_v1.chr1 2418 NULL NULL NULL 100.00 1 1:39544-42130(+);1:116435-120177(+)
#Oryza_indica.ASM465v1.chr1:1:222338-228913 segment Oryza_indica.ASM465v1.chr1 6575 segment_collinear
# gene:ONIVA01G00200 gene:ONIVA01G00200 Oryza_nivara_v1.chr1 6575 NULL NULL NULL 100.00 1 1:222338-228913(+);1:160018-166571(+)
# NOTE: wga_cov,dn,ds,goc are not computed and have dummy values
# Iteratively get & parse TSV files that define pairs of collinear genes (made with _collinear_genes.pl)
# Clusters are first created as pairs and grow as new collinear genes from other species are added.
# In some cases selected clusters will be merged on a second step.
# Note: Assumes TSV files have been sorted by $gene_stable_id and $overlap (see get_pangenes.pl) and
# warns (-v) about conflicting (with sequences from same species) or
# partially overlapping clusters (disjoint species, not enough links/edges to merge)
print "# parsing TSV files\n";
foreach $infile (@infiles) {
open(TSV, "<", $infile)
|| die "# ERROR: cannot open $infile\n";
while ( $line = <TSV> ) {
( $gene_stable_id, $prot_stable_id, $species,
$overlap, $homology_type, $hom_gene_stable_id,
$hom_prot_stable_id, $hom_species, $hom_identity,
$dn, $ds, $goc_score,
$wga_coverage, $high_confidence,
$coordinates
) = split( /\t/, $line );
next if ( !$supported{$species} || !$supported{$hom_species} );
if ( $homology_type =~ m/ortholog/ ) {
if($verbose) {
if(!defined($id2coords{$species}{$gene_stable_id}[1])) {
print "# WARN: skip gene model $species $gene_stable_id as it lacks cDNA (no coordinates)\n";
next;
} elsif(!defined($id2coords{$hom_species}{$hom_gene_stable_id}[1])) {
print "# WARN: skip gene model $hom_species $hom_gene_stable_id as it lacks cDNA (no coordinates)\n";
next;
}
}
# add $species gene to cluster only if not clustered yet
if ( !$incluster{ $supported{$species}.':::'.$gene_stable_id } ) {
if ( $incluster{ $supported{$hom_species}.':::'.$hom_gene_stable_id } ) {
# use existing cluster_id from other species ortholog
$cluster_id = $incluster{ $supported{$hom_species}.':::'.$hom_gene_stable_id };
} else {
# otherwise create a new one
$cluster_id = $supported{$species}.':::'.$gene_stable_id;
push( @tmp_cluster_ids, $cluster_id );
}
# record to which cluster this gene belongs
$incluster{ $supported{$species}.':::'.$gene_stable_id } = $cluster_id;
push( @{ $cluster{$cluster_id}{$species} }, $gene_stable_id );
# record overlap
$totaloverlap{$gene_stable_id} += $overlap;
} else {
# set cluster for $hom_species anyway
$cluster_id = $incluster{ $supported{$species}.':::'.$gene_stable_id };
}
# now add $hom_species gene
if ( !$incluster{ $supported{$hom_species}.':::'.$hom_gene_stable_id } ) {
# record to which cluster this gene belongs,
# currently 1st pair where $hom_gene_stable_id appears (heuristic)
$incluster{ $supported{$hom_species}.':::'.$hom_gene_stable_id } = $cluster_id;
push( @{ $cluster{$cluster_id}{$hom_species} }, $hom_gene_stable_id);
# record overlap
$totaloverlap{$hom_gene_stable_id} += $overlap;
} else { # $hom_species gene already clustered
# typically when a long gene model overlaps 2+ shorther ones
if($cluster_id ne $incluster{ $supported{$hom_species}.':::'.$hom_gene_stable_id }) {
$cluster_links{ $cluster_id }{ $incluster{ $supported{$hom_species}.':::'.$hom_gene_stable_id } }++;
$cluster_links{ $incluster{ $supported{$hom_species}.':::'.$hom_gene_stable_id } }{ $cluster_id }++;
}
#else { } # do nothing, previously added to same cluster
}
} elsif($homology_type =~ m/segment_collinear/) {
chomp($coordinates);
# record coords of this gene-segment pair
if($prot_stable_id eq 'segment') {
$stable_id = $hom_gene_stable_id;
$segment_species = $species;
$species = $hom_species;
($segment_coords, $coords) = split(/;/,$coordinates);
} else {
$stable_id = $gene_stable_id;
$segment_species = $hom_species;
($coords, $segment_coords) = split(/;/,$coordinates);
}
# assign coords to stable_id
$segment{$stable_id}{$species} = $coords;
$segment{$stable_id}{$segment_species} = $segment_coords;
}
}
close(TSV);
} print "\n";
# 2.3) see if disjoint clusters can be merged, can happen if long genes overlap shorther ones
my ($c1, $c2, $size1, $size2, $speciesOK);
foreach $c1 (0 .. $#tmp_cluster_ids-1) {
$cluster_id = $tmp_cluster_ids[$c1];
next if(defined($toremove{ $cluster_id }));
foreach $c2 ($c1+1 .. $#tmp_cluster_ids) {
$cluster_id2 = $tmp_cluster_ids[$c2];
if(!defined($cluster_links{ $cluster_id }{ $cluster_id2 }) ||
defined($toremove{ $cluster_id2 })) {
next;
}
# check species in clusters are different (disjoint clusters)
($speciesOK, $size1) = (1, 0);
foreach $species (keys(%{ $cluster{$cluster_id} })) {
if(defined($cluster{$cluster_id2}{$species})){
$speciesOK = 0;
last;
}
# get size of cluster1 as you go
$size1 += scalar(@{ $cluster{$cluster_id}{$species} });
}
if($speciesOK == 0){
print "# WARN: conflicting clusters $cluster_id & $cluster_id2 ($species)\n" if($verbose);
next;
}
# get size of cluster2
$size2 = 0;
foreach $species (keys(%{ $cluster{$cluster_id2} })) {
$size2 += scalar(@{ $cluster{$cluster_id2}{$species} });
}
# is there evidence to merge these clusters?
if($cluster_links{ $cluster_id }{ $cluster_id2 } >= $MINEDGESTOMERGE * $size1 * $size2) {
# actually merge cluster2 to cluster1, requires updating data structures
foreach $species (keys(%{ $cluster{$cluster_id2} })) {
foreach $hom_gene_stable_id (@{ $cluster{$cluster_id2}{$species} }) {
# copy gene ids from cluster2 to cluster, for all species
push(@{ $cluster{$cluster_id}{$species} }, $hom_gene_stable_id);
# change to which cluster_id those genes now belong
$incluster{ $supported{$species}.':::'.$hom_gene_stable_id } = $cluster_id;
}
}
delete($cluster{$cluster_id2});
$toremove{ $cluster_id2 } = 1;
print "# WARN: merged clusters $cluster_id & $cluster_id2 " .
"($cluster_links{ $cluster_id }{ $cluster_id2 },$size1,$size2)\n" if($verbose);
} else {
print "# WARN: partially overlapping clusters $cluster_id & $cluster_id2 " .
"($cluster_links{ $cluster_id }{ $cluster_id2 },$size1,$size2)\n" if($verbose);
}
}
} print "\n";
# remove individual clusters (merged) from cluster list
foreach $cluster_id (@tmp_cluster_ids) {
next if($toremove{ $cluster_id });
push(@cluster_ids,$cluster_id);
}
@tmp_cluster_ids=();
undef(%toremove);
#foreach $cluster_id (@cluster_ids) {
# next if($cluster_id !~ '1:::BaRT2v18chr3HG163450'); &&
# foreach $species (@supported_species) {
# foreach $gene_stable_id ( @{ $cluster{$cluster_id}{$species} } ) {
# print "$cluster_id $gene_stable_id\n"; }}}
# 2.4) Write BED & FASTA files with genomic segments (gdna), one per species,
# and store them in a hash with (species,coords) keys
foreach $species (@supported_species) {
$num_segments = 0;
# write BED
$filename = "$seqfolder$species.gdna.bed";
open(GDNA,">",$filename) ||
die "# ERROR: cannot create $filename\n";
foreach $stable_id (keys(%segment)) {
next if(!defined($segment{$stable_id}{$species}));
#1:125929-131075(+)
#UN-Ctg123:12-1234(-)
$coords_id = $segment{$stable_id}{$species};
if($coords_id =~ m/^(\S+)?:(\d+)-(\d+)\(([+-])\)/) {
print GDNA "$1\t$2\t$3\tNA\t0\t$4\n";
$num_segments++;
}
}
close(GDNA);
# extract segments with help from bedtools
my $FASTAgenome_file = "$seqfolder\_$species.fna";
my $outFASTAfile = "$seqfolder$species.gdna.fna";
if($num_segments) {
my $cmd = "$bedtools_path getfasta -fi $FASTAgenome_file -bed $filename -s -fo $outFASTAfile";
system("$cmd");
sleep(2);
if ( $? != 0 ) {
die "# ERROR: failed running bedtools ($cmd)\n";
}
elsif ( !-s $outFASTAfile ) {
die "# ERROR: failed generating $outFASTAfile file ($cmd)\n";
}
}
print "# $outFASTAfile : $num_segments genomic segments\n";
$filename = "$seqfolder$species$SEQEXT{'gdna'}";
if(!-s $filename){
print "# WARN: cannot find sequence file $filename, skip it\n" if($verbose);
next;
}
my $ref_fasta = parse_GETFASTA_file( $filename, $species );
foreach $coords_id ( keys(%$ref_fasta) ) {
$segment_sequence{$species}{$coords_id} = $ref_fasta->{$coords_id};
}
# log
open(INLOG,">>","$outfolder/input.log") ||
die "# ERROR: cannot create $outfolder/input.log\n";
print INLOG "$filename\n";
close(INLOG);
} print "\n";
# 2.5) quality control of clusters, criteria:
# i) genes from same species should be neighbors, else should be removed
# ii) genes from same species should be ordered along chr
my ($best_index, $best_gene_stable_id, $index, $index_dist);
my ($main_cluster_id, $new_cluster_id, $gene_id);
foreach $cluster_id (@cluster_ids) {
#next if($cluster_id !~ 'Os01g0116250'); #1:::HORVU.MOREX.r3.3HG0311160'); #gene:BGIOSGA000009'); #debug
# set main cluster id, note it can be updated within the loop
$main_cluster_id = $cluster_id;
foreach $species (@supported_species) {
if( defined($cluster{$main_cluster_id}{$species}) &&
scalar(@{ $cluster{$main_cluster_id}{$species} }) > 1 ) {
my (@checked_ids);
# rank genes in terms of cumulative overlap
my @ranked_ids = sort {$totaloverlap{$b}<=>$totaloverlap{$a}}
@{ $cluster{$main_cluster_id}{$species} };
# get index of gene with highest overlap
$best_gene_stable_id = shift(@ranked_ids); #$best_gene_stable_id = pop(@ranked_ids); #debug
$best_index = _get_element_index($sorted_ids{$species},$best_gene_stable_id);
push(@checked_ids, $best_gene_stable_id);
# iteratively compute index distance of remaining genes
foreach $gene_stable_id (@ranked_ids) {
$index = _get_element_index($sorted_ids{$species},$gene_stable_id);
$index_dist = abs($index - $best_index);
# remove/uncluster genes that are no neighbors
if($index_dist > $maxdistneigh) {
#if($index_dist > $maxdistneigh || $gene_stable_id eq 'gene:BGIOSGA000009') { # debug
# create separate singleton cluster for this gene
# original cluster was named after this gene,
# we'll need to create a new one and set it as main cluster
# NOTE: this can only happen once per cluster
if(defined($cluster{ $supported{$species}.':::'.$gene_stable_id })) {
# copy original cluster to new main cluster id
$new_cluster_id = $supported{$species}.':::'.$best_gene_stable_id;
foreach $sp2 (@supported_species) {
next if($sp2 eq $species);
foreach $gene_id (@{ $cluster{$cluster_id}{$sp2} }) {
push(@{ $cluster{$new_cluster_id}{$sp2}}, $gene_id);
$incluster{ $supported{$sp2}.':::'.$gene_id } = $new_cluster_id;
}
}
# update main cluster id and add it to list
$main_cluster_id = $new_cluster_id;
push( @cluster_ids, $main_cluster_id );
# replace original cluster with singleton
$cluster{$cluster_id} = ();
push(@{ $cluster{$cluster_id}{$species}}, $gene_stable_id);
if($verbose) {
print "# WARN: remove $gene_stable_id from cluster $cluster_id => ".
"$main_cluster_id ($index_dist)\n";
}
} else { # new cluster with new cluster_id
$new_cluster_id = $supported{$species}.':::'.$gene_stable_id;
$incluster{ $supported{$species}.':::'.$gene_stable_id } = $new_cluster_id;
push( @{ $cluster{$new_cluster_id}{$species} }, $gene_stable_id );
push( @cluster_ids, $new_cluster_id );
if($verbose) {
print "# WARN: remove $gene_stable_id from cluster $cluster_id ($index_dist)\n";
}
$unclustered{$species}++;
}
} else { # gene passes QC
push(@checked_ids, $gene_stable_id);
}
}
# rank genes in terms of chr position
@checked_ids = sort {
$id2coords{$species}{$a}[1] <=>
$id2coords{$species}{$b}[1]
}
@checked_ids;
# updated species gene_ids in main cluster
$cluster{$main_cluster_id}{$species} = \@checked_ids;
}
}
}
#foreach $sp2 (@supported_species){ foreach $gene_id (@{ $cluster{'gene:BGIOSGA000010'}{$sp2} }) { print "$gene_id\n" } }
%totaloverlap = (); # not needed anymore
# count how many clusters include each species
foreach $cluster_id (@cluster_ids) {
foreach $species (@supported_species) {
if ( $cluster{$cluster_id}{$species} ) {
$totalclusters{$species}++;
}
}
}
# 2.6) add unpaired sequences as singletons
my $total_seqs = 0;
foreach $species (@supported_species) {
my $singletons = 0;
foreach $gene_stable_id ( @{ $sorted_ids{$species} } ) {
next if ( $NOSINGLES || $incluster{ $supported{$species}.':::'.$gene_stable_id } );
# create new cluster
$cluster_id = $supported{$species}.':::'.$gene_stable_id;
$incluster{ $supported{$species}.':::'.$gene_stable_id } = $cluster_id;
push( @{ $cluster{$cluster_id}{$species} }, $gene_stable_id );
push( @cluster_ids, $cluster_id );
# add this singleton to total clusters
$totalclusters{$species}++;
$singletons++;
}
$total_seqs += $totalgenes{$species};
printf( "# %s : sequences = %d clusters = %d (unclustered = %d , singletons = %d)\n",
$species, $totalgenes{$species}, $totalclusters{$species},
$unclustered{$species}, $singletons );
}
printf( "\n# total sequences = %d\n\n", $total_seqs );
# 2.7) create and print shadow clusters of genomic sequences
foreach $cluster_id (@cluster_ids) {
next if( scalar( keys( %{ $cluster{$cluster_id} } ) ) < $min_taxa);
if($cluster{$cluster_id}{$ref_genome}) {
$filename = $cluster{$cluster_id}{$ref_genome}[0]
} else {
$filename = (split(/:::/,$cluster_id))[1];
}
my ($new,%seen) = (0);
$segment_cluster = '';
foreach $species (@supported_species) {
next if ( !$cluster{$cluster_id}{$species} );
my $segment_seqs_OK = 0;
foreach $stable_id (@{ $cluster{$cluster_id}{$species} }) {
next if(!$segment{$stable_id}{$species});
# sp1, found both in cluster and in segment pair
if(!$seen{$species}) {
$coords_id = $segment{$stable_id}{$species};
$segment_cluster .= $segment_sequence{$species}{$coords_id};
$segment_seqs_OK++;
$seen{$species}=1;
}
# sp2, which might be missing from cluster
foreach $sp (@supported_species) {
next if(!$segment{$stable_id}{$sp} || $seen{$sp});
$coords_id = $segment{$stable_id}{$sp};
$segment_cluster .= $segment_sequence{$sp}{$coords_id};
$segment_seqs_OK++;
$seen{$sp}=1;
if(!$cluster{$cluster_id}{$sp}) {
$new++
}
last;
}
}
if($segment_seqs_OK) {
$segment_species{$cluster_id} += $segment_seqs_OK;
}
}
# these are regular clusters; genuine segments have 2+ species
if(!$segment_species{$cluster_id} || $segment_species{$cluster_id} < 2 || $new < 1) {
$segment_species{$cluster_id} = 0;
next;
}
open( CLUSTER, ">", "$outfolder/$clusterdir/$filename$SEQEXT{'gdna'}" )
|| die "# ERROR: cannot create $outfolder/$clusterdir/$filename$SEQEXT{'gdna'}\n";
print CLUSTER $segment_cluster;
close(CLUSTER);
}
%segment_sequence = (); # not needed anymore
# 3) write main sequence clusters, summary text file and POCS matrix
# POCS=Percent Conserved Sequences (POCS) matrix
my $POCS_matrix_file = "$outfolder/POCS.matrix$params\.tab";
my $cluster_summary_file = "$outfolder/$clusterdir.cluster_list";
open( CLUSTER_LIST, ">", $cluster_summary_file )
|| die "# ERROR: cannot create $cluster_summary_file\n";
$n_core_clusters = 0;
foreach $cluster_id (@cluster_ids) {
next if(scalar( keys( %{ $cluster{$cluster_id} } ) ) < $min_taxa);
if ( scalar( keys( %{ $cluster{$cluster_id} } ) ) == $n_of_species ) {
$n_core_clusters++;
}
# create all types of sequence clusters
foreach $seqtype (@SEQTYPE) {
my ( %cluster_stats, @cluster_species );
($n_cluster_sp, $n_cluster_seqs) = (0, 0);
if($cluster{$cluster_id}{$ref_genome}) {
$filename = $cluster{$cluster_id}{$ref_genome}[0]
} else {
$filename = (split(/:::/,$cluster_id))[1];
}
# write sequences and count sequences
open( CLUSTER, ">", "$outfolder/$clusterdir/$filename$SEQEXT{$seqtype}" )
|| die "# ERROR: cannot create $outfolder/$clusterdir/$filename$SEQEXT{$seqtype}\n";
foreach $species (@supported_species) {
next if ( !$cluster{$cluster_id}{$species} );
$n_cluster_sp++;
foreach $gene_stable_id ( @{ $cluster{$cluster_id}{$species} } ) {
# no sequence printed if not available for this seqtype,
# frequently you might see cDNA clusters with empty twin CDS clusters
# for non-protein coding genes
next if(!$sequence{$species}{$gene_stable_id}{$seqtype});
print CLUSTER $sequence{$species}{$gene_stable_id}{$seqtype};
# use cDNA seq type to compute stats
if($seqtype eq 'cdna'){
$n_cluster_seqs++;
$cluster_stats{$species}++;
}
}
}
close(CLUSTER);
# cluster summary and PCOP update
# done with cDNAs, after gdna, cds & pep files have been created
if($seqtype eq 'cdna'){
@cluster_species = keys(%cluster_stats);
$cdsfile = $filename.$SEQEXT{'cds'};
$pepfile = $filename.$SEQEXT{'pep'};
$gdnafile = $filename.$SEQEXT{'gdna'};
if ( !-s "$outfolder/$clusterdir/$cdsfile" ) { $cdsfile = 'void' }
if ( !-s "$outfolder/$clusterdir/$pepfile" ) { $pepfile = 'void' }
if ( !-s "$outfolder/$clusterdir/$gdnafile" ) { $gdnafile = 'void' }
$num_segments = $segment_species{$cluster_id} || 'NA';
print CLUSTER_LIST
"cluster $filename size=$n_cluster_seqs taxa=$n_cluster_sp taxa(gdna)=$num_segments ".
"cdnafile: $filename$SEQEXT{$seqtype} cdsfile: $cdsfile pepfile: $pepfile gdnafile: $gdnafile\n";
foreach $species (@cluster_species) {
foreach $gene_stable_id ( @{ $cluster{$cluster_id}{$species} } ) {
print CLUSTER_LIST ": $species\n";
}
}
# add sequences in this cluster from a pair of species/taxa
foreach $sp ( 0 .. $#cluster_species - 1 ) {
foreach $sp2 ( $sp + 1 .. $#cluster_species ) {
$POCS_matrix{ $cluster_species[$sp] }{ $cluster_species[$sp2] } +=
$cluster_stats{ $cluster_species[$sp] };
$POCS_matrix{ $cluster_species[$sp] }{ $cluster_species[$sp2] } +=
$cluster_stats{ $cluster_species[$sp2] };
# now in reverse order to make sure it all adds up
$POCS_matrix{ $cluster_species[$sp2] }{ $cluster_species[$sp] } +=
$cluster_stats{ $cluster_species[$sp] };
$POCS_matrix{ $cluster_species[$sp2] }{ $cluster_species[$sp] } +=
$cluster_stats{ $cluster_species[$sp2] };
}
}
}
}
}
close(CLUSTER_LIST);
printf( "\n# number of clusters = %d (core = %d)\n\n",
scalar(@cluster_ids), $n_core_clusters );
print "# cluster_list = $outfolder/$clusterdir.cluster_list\n";
print "# cluster_directory = $outfolder/$clusterdir\n";
# 3.1) print POCS matrix #########################################
open( POCSMATRIX, ">$POCS_matrix_file" )
|| die "# EXIT: cannot create $POCS_matrix_file\n";
print POCSMATRIX "genomes";
foreach $sp ( 0 .. $#supported_species ) {
print POCSMATRIX "\t$supported_species[$sp]";
}
print POCSMATRIX "\n";
my (%POCS2ref,$perc);
foreach $sp ( 0 .. $#supported_species ) {
print POCSMATRIX "$supported_species[$sp]";
foreach $sp2 ( 0 .. $#supported_species ) {
if ( $sp == $sp2 ) {
print POCSMATRIX "\t100.00"
} else {
if ( $POCS_matrix{ $supported_species[$sp] }
{ $supported_species[$sp2] } )
{
$perc = sprintf("\t%1.2f",
(
100 * $POCS_matrix{ $supported_species[$sp] }
{ $supported_species[$sp2] }
) / (
$totalgenes{ $supported_species[$sp] } +
$totalgenes{ $supported_species[$sp2] }
)
);
print POCSMATRIX "$perc";
# save %POCS for all species vs reference
if($sp == 0){ $POCS2ref{$supported_species[$sp2]} = $perc }
}
else {
print POCSMATRIX "\tNA";
}
}
}
print POCSMATRIX "\n";
}
close(POCSMATRIX);
print "\n# percent_conserved_sequences_file = $POCS_matrix_file\n\n";
# sort species from ref down by decreasing POCS
my @supported_species_POCS;
# reference goes in 1st place
push(@supported_species_POCS, $ref_genome);
foreach $sp2 (sort {$POCS2ref{$b}<=>$POCS2ref{$a}} keys(%POCS2ref)) {
push(@supported_species_POCS, $sp2);
}
## 4) write pangene matrices in output folder
if(!$chregex){ # unsorted clusters
push(@{ $sorted_cluster_ids{'unsorted'} }, @cluster_ids );
}
else { # ordered along homologous chromosomes matching regex
%sorted_cluster_ids = sort_clusters_by_position(
\@supported_species_POCS, \%supported, \%sorted_ids, \%id2coords,
$chregex, \%incluster, \%cluster, $nointerv );
foreach $chr (sort keys(%sorted_cluster_ids)) {
printf("# clusters sorted by position in chr %s = %d\n",
$chr, scalar(@{ $sorted_cluster_ids{$chr} }));
}
}
# sort chromosome names, will be used later on
@sorted_chrs = sort {$a cmp $b} keys(%sorted_cluster_ids);
# set matrix filenames and write headers
my $pangene_matrix_file = "$outfolder/pangene_matrix$params\.tab";
my $pangene_gene_file = "$outfolder/pangene_matrix_genes$params\.tab";
my $pangene_matrix_tr = "$outfolder/pangene_matrix$params\.tr.tab";
my $pangene_gene_tr = "$outfolder/pangene_matrix_genes$params\.tr.tab";
my $pangene_fasta_file = "$outfolder/pangene_matrix$params\.fasta";
my $pangene_bed_file = "$outfolder/pangene_matrix$params\.tr.bed";
open( PANGEMATRIX, ">$pangene_matrix_file" )
|| die "# EXIT: cannot create $pangene_matrix_file\n";
open( PANGENEMATRIX, ">$pangene_gene_file" )
|| die "# EXIT: cannot create $pangene_gene_file\n";