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