MayaChemTools

   1 #!/usr/bin/perl -w
   2 #
   3 # $RCSfile: ElementalAnalysis.pl,v $
   4 # $Date: 2008/01/30 21:44:44 $
   5 # $Revision: 1.6 $
   6 #
   7 # Author: Manish Sud <msud@san.rr.com>
   8 #
   9 # Copyright (C) 2004-2008 Manish Sud. All rights reserved.
  10 #
  11 # This file is part of MayaChemTools.
  12 #
  13 # MayaChemTools is free software; you can redistribute it and/or modify it under
  14 # the terms of the GNU Lesser General Public License as published by the Free
  15 # Software Foundation; either version 3 of the License, or (at your option) any
  16 # later version.
  17 #
  18 # MayaChemTools is distributed in the hope that it will be useful, but without
  19 # any warranty; without even the implied warranty of merchantability of fitness
  20 # for a particular purpose.  See the GNU Lesser General Public License for more
  21 # details.
  22 #
  23 # You should have received a copy of the GNU Lesser General Public License
  24 # along with MayaChemTools; if not, see <http://www.gnu.org/licenses/> or
  25 # write to the Free Software Foundation Inc., 59 Temple Place, Suite 330,
  26 # Boston, MA, 02111-1307, USA.
  27 #
  28 
  29 use 5.006;
  30 use strict;
  31 use FindBin; use lib "$FindBin::Bin/../lib";
  32 use Getopt::Long;
  33 use File::Basename;
  34 use Text::ParseWords;
  35 use Benchmark;
  36 use FileUtil;
  37 use TextUtil;
  38 use MolecularFormula;
  39 
  40 my($ScriptName, %Options, $StartTime, $EndTime, $TotalTime);
  41 
  42 # Autoflush STDOUT
  43 $| = 1;
  44 
  45 # Starting message...
  46 $ScriptName = basename($0);
  47 print "\n$ScriptName: Starting...\n\n";
  48 $StartTime = new Benchmark;
  49 
  50 # Get the options and setup script...
  51 SetupScriptUsage();
  52 if ($Options{help}) {
  53   die GetUsageFromPod("$FindBin::Bin/$ScriptName");
  54 }
  55 
  56 my($OutDelim, $OutQuote, $RowsOutput,  $CheckFormula, $FileOutput, $Precision, $OutFileName, @SpecifiedFormulas, @SpecifiedCalculations, @SpecifiedValueLabels, %ValueLabelsMap);
  57 ProcessOptions();
  58 
  59 PerformElementalAnalysis();
  60 print "$ScriptName:Done...\n\n";
  61 
  62 $EndTime = new Benchmark;
  63 $TotalTime = timediff ($EndTime, $StartTime);
  64 print "Total time: ", timestr($TotalTime), "\n";
  65 
  66 ###############################################################################
  67 
  68 # List calculated data values...
  69 sub ListFormulaData {
  70   my($DataLabelRef, $DataValueRef) = @_;
  71   my($Index, $Line, $Value);
  72 
  73   if ($RowsOutput) {
  74     $Line = '';
  75     # Format data...
  76     if ($OutQuote || $Options{outdelim} !~ /^comma$/i) {
  77       $Line = JoinWords($DataValueRef, $OutDelim, $OutQuote);
  78     }
  79     else {
  80       # Always quote values containing commas...
  81       $Line = ($DataValueRef->[0] =~ /\,/) ? qq("$DataValueRef->[0]") : $DataValueRef->[0];
  82       for $Index (1 .. $#{$DataValueRef} ) {
  83 	$Value = $DataValueRef->[$Index];
  84 	if ($Value =~ /\,/) {
  85 	  $Value = qq("$Value");
  86 	}
  87 	$Line .= $OutDelim . $Value;
  88       }
  89     }
  90     if ($FileOutput) {
  91       print OUTFILE "$Line\n";
  92     }
  93     else {
  94       print "$Line\n";
  95     }
  96   }
  97   else {
  98     # Format and list data...
  99     $Line = '';
 100     for $Index (0 .. $#{$DataLabelRef} ) {
 101       $Line = $DataLabelRef->[$Index] . ': ' . $DataValueRef->[$Index];
 102       if ($FileOutput) {
 103 	print OUTFILE "$Line\n";
 104       }
 105       else {
 106 	print "$Line\n";
 107       }
 108     }
 109   }
 110 }
 111 
 112 # List calculated data for a formula...
 113 sub ListHeaderRowData {
 114   my($DataLabelRef) = @_;
 115   my($Line);
 116 
 117   # Format data...
 118   $Line = JoinWords($DataLabelRef, $OutDelim, $OutQuote);
 119   $Line =~ s/\://g;
 120   # List data...
 121   if ($FileOutput) {
 122     print OUTFILE "$Line\n";
 123   }
 124   else {
 125     print "$Line\n";
 126   }
 127 }
 128 
 129 # Elemental analysis...
 130 sub PerformElementalAnalysis {
 131   my($Formula, $FormulaDataRef, $ValueLabel, $CalculationType, $CalculatedValue, $ElementsRef, $ElementCompositionRef, $Status, $ErrorMsg, @ValueLabels, @CalculatedValues);
 132 
 133   print "Performing elemental analysis...\n";
 134 
 135   if ($FileOutput) {
 136     print "Generating file $OutFileName...\n";
 137     open OUTFILE, ">$OutFileName" or die "Couldn't open $OutFileName: $!\n";
 138   }
 139 
 140   # Setup value labels...
 141   @ValueLabels = ();
 142   if ($RowsOutput) {
 143     push @ValueLabels, "Formula";
 144   }
 145   for $CalculationType (@SpecifiedCalculations) {
 146     push @ValueLabels, $ValueLabelsMap{$CalculationType};
 147   }
 148 
 149   if ($RowsOutput) {
 150     ListHeaderRowData(\@ValueLabels);
 151   }
 152 
 153   # Go over specified properties...
 154   FORMULA: for $Formula (@SpecifiedFormulas) {
 155     if (!$RowsOutput) {
 156       if ($FileOutput) {
 157 	print OUTFILE "\nPerforming elemental analysis using formula $Formula...\n\n";
 158       }
 159       else {
 160 	print "\nPerforming elemental analysis using formula  $Formula...\n\n";
 161       }
 162     }
 163     # Calculate appropriate values and write 'em out...
 164     if ($CheckFormula) {
 165       ($Status, $ErrorMsg) = MolecularFormula::IsMolecularFormula($Formula);
 166       if (!$Status) {
 167 	warn("Warning: Ignoring formula $Formula: It's not a valid value: $ErrorMsg\n");
 168 	next FORMULA;
 169       }
 170     }
 171     @CalculatedValues = ();
 172     if ($RowsOutput) {
 173       push @CalculatedValues, $Formula;
 174     }
 175     for $CalculationType (@SpecifiedCalculations) {
 176       if ($CalculationType =~ /^ElementalAnalysis$/i) {
 177 	($ElementsRef, $ElementCompositionRef) = MolecularFormula::CalculateElementalComposition($Formula);
 178 	$CalculatedValue = (defined($ElementsRef) && defined($ElementCompositionRef)) ? MolecularFormula::FormatCompositionInfomation($ElementsRef, $ElementCompositionRef, $Precision) : '';
 179       }
 180       elsif ($CalculationType =~ /^MolecularWeight$/i) {
 181 	$CalculatedValue = MolecularFormula::CalculateMolecularWeight($Formula);
 182 	$CalculatedValue = (defined($CalculatedValue) && length($CalculatedValue)) ? (sprintf("%.${Precision}f", $CalculatedValue)) : "";
 183       }
 184       elsif ($CalculationType =~ /^ExactMass$/i) {
 185 	$CalculatedValue = MolecularFormula::CalculateExactMass($Formula);
 186 	$CalculatedValue = (defined($CalculatedValue) && length($CalculatedValue)) ? (sprintf("%.${Precision}f", $CalculatedValue)) : "";
 187       }
 188       else {
 189 	$CalculatedValue = '';
 190       }
 191       push @CalculatedValues, $CalculatedValue;
 192     }
 193     # List data...
 194     ListFormulaData(\@ValueLabels, \@CalculatedValues);
 195   }
 196   if ($FileOutput) {
 197     close OUTFILE;
 198   }
 199   print "\n";
 200 }
 201 
 202 # Process option values...
 203 sub ProcessOptions {
 204   $OutDelim = ($Options{outdelim} =~ /^tab$/i ) ? "\t" : (($Options{outdelim} =~ /^semicolon$/i) ? "\;" : "\,");
 205   $OutQuote = ($Options{quote} =~ /^yes$/i) ? 1 : 0;
 206 
 207   $RowsOutput = ($Options{outputstyle} =~ /^FormulaRows$/i) ? 1 : 0;
 208   $FileOutput = ($Options{output} =~ /^File$/i) ? 1 : 0;
 209   $CheckFormula = $Options{fast} ? 0 : 1;
 210 
 211   $Precision = $Options{precision};
 212 
 213   # Setup formulas...
 214   @SpecifiedFormulas = ();
 215   if (@ARGV >= 1) {
 216     push @SpecifiedFormulas, @ARGV;
 217   }
 218   else {
 219     # Setup mode specified default values...
 220     push @SpecifiedFormulas, 'H2O';
 221   }
 222 
 223   # Setup what to calculate...
 224   @SpecifiedCalculations = ();
 225   if ($Options{mode} =~ /^All$/i) {
 226     @SpecifiedCalculations = qw(ElementalAnalysis MolecularWeight ExactMass);
 227   }
 228   else {
 229     my($Mode, $ModeValue, @SpecifiedModeValues);
 230     $Mode = $Options{mode};
 231     $Mode =~ s/ //g;
 232     @SpecifiedModeValues = split /\,/, $Mode;
 233     for $ModeValue (@SpecifiedModeValues) {
 234       if ($ModeValue !~ /^(ElementalAnalysis|MolecularWeight|ExactMass)$/i) {
 235 	if ($ModeValue =~ /^All$/i) {
 236 	  die "Error: All value for option \"-m --mode\" is not allowed with other valid values.\n";
 237 	}
 238 	else {
 239 	  die "Error: The value specified, $ModeValue, for option \"-m --mode\" is not valid. Allowed values: ElementalAnalysis, MolecularWeight, or ExactMass\n";
 240 	}
 241       }
 242       push @SpecifiedCalculations, $ModeValue;
 243     }
 244   }
 245   my($Index, $Value, $Label);
 246   # Set up labels for calculated values...
 247   @SpecifiedValueLabels = ();
 248   if ($Options{valuelabels}) {
 249     my($Value, $Label, @ValueLabels);
 250     @ValueLabels = split /\,/, $Options{valuelabels};
 251     if (@ValueLabels % 2) {
 252       die "Error: The value specified, $Options{valuelabels}, for option \"-v --valuelabels\" is not valid: It must contain even number of comma delimited values\n";
 253     }
 254     for ($Index = 0; $Index < @ValueLabels; $Index +=2) {
 255       $Value = $ValueLabels[$Index];
 256       $Value =~ s/ //g;
 257       $Label = $ValueLabels[$Index + 1];
 258       if ($Value !~ /^(ElementalAnalysis|MolecularWeight|ExactMass)$/i) {
 259 	die "Error: The value specified, $Value, using option \"-v --valuelabels\" is not valid. Allowed values: ElementalAnalysis, MolecularWeight, or ExactMass\n";
 260       }
 261       push @SpecifiedValueLabels, ($Value, $Label);
 262     }
 263   }
 264 
 265   # Set up calculation type to label map...
 266   %ValueLabelsMap = (ElementalAnalysis => 'ElementalAnalysis', MolecularWeight => 'MolecularWeight', ExactMass => 'ExactMass');
 267   if (@SpecifiedValueLabels) {
 268     for ($Index = 0; $Index < @SpecifiedValueLabels; $Index +=2) {
 269       $Value = $SpecifiedValueLabels[$Index];
 270       $Label = $SpecifiedValueLabels[$Index + 1];
 271       if (exists $ValueLabelsMap{$Value}) {
 272 	$ValueLabelsMap{$Value} = $Label;
 273       }
 274     }
 275   }
 276 
 277   # Setup output file name...
 278   $OutFileName = '';
 279   if ($FileOutput) {
 280     my($OutFileRoot, $OutFileExt);
 281 
 282     $OutFileRoot = '';
 283     $OutFileExt = "csv";
 284     if ($Options{outdelim} =~ /^tab$/i) {
 285       $OutFileExt = "tsv";
 286     }
 287     if ($Options{root}) {
 288       my ($RootFileDir, $RootFileName, $RootFileExt) = ParseFileName($Options{root});
 289       if ($RootFileName && $RootFileExt) {
 290 	$OutFileRoot = $RootFileName;
 291       }
 292       else {
 293 	$OutFileRoot = $Options{root};
 294       }
 295     }
 296     else {
 297       $OutFileRoot = 'FormulasElementalAnalysis';
 298     }
 299     $OutFileName = $OutFileRoot . '.' . $OutFileExt;
 300     if (!$Options{overwrite}) {
 301       if (-e $OutFileName) {
 302 	die "Error: Output file, $OutFileName, already exists.\nUse \-o --overwrite\ option or specify a different name using \"-r --root\" option.\n";
 303       }
 304     }
 305   }
 306 }
 307 
 308 
 309 # Setup script usage  and retrieve command line arguments specified using various options...
 310 sub SetupScriptUsage {
 311 
 312   # Retrieve all the options...
 313   %Options = ();
 314   $Options{mode} = "All";
 315   $Options{outdelim} = "comma";
 316   $Options{output} = "STDOUT";
 317   $Options{outputstyle} = "FormulaBlock";
 318   $Options{precision} = 2;
 319   $Options{quote} = "yes";
 320 
 321   if (!GetOptions(\%Options, "help|h", "fast", "mode|m=s", "outdelim=s", "output=s", "outputstyle=s", "overwrite|o", "precision=i", "quote|q=s", "root|r=s", "valuelabels|v=s", "workingdir|w=s")) {
 322     die "\nTo get a list of valid options and their values, use \"$ScriptName -h\" or\n\"perl -S $ScriptName -h\" command and try again...\n";
 323   }
 324   if ($Options{workingdir}) {
 325     if (! -d $Options{workingdir}) {
 326       die "Error: The value specified, $Options{workingdir}, for option \"-w --workingdir\" is not a directory name.\n";
 327     }
 328     chdir $Options{workingdir} or die "Error: Couldn't chdir $Options{workingdir}: $! \n";
 329   }
 330   if ($Options{outdelim} !~ /^(comma|semicolon|tab)$/i) {
 331     die "Error: The value specified, $Options{outdelim}, for option \"--outdelim\" is not valid. Allowed values: comma, tab, or semicolon\n";
 332   }
 333   if ($Options{output} !~ /^(STDOUT|File)$/i) {
 334     die "Error: The value specified, $Options{output}, for option \"--output\" is not valid. Allowed values: STDOUT or File\n";
 335   }
 336   if ($Options{outputstyle} !~ /^(FormulaBlock|FormulaRows)$/i) {
 337     die "Error: The value specified, $Options{outputstyle}, for option \"--outputstyle\" is not valid. Allowed values: FormulaBlock or FormulaRows\n";
 338   }
 339   if (!IsPositiveInteger($Options{precision})) {
 340     die "Error: The value specified, $Options{precision}, for option \"-p --precision\" is not valid. Allowed values: > 0 \n";
 341   }
 342   if ($Options{quote} !~ /^(yes|no)$/i) {
 343     die "Error: The value specified, $Options{quote}, for option \"-q --quote\" is not valid. Allowed values: yes or no\n";
 344   }
 345 }
 346