ImportMothurTaxonomy.pl 8.23 KB
Newer Older
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
#! /usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use File::Basename;
use feature 'say';
use lib (`ktGetLibPath`);
use KronaTools;

setOption('name', 'root');
setOption('out', 'mothur.krona.html');

my @options =
qw(
	out
	name
	combine

);
	# minConfidence
	# depth
	# hueBad
	# hueGood
	# local
	# url
	# postUrl

getKronaOptions(@options);

if
(
	@ARGV < 1
)
{
	printUsage
	(
		'Create a Krona chart from Mothur classifications.',
		'mothur_details',
40 41
		'Option 1 : Take 1 argument : FILE.taxonomy
		or Option 2 : Take 3 arguments : FILE.taxonomy, FILE.groups and FILE.names.',
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
		0,
		1,
		\@options
	);
	
	exit 0;
}

my $tree = newTree();
my @datasetNames;
my $set = 0;

sub getExtension{
	my $fileName = $_[0];
	my ($name,$path,$suffix) = fileparse($fileName,qr"\..[^.]*$");
	return ($path,$name);
}

sub getNames {
	#create a hash of file.names : key = ID Seq and value = array with all ID seq with same seq 
	my $filename = $_[0];
	my $path = $_[1];
	open INFILE, "${path}${filename}.names" or die $!;
	my %hashNames;
	while (my $line = <INFILE>) 
	{
		my ($key, $value) = split /\s+/, $line;
		push @{$hashNames{$key}}, split /\s*,\s*/,$value;
	}
	return \%hashNames;
}

sub getGroups {
75
	#create a hash of file.groups : key = Num sample and value = array with all ID seq
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
	my $filename = $_[0];
	my $path = $_[1];
	open INFILE, "${path}${filename}.groups" or die $!;
	my %hashGroups;
	while (my $line = <INFILE>) 
	{
		my ($value, $key) = split /\t/, $line;
		push @{ $hashGroups{$key} }, $value;
	}
	return %hashGroups;
}

sub getIdNames {
	#retrieve the general ID seq 
	my $idGroups = $_[0];
	my $hashNames = $_[1];
	foreach my $key ( keys %$hashNames )  
	{
		foreach my $values ( @{ $hashNames->{$key} } )  
		{
		if ($idGroups eq $values)
			{
				return $key;
			}
		}
	}
}


sub getTaxonomy {
	#create two hashs of file.taxonomy : 
	#taxonomyLineage : key = ID seq and value = array of taxons
	#taxonomyScore : key = ID seq and value = array of pourcent
109
	#taxonomyCount : key = ID seq and value = number of sequences
110 111
	my %taxonomyLineage;
	my %taxonomyScores;
112
	my %taxonomyCount;
113 114 115 116 117 118 119 120 121 122 123 124
	my $filename = $_[0];
	my $path = $_[1];
	say "${path}${filename}.taxonomy";
	open INFILE, "${path}${filename}.taxonomy" or die $!;
	while (my $line = <INFILE>) 
	{
		next if ($line =~ m/OTU\tSize\tTaxonomy/);
		my $root;
		my @lineage;
		my @ranks;
		my @scores;
		my $allRanks;
125 126 127
		my $count = 1 ;
		
		my @fields = split /[\t;]/, $line;
128 129 130
		my $queryID = $fields[0];
		for ( my $i = 1; $i < $#fields; $i++ )
		{
131 132 133 134 135 136 137
			if( ($i == 1) && $fields[$i] =~ /^(\d+)$/ ) {
				$count = $1 ;
			} else {
				my ($val, $int) = $fields[$i] =~ /\"?(\w+)\"?\(*(\d*)\)*/;
				push @lineage, $val;
				push @scores, $int;
			}
138 139 140
		}
		push(@{ $taxonomyLineage{$queryID} }, @lineage);
		push(@{ $taxonomyScores{$queryID} }, @scores);
141
		$taxonomyCount{$queryID} = $count;
142 143
	}

144
	return (\%taxonomyLineage, \%taxonomyScores, \%taxonomyCount);
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
}

sub getLineage{
	# retrun the good lineage for one ID seq
	my $hashLineage = $_[0];
	my $idNames = $_[1];
	my @lineage = @{ $hashLineage->{$idNames} };
	return @lineage;
}

sub getScores{
	# retrun the good score for one ID seq
	my $hashScores = $_[0];
	my $idNames = $_[1];
	my @scores = @{ $hashScores->{$idNames} };
	return @scores;
}

sub getListFiles{
	#check if all files exists
	my $filename=$_[0];
	my $path=$_[1];
	opendir(DIR, $path);
168
	my @files = grep(/^$filename\.(taxonomy|groups|names|count_table)/,readdir(DIR));
169 170 171 172
	closedir(DIR);
	return \@files;
}

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
sub count_table_parse {
	#return for each sample, the count seqs for each unique sequence
	my $filename = $_[0];
	my $path = $_[1];
	say "${path}${filename}.count_table";
	open INFILE, "${path}${filename}.count_table" or die $!;
	my %hashCount;
	my @firstline = split('\t',<INFILE>);
	my @samples = @firstline[2..$#firstline-1];
	shift(@firstline);
	while (my $line = <INFILE>) 
	{
		my %temp;
		chomp($line);
		my @line = split('\t', $line);
		foreach my $cpt (1..$#line) {
			$temp{$firstline[$cpt-1]}=$line[$cpt];
		}
		$hashCount{$line[0]}={%temp};
	}
	return (\@samples,\%hashCount);
}

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
foreach my $input(@ARGV)
{
	say "MY INPUT                       $input";
	my ($fileName, $magFile, $name) = parseDataset($input);
	say "Importing $fileName...";
	open INFILE, "<$fileName" or die $!;
	my $format;
	my $line = <INFILE>;
	if ( $line =~ /\t/ )
	{
		$format = 1;
		say "File taxonomy found.";
		
		while ( $line !~ /\t/ )
		{
			$line = <INFILE>;
			
			if ( ! $line )
			{
				ktDie("Classifications not found in \"$fileName\". Is it an \"Assignment detail\" file?");
			}
		}
	}
	else
	{
		say "Command line format detected.";
	}
	my ($path,$filewe) = getExtension($input);
	#~ say "my name                $name";
	#~ say "my file                $filewe";
	#~ say "my path                $path";
	#~ say "my fullname                ${path}${filewe}";
	my $listFiles = getListFiles($filewe,$path);
	my $size = $#$listFiles + 1;
230
	my ($hashLineage, $hashScores, $hashCount) = getTaxonomy($filewe,$path);
231
	#if i have multiple samples (FILE.names and FILE.groups)
232 233
	if ($size eq 3)
	{
234 235
		my %samples = getGroups($filewe,$path);    # {'sample1:["seq_1", "seq_2"]', 'sample2':["seq_8"]}
		my $hashNames = getNames($filewe,$path);   # {'seq_3:["seq_4", "seq_5"]', 'seq_8':[]}
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
		foreach my $sample (keys %samples)
		{
			say "My sample      ",$sample;
			foreach my $seq (@{$samples{$sample}})
			{
				#
				my $idNames = getIdNames($seq,$hashNames);
				my @lineage = getLineage($hashLineage,$idNames);
				my @scores = getLineage($hashScores,$idNames);
				my $allRanks;
				my $root = $lineage[0];
				for ( my $i = 1; $i < @lineage; $i ++ )
				{
					if (! getOption('combine'))
					{
						if ( $lineage[$i] eq $root)
						{
							setOption('name',$root );
							$allRanks = 1;
							next;
						}
					}
				}
				addByLineage
				(
				$tree,
				$set,#rank for the different samples
				\@lineage,
				$seq,#name of id sequence
				undef,
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
				undef,
				\@scores #pourcent
				# $format ? ($allRanks ? undef : \@webRanks) : \@ranks
				);
			}

			if ( ! getOption('combine') )
			{
				$set++;
				push @datasetNames, $sample;
			}
		}
		close INFILE;
	}
	elsif ($size eq 2)
	{
		my ($samples,$counTable) = count_table_parse($filewe,$path);
		foreach my $sample (@$samples)
		{
			say "My sample      ",$sample;
286
			foreach my $seq (keys %$hashLineage)
287 288 289 290
			{				
				my $count = $counTable->{$seq}->{$sample};
				if ($count != "0")
				{
291 292 293 294 295 296
					my $total = $count;
					my $allRanks;
					my @lineage = @{ $hashLineage->{$seq} };
					my @scores = @{ $hashScores->{$seq} };
					my $root = $lineage[0];
					for ( my $i = 1; $i < @lineage; $i ++ )
297
					{
298
						if (! getOption('combine'))
299
						{
300 301 302 303 304 305
							if ( $lineage[$i] eq $root)
							{
								setOption('name',$root );
								$allRanks = 1;
								next;
							}
306 307
						}
					}
308 309 310 311 312 313 314 315 316 317 318
					addByLineage
					(
					$tree,
					$set,#rank for the different samples
					\@lineage,
					$seq,#name of id sequence
					$total,
					undef,
					\@scores #pourcent
					# $format ? ($allRanks ? undef : \@webRanks) : \@ranks
					);
319
				}
320 321 322 323 324 325 326 327 328 329
			}

			if ( ! getOption('combine') )
			{
				$set++;
				push @datasetNames, $sample;
			}
		}
		close INFILE;
	}
330
	#if i have just FILE.taxonomy (OTU)
331 332
	elsif($size eq 1)
	{
333
		foreach my $seq (keys %$hashLineage)
334
		{
Penom Nom's avatar
Penom Nom committed
335
			if ($hashCount->{$seq} != "0")
336
			{
Penom Nom's avatar
Penom Nom committed
337 338 339 340 341
				my $allRanks;
				my @lineage = @{ $hashLineage->{$seq} };
				my @scores = @{ $hashScores->{$seq} };
				my $root = $lineage[0];
				for ( my $i = 1; $i < @lineage; $i ++ )
342
				{
Penom Nom's avatar
Penom Nom committed
343 344 345 346 347 348
					if ( $lineage[$i] eq $root)
					{
						setOption('name',$root );
						$allRanks = 1;
						next;
					}
349
				}
Penom Nom's avatar
Penom Nom committed
350 351 352 353 354 355 356 357 358 359 360
				addByLineage
				(
				$tree,
				$set,
				\@lineage,
				$seq,
				$hashCount->{$seq},
				undef,
				\@scores
				# $format ? ($allRanks ? undef : \@webRanks) : \@ranks
				);
361
			}
362
		}
363 364 365 366 367
		if ( ! getOption('combine') )
			{
				$set++;
				push @datasetNames, $filewe;
			}
368 369 370
	}
	else
	{
371
		say "There are not all files required. Please check if you have opt1 : FILE.taxonomy or opt2 : FILE.taxonomy, FILE.groups and FILE.names in your current directory.";
372 373 374 375 376 377 378 379
		exit 0;
	}
} 
say "Done";

my @attributeNames =
(
	'count',
380
	'magnitude',
381
	'unassigned',
382
	'score'
383 384 385 386 387
);

my @attributeDisplayNames =
(
	'Count',
388
	'Total',
389 390 391 392 393 394 395 396 397 398 399 400 401
	'Unassigned',
	'Avg. % Confidence',
);

writeTree
(
	$tree,
	\@attributeNames,
	\@attributeDisplayNames,
	\@datasetNames,
	# getOption('hueBad'),
	# getOption('hueGood')
);