script/RNAalisplit.pl untested

filter: Statementstmt 0.0% 0 / 308 Branchbran 0.0% 0 / 76 Conditioncond 0.0% 0 / 13 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 424 CC 35 SCAR 46.0
CC
35
Cov
0%
make_distance_matrix
272.0
dump_matrix
72.0
evaluate_alignment
56.0
CRAP 99.6
1 #!/usr/bin/env perl
2 # Last changed Time-stamp: <2019-01-07 00:40:43 mtw>
3 # -*-CPerl-*-
4 #
5 # usage: RNAalisplit.pl -a myfile.aln
6 #
7 # NB: Display ID handling in Bio::AlignIO is broken for Stockholm
8 # format. Use ClustalW format instead !!!
9  
10 use version; our $VERSION = qv('0.09');
11 use strict;
12 use warnings;
13 use Bio::RNA::RNAaliSplit;
14 use Bio::RNA::RNAaliSplit::WrapRNAz;
15 use Bio::RNA::RNAaliSplit::WrapRscape;
16 use Bio::RNA::RNAaliSplit::WrapRNAalifold;
17 use Bio::RNA::RNAaliSplit::WrapAnalyseDists;
18 use Getopt::Long qw( :config posix_default bundling no_ignore_case );
19 use Data::Dumper;
20 use Pod::Usage;
21 use Path::Class;
22 use File::Basename;
23 use Carp;
24 use RNA;
25 #use diagnostics;
26  
27 #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^#
28 #^^^^^^^^^^ Variables ^^^^^^^^^^^#
29 #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^#
30  
31 my $format = "ClustalW";
32 my $method = "dHn"; # SCI | dHn | dHx | dBp | dHB
33 my $rscape_stat = "GTp";
34 my $outdir = "as";
35 my $verbose = undef;
36 my $rnaz=undef;
37 my @nseqs=();
38 my ($alifile,$fi);
39 my $scaleH = 1.;
40 my $scaleB = 1.;
41 my $ribosum = 1;
42 my $show_version = 0;
43 my %foldme = (); # HoH of folded input sequences for dBp computation
44  
45 Getopt::Long::config('no_ignore_case');
46 pod2usage(-verbose => 1) unless GetOptions("aln|a=s" => \$alifile,
47 "method|m=s" => \$method,
48 "noribosum" => sub{$ribosum=0},
49 "out|o=s" => \$outdir,
50 "rscapestat=s" => \$rscape_stat,
51 "scaleH" => \$scaleH,
52 "scaleB" => \$scaleB,
53 "verbose|v" => sub{$verbose = 1},
54 "version" => sub{$show_version = 1},
55 "man" => sub{pod2usage(-verbose => 2)},
56 "help|h" => sub{pod2usage(1)}
57 );
58  
59 if ($show_version == 1){
60 print "RNAalisplit $VERSION\n";
61 exit(0);
62 }
63  
64 unless (-f $alifile){
65 warn "Could not find input file provided via --aln|-a option";
66 pod2usage(-verbose => 0);
67 }
68  
69 if($method eq "dBp" || $method eq "dHB"){
70 $fi = fold_input_alignment($alifile); # for later computation of BP dist
71 }
72  
73 my $round = 1;
74 my $done = 0;
75 while ($done != 1){
76 my $lround = sprintf("%03d", $round);
77 my $current_round_name = "round_".$lround;
78 my $odirname = dir($outdir,$current_round_name);
79 print STDERR "Computing round $lround ...\n";
80 alisplit($alifile,$odirname);
81 $round++;
82 $done = 1;
83 #TODO sort output by RNAz SVM prob and re-run with the first few as input alignments
84 }
85  
86  
87 ###############
88 # subroutines #
89 ###############
90  
91 sub alisplit {
92 my ($alnfile,$odirn) = @_;
93 my ($what,$alifold,$rscape);
94 my $AlignSplitObject = Bio::RNA::RNAaliSplit->new(ifile => $alnfile,
95 format => $format,
96 odir => $odirn,
97 dump => 1);
98 #print Dumper($AlignSplitObject);
99 my $dim = $AlignSplitObject->next_aln->num_sequences;
100 my $stkfile = $AlignSplitObject->alignment_stk;
101 my $dmfile = make_distance_matrix($AlignSplitObject,$method,$odirn);
102  
103 # compute Neighbor Joining tree and do split decomposition
104 print STDERR "Perform Split Decomposition ...\n";
105 my $sd = Bio::RNA::RNAaliSplit::WrapAnalyseDists->new(ifile => $dmfile,
106 odir => $AlignSplitObject->odir);
107 print STDERR "Identified ".$sd->count." splits\n";
108 print join "\t", ("#hint","RNAz prob","z-score","SCI","seqs","statistic","SSCBP","consensus structure","alignment"), "\n";
109  
110 # run RNAalifold for the input alignment
111 $alifold = Bio::RNA::RNAaliSplit::WrapRNAalifold->new(ifile => $alnfile,
112 odir => $AlignSplitObject->odir,
113 ribosum => $ribosum);
114  
115 # run RNAz for the input alignment
116 $rnaz = Bio::RNA::RNAaliSplit::WrapRNAz->new(ifile => $alnfile,
117 odir => $AlignSplitObject->odir);
118  
119 # run R-scape for the input alignment
120 $rscape = Bio::RNA::RNAaliSplit::WrapRscape->new(ifile => $alifold->alignment_stk, # use RNAalifold-generated stk
121 odir => $AlignSplitObject->odir,
122 statistic => $rscape_stat,
123 nofigures => 1);
124 $rscape->status == 0 ? $what = $rscape->TP : $what = "n/a";
125  
126 print join "\t", "-",$rnaz->P,$rnaz->z,$alifold->sci,$dim,$rscape->statistic,$what,
127 $alifold->consensus_struc,$alnfile."\n";
128  
129 # extract split sets and run RNAz/RNAalifold/R-scape on each of them
130 my $splitnr=1;
131 while (my $sets = $sd->pop()){
132 my ($sa1_c,$sa1_s,$sa2_c,$sa2_s); # subalignments in Clustal and Stockholm
133 my $set1 = $$sets{S1};
134 my $set2 = $$sets{S2};
135 my $token = "split".$splitnr;
136 #print "set1: @$set1\n"; #print "set2: @$set2\n";
137 ($sa1_c,$sa1_s) = $AlignSplitObject->dump_subalignment("splits", $token.".set1", $set1);
138 ($sa2_c,$sa2_s) = $AlignSplitObject->dump_subalignment("splits", $token.".set2", $set2);
139 if( scalar(@$set1) > 1){evaluate_alignment($sa1_c,$sa1_s,$AlignSplitObject->odir,scalar(@$set1))}
140 if( scalar(@$set2) > 1){evaluate_alignment($sa2_c,$sa2_s,$AlignSplitObject->odir,scalar(@$set2))}
141 $splitnr++;
142 }
143 }
144  
145 sub evaluate_alignment {
146 my ($aln, $stk, $odir, $count) = @_;
147 my ($hint,$rnazo,$alifoldo,$rscapeo,$cs,$what);
148  
149 $rnazo = Bio::RNA::RNAaliSplit::WrapRNAz->new(ifile => $aln,
150 odir => $odir);
151 ($rnazo->P > $rnaz->P) ? ($hint = "?") : ($hint = "-");
152 if($rnazo->P > 1.2*$rnaz->P){$hint = "x"};
153 if($rnazo->P > 1.3*$rnaz->P){$hint = "X"};
154 $alifoldo = Bio::RNA::RNAaliSplit::WrapRNAalifold->new(ifile => $aln,
155 odir => $odir,
156 ribosum => $ribosum);
157 $cs = $alifoldo->consensus_struc;
158 $rscapeo = Bio::RNA::RNAaliSplit::WrapRscape->new(ifile => $alifoldo->alignment_stk, # use RNAalifold-generated stk
159 odir => $odir,
160 statistic => $rscape_stat,
161 nofigures => 1);
162 if ($rscapeo->status == 0){ # all OK
163 $what = $rscapeo->TP;
164 }
165 elsif ($rscapeo->status == 1){ # no significant basepairs
166 $what = "0:no_sign";
167 }
168 elsif ($rscapeo->status == 2){ # covariation scores are almost constant, no further analysis
169 $what = "0:no_data";
170 }
171 else { $what = "n/a" }
172  
173 print join "\t",($hint,$rnazo->P,$rnazo->z,$alifoldo->sci,$count,$rscapeo->statistic,$what,$cs,$aln), "\n";
174 }
175  
176 sub make_distance_matrix {
177 my ($ASO,$m,$od) = @_;
178 my $this_function = (caller(0))[3];
179 my ($i,$j,$Dfile,$dHn,$dHx,$dBp,$dHB);
180 my @pw_alns = ();
181 my @D = ();
182 my $check = 1;
183 my $dim = $ASO->next_aln->num_sequences;
184  
185 # extract all pairwise alignments
186 print STDERR "Extracting pairwise alignments ...\n";
187 for ($i=1;$i<$dim;$i++){
188 for($j=$i+1;$j<=$dim;$j++){
189 my $token = join "_", "pw",$i,$j;
190 my ($sa_clustal,$sa_stockholm) = $ASO->dump_subalignment("pairwise", $token, [$i,$j]);
191 push @pw_alns, $sa_clustal->stringify;
192 }
193 }
194  
195 # initialize distance matrix
196 for($i=0;$i<$dim;$i++){
197 for ($j=0;$j<$dim;$j++){
198 $D[$dim*$i+$j] = 0.;
199 }
200 }
201  
202 # build distance matrix based on pairwise alignments
203 print STDERR "Constructing distance matrix based on pairwise alignments ...\n";
204 foreach my $ali (@pw_alns){
205 my $pw_aso = Bio::RNA::RNAaliSplit->new(ifile => $ali,
206 format => "ClustalW",
207 odir => $od);
208 my ($i,$j) = sort split /_/, $pw_aso->ifilebn;
209  
210 $dHn = $pw_aso->hammingdistN;
211 $dHx = $pw_aso->hammingdistX;
212 my $id1 = $pw_aso->next_aln->get_seq_by_pos(1)->display_id;
213 my $id2 = $pw_aso->next_aln->get_seq_by_pos(2)->display_id;
214 # my $seq1 = $so1->seq;
215 # my $seq2 = $so2->seq;
216 # my ($ss1,$mfe1) = RNA::fold($seq1);
217 # my ($ss2,$mfe2) = RNA::fold($seq2);
218 #print ">> \$seq1: $seq1\n $ss1\n>> \$seq2: $seq2\n $ss2\n\n";
219 # print Dumper($so1);
220  
221 if ($m eq "SCI"){
222 # distance = -log( [normalized] pairwise SCI)
223 my ($sci,$dsci);
224 if($pw_aso->sci > 1){$sci = 1}
225 elsif ($pw_aso->sci == 0.){$sci = 0.000001}
226 else { $sci = $pw_aso->sci; }
227 $dsci = -1*log($sci)/log(10);
228 $D[$dim*($i-1)+($j-1)] = $D[$dim*($j-1)+($i-1)] = $dsci;
229 # print "$i -> $j : $sci\t$dsci\n";
230 }
231 elsif ($m eq "dHn") { # hamming dist with gaps replaced by Ns
232 $D[$dim*($i-1)+($j-1)] = $D[$dim*($j-1)+($i-1)] = $dHn;
233 }
234 elsif ($m eq "dHx") { # hamming dist with all gap columns removed
235 $D[$dim*($i-1)+($j-1)] = $D[$dim*($j-1)+($i-1)] = $dHx;
236 }
237 elsif ($m eq "dBp") { # base pairdistance
238 carp "ERROR [$this_function] sequence \'display_id\' not found in input alignment"
239 unless (exists $$fi{$id1} && exists $$fi{$id2});
240 my $gss1 = $$fi{$id1}->{gss};
241 my $gss2 = $$fi{$id2}->{gss};
242 my $dBp = RNA::bp_distance($gss1,$gss2);
243 $D[$dim*($i-1)+($j-1)] = $D[$dim*($j-1)+($i-1)] = $dBp;
244  
245 }
246 elsif($m eq "dHB") { # combined hamming + basepair distance
247 carp "ERROR [$this_function] sequence \'display_id\' not found in input alignment"
248 unless (exists $$fi{$id1} && exists $$fi{$id2});
249 my $gss1 = $$fi{$id1}->{gss};
250 my $gss2 = $$fi{$id2}->{gss};
251 my $dBp = RNA::bp_distance($gss1,$gss2);
252 my $dHB = $scaleH*$dHn + $scaleB*$dBp;
253 $D[$dim*($i-1)+($j-1)] = $D[$dim*($j-1)+($i-1)] = $dHB;
254 }
255 else {croak "Method $method not available ..please use SCI|dHn|dHx|dBp|dHB"}
256 }
257  
258 # write matrix to file
259 print STDERR "Writing distance matrix to file ...\n";
260 if ($m eq "SCI"){ $Dfile = dump_matrix(\@D,$dim,1,1,"S",$ASO,$verbose)}
261 elsif ($m eq "dHn"){$Dfile = dump_matrix(\@D,$dim,1,1,"dHn",$ASO,$verbose)}
262 elsif ($m eq "dHx"){$Dfile = dump_matrix(\@D,$dim,1,1,"dHx",$ASO,$verbose)}
263 elsif ($m eq "dBp"){$Dfile = dump_matrix(\@D,$dim,1,1,"dBp",$ASO,$verbose)}
264 elsif ($m eq "dHB"){$Dfile = dump_matrix(\@D,$dim,1,1,"dHB",$ASO,$verbose)}
265 else { croak "Method $m not available ..please use SCI|dHn|dHx|dBp|dHB"}
266  
267 # check triangle inequality
268 if ($check == 1){
269 print STDERR "Checking triangle inequality ...\n";
270 my $result = check_triangle($dim,\@D);
271 }
272 return $Dfile;
273 }
274  
275  
276 sub dump_matrix {
277 my ($M,$d,$ad,$pd,$what,$aso,$verbos) = @_;
278 my ($i,$j,$info);
279 my $ad_mx = file($aso->odir,"ld.mx"); # AnalyseDists lower diagoinal distance matrix
280 my $pd_mx = file($aso->odir,"phylip.dst"); # Phylip distance matrix
281 if(defined($verbos)){
282 print STDERR "Analysedists matrix \$ad_mx is $ad_mx\n";
283 print STDERR "Phylip matrix \$pd_mx is $pd_mx\n";
284 }
285 if ($what eq "S"){$info="> S (SCI distance)"}
286 elsif($what eq "dHn"){$info="> H (Hamming distance with gap Ns)"}
287 elsif($what eq "dHx"){$info="> H (Hamming distance with gaps removed)"}
288 elsif($what eq "dBp"){$info="> B (Base pair distance)"}
289 else{$info="> H (unknown)"}
290  
291 if (defined $ad){ # print lower triangle matrix input for AanalyseDists
292 open my $matrix, ">", $ad_mx or die $!;
293 print $matrix $info,"\n";
294 print $matrix "> X $d\n";
295 for ($i=1;$i<$d;$i++){
296 for($j=0;$j<$i;$j++){
297 printf $matrix "%6.4f ", @$M[$d*$i+$j];
298 }
299 print $matrix "\n";
300 }
301 close $matrix;
302 }
303 else{ # print entire matrix
304 for ($i=0;$i<$d;$i++){
305 for($j=0;$j<$d;$j++){
306 printf "%6.4f ", @$M[$d*$i+$j];
307 }
308 print "\n";
309 }
310 }
311 if (defined $pd){ # print phylip distance matrix
312 open my $matrix, ">", $pd_mx or die $!;
313 print $matrix "$d\n";
314 for ($i=0;$i<$d;$i++){
315 my $val = ${$aso->next_aln}{_order}->{$i};
316 $val=~s/\//_/g;
317 my $id = join '_', eval($i+1),$val;
318 print $matrix $id." ";
319 for($j=0;$j<$d;$j++){
320 printf $matrix "%6.4f ", @$M[$d*$i+$j];
321 }
322 print $matrix "\n";
323 }
324 close $matrix;
325 }
326 return $ad_mx;
327 }
328  
329 sub check_triangle {
330 my ($d,$dref) = @_;
331 my $count = 0;
332 my @M = @$dref;
333 my ($i,$j,$k,$d_ij,$d_jk,$d_ik);
334 for ($i=0;$i<$d;$i++){
335 for($j=0;$j<$d;$j++){
336 $d_ij = $M[$d*$i+$j];
337 for($k=0;$k<$d;$k++){
338 $d_jk = $M[$d*$j+$k];
339 $d_ik = $M[$d*$i+$k];
340 $count++;
341 croak "ERROR triangle inequation not satisfied i:$i j:$j k:$k"
342 unless ($d_ij + $d_jk >= $d_ik);
343 }
344 }
345 }
346 print STDERR "Checked $count triangles ...\n";
347 }
348  
349 sub fold_input_alignment {
350 my $aln = shift;
351 my %foldin = ();
352  
353 my $input_AlignIO = Bio::AlignIO->new(-file => $alifile,
354 -format => 'ClustalW'
355 );
356 my $input_aln = $input_AlignIO->next_aln;
357 foreach my $element ($input_aln->each_seq) {
358 my @gappos = ();
359 my $gseq = $element->seq;
360 for (my $i=0;$i<length($gseq);$i++){
361 push @gappos, $i if (substr($gseq,$i,1) eq "-"); # keep gap positions
362 }
363 my $seq = $gseq;
364 $seq =~ s/-//g; # get gap-free sequence
365 my ($ss,$mfe) = RNA::fold($seq);
366 my $gss = $ss;
367 for (my $i=0;$i<=$#gappos;$i++){
368 my $gaps_inserted = 0;
369 substr($gss,$gappos[$i]+$gaps_inserted,0) = ".";
370 $gaps_inserted++;
371 }
372 # print $element->display_id."\n$gseq\n$gss\n$seq\n$ss\n";
373 # print join ",", @gappos,"\n---\n";
374 unless (exists($foldin{$element->display_id})){
375 $foldin{$element->display_id} = {
376 gseq => $gseq,
377 seq => $seq,
378 ss => $ss,
379 gss =>$gss,
380 mfe => $mfe,
381 }
382 }
383 else{
384 croak "ERROR: duplicate sequence identifier in input: ".$element->display_id;
385 }
386 }
387 return \%foldin;
388 }
389  
390  
391 __END__
392  
393 =head1 NAME
394  
395 RNAalisplit - Split and decompose RNA multiple sequence alignments
396  
397 =head1 SYNOPSIS
398  
399 RNAalisplit.pl [--aln|-a I<FILE>] [--method|-m I<OPTION>] [options]
400  
401 =head1 DESCRIPTION
402  
403 This tool splits multiple sequence alignments horizontally, thereby
404 extracting sets of sequences that group together according to a
405 decision value. The most natural decision value is the RNAz SVM
406 RNA-classs probability.
407  
408 A neighbour joining tree is reconstructed from pairwise distances of
409 sequences in the input alignment and subsets of the alignment are
410 derived by splitting at each edge of the NJ tree as well as performing
411 a split decomposition of the matrix of pairwise distances. These
412 subsets/subalignments are then evaluated according to the same
413 decision value and a decision is made whether a subalignment performs
414 better than the original alignment.This can be used to discriminate
415 sequences that to not 'fit' in the input alignment.
416  
417 Output is written to STDOUT and a directory containing all temporary
418 RNAalifold / RNAz / R-scape output files is created. Inside this
419 directory, the 'phylip.dst' file contains the distance matrix computed
420 from pairwise distances. It can be visualized e.g. with SplitsTree.
421  
422 =head1 OPTIONS
423  
424 =over
425  
426 =item B<--aln|-a>
427  
428 A multiple sequence alignment in ClustalW format
429  
430 =item B<--method|-m>
431  
432 Method to compute pairwise ditances. Available options are 'dHn',
433 'dHx', 'dBp', and 'SCI'. The first and second compute pairwise Hamming
434 distances of sequences, where 'dHn' replaces gaps with 'N', whereas
435 'dHx' removes all gap columns (is not yet implemented). 'dBp' folds
436 RNA sequences into thir MFE structures and computes pairwise base pair
437 distances. 'SCI' computes the distance as 1-log(SCI), based on a
438 truncated strucure conservation index of two sequences. The latter,
439 however, is not a metric and therefore often results in negative
440 branch lengths in Neighbor Joining trees. Use with caution. [default:
441 'dHn']
442  
443 =item B<--noribosum>
444  
445 Turn off ribosum scoring for RNAalifold computation. Default: ribosum
446 scoring on
447  
448 =item B<--rscapestat>
449  
450 R-scape covariation statistic. Allowed values are: 'GT', 'MI', 'MIr',
451 'MIg', 'CHI', 'OMES', 'RAF', 'RAFS'. Appending either 'p' or 'a' to
452 any of them calculates its average product correction and average sum
453 correction, respctively (e.g. GTp or GTa). See the R-scape manual for
454 details.
455  
456 =item B<--out|-o>
457  
458 Output base directory. Temporary data and results will be written to
459 this directory
460  
461 =item B<--version>
462  
463 Show RNAalisplit version and exit
464  
465 =back
466  
467 =head1 AUTHOR
468  
469 Michael T. Wolfinger E<lt>michael@wolfinger.euE<gt> and
470 E<lt>michael.wolfinger@univie.ac.atE<gt>
471  
472 =cut
473 (END)