comparison bin/ElementalAnalysis.pl @ 0:4816e4a8ae95 draft default tip

Uploaded
author deepakjadmin
date Wed, 20 Jan 2016 09:23:18 -0500
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4816e4a8ae95
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
358 __END__
359
360 =head1 NAME
361
362 ElementalAnalysis.pl - Perform elemental analysis using specified formulas
363
364 =head1 SYNOPSIS
365
366 ElementalAnalysis.pl Formula(s)...
367
368 ElementalAnalysis.pl [B<-h, --help>]
369 [B<-m, --mode> All | "ElementalAnalysis, [MolecularWeight, ExactMass]"]
370 [B<--outdelim> comma | tab | semicolon]
371 [B<--output> STDOUT | File] [B<--outputstyle> FormulaBlock | FormulaRows]
372 [B<-o, --overwrite>] [B<--precision> number] [B<-q, --quote> yes | no] [B<-r, --root> rootname]
373 [B<-v --valuelabels> [Name, Label, [Name, Label,...]]
374 [B<-w, --workingdir> dirname] Formula(s)...
375
376 =head1 DESCRIPTION
377
378 Perform elemental analysis using molecular formula(s) specified on the command line.
379
380 In addition to straightforward molecular formulas - H2O, HCl, C3H7O2N -
381 other supported variations are: Ca3(PO4)2, [PCl4]+, [Fe(CN)6]4-, C37H42N2O6+2, Na2CO3.10H2O,
382 8H2S.46H2O, and so on. Charges are simply ignored. Isotope symbols in formulas specification, including
383 D and T, are not supported.
384
385 =head1 PARAMETERS
386
387 =over 4
388
389 =item B<Formulas> I<Formula1 [Formula2...]>
390
391 I<Formulas> is a space delimited list of molecular formulas to use for elemental analysis.
392
393 Input value format is: I<Formula1 [Formula2 Formula3...]>. Default: I<H2O>.
394 Examples:
395
396 HCl
397 HCl, C3H7O2N
398 H2O2 Ca3(PO4)2 [PCl4]+
399
400 =back
401
402 =head1 OPTIONS
403
404 =over 4
405
406 =item B<-h, --help>
407
408 Print this help message.
409
410 =item B<--fast>
411
412 In this mode, the specified formulas are considered valid and initial formula
413 validation check is skipped.
414
415 =item B<-m, --mode> I<All | "ElementalAnalysis,[MolecularWeight,ExactMass]">
416
417 Specify what values to calculate using molecular formulas specified on command
418 line: calculate all supported values or specify a comma delimited list of values. Possible
419 values: I<All | "ElementalAnalysis, [MolecularWeight, ExactMass]">. Default: I<All>.
420
421 =item B<--outdelim> I<comma | tab | semicolon>
422
423 Output text file delimiter. Possible values: I<comma, tab, or semicolon>
424 Default value: I<comma>.
425
426 =item B<--output> I<STDOUT | File>
427
428 List information at STDOUT or write it to a file. Possible values: I<STDOUT or File>. Default:
429 I<STDOUT>. B<-r, --root> option is used to generate output file name.
430
431 =item B<--outputstyle> I<FormulaBlock | FormulaRows>
432
433 Specify how to list calculated values: add a new line for each property and present it as a block
434 for each formula; or include all properties in one line and show it as a single line.
435
436 Possible values: I<FormulaBlock | FormulaRows>. Default: I<FormulaBlock>
437
438 An example for I<FormulaBlock> output style:
439
440 Formula: H2O
441 ElementalAnalysis: H: H: 11.1898%; O: 88.8102%
442 MolecularWeight: 18.0153
443 ExactMass: 18.0106
444 ... ...
445 ... ...
446 ... ...
447
448 Formula: H2O2
449 ElementalAnalysis: H: 5.9265%; O: 94.0735%
450 MolecularWeight: 34.0147
451 ExactMass: 34.0055
452 ... ...
453 ... ...
454 ... ...
455
456 An example for I<FormulaRows> output style:
457
458 Formula,ElementalAnalysis,MolecularWeight,ExactMass
459 H2O,H: 11.1898%; O: 88.8102%,18.0153,18.0106
460 H2O2,H: 5.9265%; O: 94.0735%,34.0147,34.0055
461
462 =item B<-o, --overwrite>
463
464 Overwrite existing files.
465
466 =item B<--precision> I<number>
467
468 Precision for listing numerical values. Default: up to I<4> decimal places.
469 Valid values: positive integers.
470
471 =item B<-r, --root> I<rootname>
472
473 New text file name is generated using the root: <Root>.<Ext>. File name is only
474 used during I<File> value of B<-o, --output> option.
475
476 Default file name: FormulsElementalAnalysis.<Ext>. The csv, and tsv
477 <Ext> values are used for comma/semicolon, and tab delimited text files respectively.
478
479 =item B<-v --valuelabels> I<Name,Label,[Name,Label,...]>
480
481 Specify labels to use for calculated values. In general, it's a comma delimited
482 list of value name and column label pairs. Supported value names: I<ElementalAnalysis,
483 MolecularWeight, and ExactMass>. Default labels: I<ElementalAnalysis, MolecularWeight,
484 and ExactMass>.
485
486 =item B<-w, --workingdir> I<dirname>
487
488 Location of working directory. Default: current directory.
489
490 =back
491
492 =head1 EXAMPLES
493
494 To perform elemental analysis, calculate molecular weight and exact mass for H2O,
495 type:
496
497 % ElementalAnalysis.pl
498
499 To perform elemental analysis, calculate molecular weight and exact mass for
500 Ca3(PO4)2 and [PCl4]+, type:
501
502 % ElementalAnalysis.pl "Ca3(PO4)2" "[PCl4]+"
503
504 To perform elemental analysis, use label analysis for calculated data, and generate a
505 new CSV file ElementalAnalysis.csv for H2O and H2O2, type:
506
507 % ElementalAnalysis.pl --m ElementalAnalysis --output File
508 --valuelabels "ElementalAnalysis,Analysis" -o -r ElementalAnalysis.csv
509 H2O H2O2
510
511 To calculate molecular weight and exact mass with four decimal precision and
512 generate a new CSV file WeightAndMass.csv with data rows for H2O and H2O2, type:
513
514 % ElementalAnalysis.pl --m "MolecularWeight,ExactMass" --output File
515 --outputstyle FormulaRows -o -r WeightAndMass.csv
516 H2O H2O2
517
518 =head1 AUTHOR
519
520 Manish Sud <msud@san.rr.com>
521
522 =head1 SEE ALSO
523
524 ElementalAnalysisSDFiles.pl, ElementalAnalysisTextFiles.pl
525
526 =head1 COPYRIGHT
527
528 Copyright (C) 2015 Manish Sud. All rights reserved.
529
530 This file is part of MayaChemTools.
531
532 MayaChemTools is free software; you can redistribute it and/or modify it under
533 the terms of the GNU Lesser General Public License as published by the Free
534 Software Foundation; either version 3 of the License, or (at your option)
535 any later version.
536
537 =cut