File: run_CM_to_WigeoN.pl

package info (click to toggle)
microbiomeutil 20101212%2Bdfsg1-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 49,276 kB
  • sloc: perl: 4,878; ansic: 419; makefile: 98; sh: 27
file content (363 lines) | stat: -rwxr-xr-x 8,525 bytes parent folder | download | duplicates (6)
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
#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long qw(:config no_ignore_case bundling);
#use FindBin;
#Hack needed because FindBin is braindead.
BEGIN{ $FindBin::Bin = "/usr/lib/WigeoN" };

use lib ("$FindBin::Bin/PerlLib");
use Fasta_reader;
use CdbTools;


my $usage = <<_EOUSAGE_;

##########################################################################################
run_CM.pl
##########################################################################################
#
#  Required:
#
#    --query_NAST      multi-fasta file containing query sequences in alignment format
#
#    --db_NAST        db in NAST format
#    --db_FASTA       db in fasta format (megablast formatted)
#
#  Common opts:
#
#    -n       number of top matching database sequences to compare to (default 15)
#    -R       min divergence ratio default: 1.007
#    -P       min percent identity among matching sequences (default 90)
#
#  ## parameters to tune ChimeraMaligner:
#   
#  Scoring parameters:
#   -M match score   (default: +5)
#   -N mismatch penalty  (default: -4)
#   -Q min query coverage by matching database sequence (default: 70)
#   -T maximum traverses of the multiple alignment  (default: 1)
#
#
#  Flags:
#   --printAlignments     (default off)
#   -v   verbose
#   --exec_dir          cd here before running
#
#########################################################################################


_EOUSAGE_
	
	;


## required options
my ($query_NAST, $db_NAST, $db_FASTA);

# common opts
my $numSeqsCompare = 15;
my $minPerID = 90;
my $minDivR = 1.007;

# chimera maligner opts:
my ($matchScore, $mismatchPenalty, $maxTraverse, $minQueryCoverage);
my $VERBOSE;

# misc
my $printAlignmentsFlag = 0;
my $exec_dir;

&GetOptions (
	
	"query_NAST=s" => \$query_NAST,
	"db_NAST=s" => \$db_NAST,
	"db_FASTA=s" => \$db_FASTA,
	
	# common opts
	"R=f" => \$minDivR,  # same as -R on chimeraMaligner
	"n=i" => \$numSeqsCompare,
	"P=f" => \$minPerID,
	
	## ChimeraMaligner parameters:
	"M=i" => \$matchScore,
	"N=i" => \$mismatchPenalty,
	"Q=i" => \$minQueryCoverage,
	"T=i" => \$maxTraverse,	
		
	"printAlignments" => \$printAlignmentsFlag,
	'v' => \$VERBOSE,
	
	'exec_dir=s' => \$exec_dir,

	);

unless ($query_NAST && $db_NAST && $db_FASTA) { die $usage; }


chdir($exec_dir) or die "Error, cannot cd to $exec_dir";

my $num_blast_hits = $numSeqsCompare + 1; # include self potentially.

main: {
	
	my $fasta_reader = new Fasta_reader($query_NAST);
	while (my $seq_obj = $fasta_reader->next()) {
		my $acc = $seq_obj->get_accession();
		my $query_acc = $acc; # should make all query_acc here.
		my $seqlength = length($seq_obj->get_sequence());
		my $query_seq = $seq_obj->get_sequence();
		$query_seq =~ s/[\-\.]//g;
		if ($seqlength == 0) {
			print "!!! ERROR, $acc has no NAST sequence.  Skipping.\n";
			print STDERR "!!! ERROR, $acc has no NAST sequence.  Skipping.\n";
			next;
		}
				
		print "\nQuery: $acc\n\n" if $VERBOSE;
		
		my $fasta_format = $seq_obj->get_FASTA_format();
		my $query_sequence = $seq_obj->get_sequence();
		$query_sequence =~ s/[\.\-]//g; # strip gaps if in fasta-align format.

		my $query_file = "tmp.$$.query";
		my $db_file = "tmp.$$.db";
		open (my $fh, ">$query_file") or die "Error, cannot write to $query_file ";
		print $fh $fasta_format;
		close $fh;
		
		my %DB_seqs;

		# run megablast, get single top hits
		#my $best_hit;
		#{
		#my @best_hits = &blast_seq($acc, $query_sequence, $db_FASTA);
		#	$best_hit = shift @best_hits;
		#}
		#my $best_hit_fasta = &cdbyank($best_hit, $db_NAST);
		
		#$DB_seqs{$best_hit} = $best_hit_fasta;

		# run megablast, get hits from each end of seq (2 separate searches)
		my $top_hits = &blast_to_top_hits($acc, $query_sequence, $db_FASTA);
		
		
		unless ($top_hits) {
			print "ChimeraMaligner\t$acc\tUNKNOWN\n";
			next;
		}
		
		print "Selected Top Hits:\t$top_hits\n" if $VERBOSE;
				
		open ($fh, ">$db_file") or die "Error, cannot write to $db_file";
		foreach my $hit_acc (split (/\s+/, $top_hits)) {
			my $nast = &cdbyank($hit_acc, $db_NAST);
			print $fh $nast;
			$DB_seqs{$hit_acc} = $nast;
		}
		close $fh;
		
		eval {
			## run chimeraMaligner
			my $cmd = "$FindBin::Bin/../CMCS/ChimeraMaligner/chimeraMaligner.pl --query_NAST $query_file --db_NAST $db_file ";
			
			if ($printAlignmentsFlag) {
			    $cmd .= " --printAlignments ";
			}
						
			if (defined $matchScore) {
				$cmd .= " -M $matchScore ";
			}
			if (defined $mismatchPenalty) {
				$cmd .= " -N $mismatchPenalty ";
			}
			if (defined $minDivR) {
				$cmd .= " -R $minDivR ";
			}
			if (defined $maxTraverse) {
				$cmd .= " -T $maxTraverse ";
			}
			if (defined $minQueryCoverage) {
				$cmd .= " -Q $minQueryCoverage ";
			}
			
			print STDERR "$cmd\n";
		
			my $result = `$cmd`;
			if ($?) {
				die "Error, cmd $cmd died with ret $?";
			}
			my @toks = split(/\t/, $result);
			my @accs_for_renast;
			if ($toks[2] eq 'YES') {
				while ($toks[3] =~ /\((\S+), NAST:(\d+)-(\d+), ECO:\d+-\d+, RawLen:(\d+), G:([\d\.]+), L:([\d\.]+), ([\d\.]+)\)/g) {
					
					my $acc = $1;
					
					my $range_lend = $2;
					my $range_rend = $3;
					
					my $segmentLength = $4;
					
					my $global_per_id = $5;
					my $local_per_id = $6;
					my $divR = $7;
					
					push (@accs_for_renast, $acc);
				}
			
				## RENAST it!
				open (my $ofh, ">$query_file.tmp") or die $!;
				print $ofh ">$query_acc\n$query_seq\n";
				close $ofh;
				
				open ($ofh, ">$query_file.dbrenast.tmp") or die $!;
				foreach my $acc (@accs_for_renast) {
					my $fasta_seq = $DB_seqs{$acc};
					print $ofh $fasta_seq . "\n";
				}
				close $ofh;

				## RENAST it
				my $cmd = "NAST-iEr $query_file.dbrenast.tmp $query_file.tmp > $query_file";
				my $ret = system($cmd);
				
				unlink("$query_file.tmp", "$query_file.dbrenast.tmp"); # awful names

				if ($ret) { 
					die "Error, cmd $cmd died with ret $ret";
				}
				
			}  ## End of RENAST
			
		#	my $best_ref_file = "tmp.$$.bestref";
		#	open (my $ofh, ">$best_ref_file") or die  $!;
	#		print $ofh $DB_seqs{$best_hit};
		#	close $ofh;

			## Run WigeoN
			$cmd = "$FindBin::Bin/run_WigeoN.pl --query_NAST $query_file ";
			my $ret = system($cmd);
			if ($ret) {
				die "Error, cmd $cmd died with ret $ret";
			}
			
		};
		if ($@) {
			print STDERR "$acc failed:   $@\n\n";
			die;
		}
		
		unlink($query_file, $db_file);

	}
	
	exit(0);
}

####
sub blast_to_top_hits {
	my ($acc, $query_seq, $db_FASTA) = @_;

	my $length = length($query_seq);
	
	## search first 33% and last 33% of sequence.
	
	my $first_part = substr($query_seq, 0, int(0.33 * $length));
	
	my $second_part = substr($query_seq, int(0.66 * $length));
	
	my @top_hits_first = &blast_seq($acc, $first_part, $db_FASTA);
	my @top_hits_second = &blast_seq($acc, $second_part, $db_FASTA);
	
	print "Top hits Left:\n" . join ("\t\n", @top_hits_first) . "\n\n" if $VERBOSE;
	
	print "Top hits Right:\n" . join ("\t\n", @top_hits_second) . "\n\n" if $VERBOSE;


	my @merged_hits = &merge_hits(\@top_hits_first, \@top_hits_second);
	
	
	# Use full union N-number of best hits from each side.
	
	#if (scalar(@merged_hits) > $numSeqsCompare) {
	#	@merged_hits = @merged_hits[0..$numSeqsCompare-1];
	#}
	
	return (join (" ", @merged_hits));	
}


####
sub merge_hits {
	my ($list_A_aref, $list_B_aref) = @_;
	
	my @A = @$list_A_aref;
	my @B = @$list_B_aref;
	
	my %seen;
	my @merged;
	while (@A || @B) {
		if (@A) {
			my $entry = shift @A;
			if (! $seen{$entry}) {
				push (@merged, $entry);
				$seen{$entry} = 1;
			}
		}
		if (@B) {
			my $entry = shift @B;
			if (! $seen{$entry}) {
				push (@merged, $entry);
				$seen{$entry} = 1;
			}
		}
	}
	
	return(@merged);
}
	
####
sub blast_seq {
	my ($acc, $seq, $db) = @_;

	open (my $fh, ">tmp.$$.q") or die $!;
	print $fh ">$acc\n$seq\n";
	close $fh;
	
	my $cmd = "megablast -d $db -i ./tmp.$$.q -e 1e-10 -m 8 -v $num_blast_hits -b $num_blast_hits 2>/dev/null";
		
	my @results = `$cmd`;

	unlink("tmp.$$.q");
	
	if ($?) {
	    print STDERR "Error, cmd $cmd died with ret $?";
		return(); # empty blast results.
	}

	my @top_hits;
	my %seen;
	foreach my $result (@results) {
		my @x = split (/\t/, $result);
		
		$x[1] =~ s/\#.*$//;  # megablast bundling space-delimited header components into \#-delimited accessions. weird stuff...

		if ($x[0] eq $x[1]) { next; } # no same query as hit.
		my $acc = $x[1];
		
		my $per_ID = $x[11];

		unless ($per_ID >= $minPerID) { next; }
		
		if (! $seen{$acc}) {
			$seen{$acc} = 1;
			push (@top_hits, $acc);
		}
	}

	return(@top_hits);
}