blib/lib/Chemistry/File/Formula.pm

filter: Statementstmt 98.9% 90 / 91 Branchbran 82.5% 33 / 40 Conditioncond 63.6% 7 / 11 MC/DCmcdc 33.3% 2 / 6 Subroutinesub 91.6% 11 / 12 Podpod 42.8% 3 / 7 totaltotal 87.4% 146 / 167 CC 29 SCAR 16.4
CC
29
Cov
92%
internal_formula_parser
7.0
parse_string
6.2
ParensBalanced
6.1
CRAP 5.2
« blib/lib/Chemistry/MacroMol.pm ↑ Summary blib/lib/Parse/Yapp/Options.pm »
1 package Chemistry::File::Formula;
2 12 $VERSION = '0.35';
3 # $Id: Formula.pm,v 1.13 2005/05/20 19:01:05 itubert Exp $
4  
5 12 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 12 ▶use base "Chemistry::File";
Subroutine BEGIN: called CC=1 SCAR=0.0
7 12 ▶use Chemistry::Mol;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 12 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 12 ▶use Text::Balanced qw(extract_bracketed);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 =head1 NAME
12  
13 Chemistry::File::Formula - Molecular formula reader/formatter
14  
15 =head1 SYNOPSIS
16  
17 use Chemistry::File::Formula;
18  
19 my $mol = Chemistry::Mol->parse("H2O");
20 print $mol->print(format => formula);
21 print $mol->formula; # this is a shorthand for the above
22 print $mol->print(format => formula,
23 formula_format => "%s%d{<sub>%d</sub>});
24  
25 =cut
26  
27 12 Chemistry::Mol->register_format('formula');
28  
29 =head1 DESCRIPTION
30  
31 This module converts a molecule object to a string with the formula. It
32 registers the 'formula' format with Chemistry::Mol.
33 Besides its obvious use, it is included in the Chemistry::Mol distribution
34 because it is a very simple example of a Chemistry::File derived I/O module.
35  
36 The format can be specified as a printf-like string with the following control
37 sequences, which are specified with the formula_format parameter to $mol->print
38 or $mol->write.
39  
40 =over
41  
42 =item %s symbol
43  
44 =item %D number of atoms
45  
46 =item %d number of atoms, included only when it is greater than one
47  
48 =item %d{substr} substr is only included when number of atoms is greater than
49 one
50  
51 =item %j{substr} substr is inserted between the formatted string for each
52 element. (The 'j' stands for 'joiner'). The format should have only one joiner,
53 and its location in the string doesn't matter.
54  
55 =item %% a percent sign
56  
57 =back
58  
59 If no format is specified, the default is "%s%d". Some examples follow. Let's
60 assume that the formula is C2H6O, as it would be formatted by default.
61  
62 =over
63  
64 =item C<< %s%D >>
65  
66 Like the default, but include explicit indices for all atoms.
67 The formula would be formatted as "C2H6O1"
68  
69 =item C<< %s%d{E<lt>subE<gt>%dE<lt>/subE<gt>} >>
70  
71 HTML format. The output would be
72 "CE<lt>subE<gt>2E<lt>/subE<gt>HE<lt>subE<gt>6E<lt>/subE<gt>O".
73  
74 =item C<< %D %s%j{, } >>
75  
76 Use a comma followed by a space as a joiner. The output would be
77 "2 C, 6 H, 1 O".
78  
79 =back
80  
81 =head2 Parsing Formulas
82  
83 Formulas can also be parsed back into Chemistry::Mol objects.
84 The formula may have parentheses and square or triangular brackets, and
85 it may have the following abbreviations:
86  
87 Me => '(CH3)',
88 Et => '(CH3CH2)',
89 Bu => '(C4H9)',
90 Bn => '(C6H5CH2)',
91 Cp => '(C5H5)',
92 Ph => '(C6H5)',
93 Bz => '(C6H5CO)',
94  
95 The formula may also be preceded by a number, which multiplies the whole
96 formula. Some examples of valid formulas:
97  
98 =over
99  
100 =item CH3(CH2)3CH3. Equivalent to C5H12.
101  
102 =item C6H3Me3. Equivalent to C9H12.
103  
104 =item 2Cu[NH3]4(NO3)2. Equivalent to Cu2H24N12O12.
105  
106 =item 2C(C[C<C>5]4)3. Equivalent to C152 (kind of silly example...).
107  
108 =item 2C(C(C(C)5)4)3. Equivalent to C152.
109  
110 =item C 1 0 H 2 2. Equivalent to C10H22. Note that whitespace is completely
111 ignored.
112  
113 =back
114  
115 When a formula is parsed, a molecule object is created which consists of
116 the set of the atoms in the formula (no bonds or coordinates, of course).
117 The atoms are created in alphabetical order, so the molecule object for C2H5Br
118 would have the atoms in the following sequence: Br, C, C, H, H, H, H, H.
119  
120 =cut
121  
122 9 ▶sub parse_string {
Subroutine parse_string: called CC=6 SCAR=18.2
Pod documented
123 9 my ($self, $string, %opts) = @_;
124 9 ▶ my $mol_class = $opts{mol_class} || "Chemistry::Mol";
Condition50%1/2
$opts{'mol_class'} || 'Chemistry::Mol'
l!l
90
MC/DC0%0/1
$opts{'mol_class'} || 'Chemistry::Mol'
$opts{'mol_class'}
Truth table50%1/2
A
A= $opts{'mol_class'}
Aresult
11
00
125 9 ▶ my $atom_class = $opts{atom_class} || "Chemistry::Atom";
Condition50%1/2
$opts{'atom_class'} || 'Chemistry::Atom'
l!l
09
MC/DC0%0/1
$opts{'atom_class'} || 'Chemistry::Atom'
$opts{'atom_class'}
Truth table50%1/2
A
A= $opts{'atom_class'}
Aresult
11
00
126 9 ▶ my $bond_class = $opts{bond_class} || "Chemistry::Bond";
Condition50%1/2
$opts{'bond_class'} || 'Chemistry::Bond'
l!l
09
MC/DC0%0/1
$opts{'bond_class'} || 'Chemistry::Bond'
$opts{'bond_class'}
Truth table50%1/2
A
A= $opts{'bond_class'}
Aresult
11
00
127  
128 9 my $mol = $mol_class->new;
129 #$string =~ /^(?:([A-Z][a-z]*)(\d*))+$/ or croak("invalid formula $string\n");
130 #my (%formula) = $string =~ m/([A-Z][a-z]*)(\d*)/g;
131 #for (values %formula) {
132 #$_ = 1 unless length; # Add implicit indices
133 #}
134 9 my %formula = parse_formula($string);
135 9 for my $sym (sort keys %formula) {
136 18 ▶ for (my $i = 0; $i < $formula{$sym}; ++$i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $formula{$sym}) 478 18 496
137 478 $mol->add_atom($atom_class->new(symbol => $sym));
138 }
139 }
140 9 return $mol;
141 }
142  
143 11 ▶sub write_string {
Subroutine write_string: called CC=6 SCAR=17.9
Pod documented
144 11 my ($self, $mol, %opts) = @_;
145 11 my @formula_parts;
146 11 ▶ my $format = $opts{formula_format} || "%s%d"; # default format
Condition100%2/2
$opts{'formula_format'} || '%s%d'
l!l
110
MC/DC100%1/1
$opts{'formula_format'} || '%s%d'
$opts{'formula_format'}
Truth table100%2/2
A
A= $opts{'formula_format'}
Aresult
11
00
147 11 my $fh = $mol->formula_hash;
148 11 $format =~ s/%%/\\%/g; # escape %% with a \
149 11 my $joiner = "";
150 11 ▶ $joiner = $1 if $format =~ s/(?<!\\)%j{(.*?)}//; # joiner %j{}
Branch: 1 branch
BranchTrueFalseTotal
if $format =~ s/(?<!\\)%j{(.*?)}// 0 11 11
151 11 for my $sym (sort keys %$fh) {
152 29 my $s = $format;
153 29 my $n = $fh->{$sym};
154 29 $s =~ s/(?<!\\)%s/$sym/g; # %s
155 29 $s =~ s/(?<!\\)%D/$n/g; # %D
156 29 ▶ $s =~ s/(?<!\\)%d\{(.*?)\}/$n > 1 ? $1 : ''/eg; # %d{}
Branch: 1 branch
BranchTrueFalseTotal
$n > 1 ? : 1 2 3
157 29 ▶ $s =~ s/(?<!\\)%d/$n > 1 ? $n : ''/eg; # %d
Branch: 1 branch
BranchTrueFalseTotal
$n > 1 ? : 21 6 27
158 29 $s =~ s/\\(.)/$1/g; # other \ escapes
159 29 push @formula_parts, $s;
160 }
161 11 return join($joiner, @formula_parts);
162 }
163  
164  
165 0 ▶sub file_is {
Subroutine file_is: not called CC=1 SCAR=6.9
Pod documented
166 0 return 0; # no files are identified automatically as having this format
167 }
168  
169 ### Code derived from formula.pl by Brent Gregersen follows
170  
171 12 my %macros = (
172 Me => '(CH3)',
173 Et => '(CH3CH2)',
174 Bu => '(C4H9)',
175 Bn => '(C6H5CH2)',
176 Cp => '(C5H5)',
177 Ph => '(C6H5)',
178 Bz => '(C6H5CO)',
179 # Ac is an element
180 # Pr is an element
181 );
182  
183  
184 9 ▶sub parse_formula {
Subroutine parse_formula: called CC=4 SCAR=13.9
Pod undocumented
185 9 my ($formula) = @_;
186 9 my (%elements);
187  
188 #check balancing
189 9 ▶ return %elements if (!ParensBalanced($formula));
Branch: 1 branch
BranchTrueFalseTotal
unless ParensBalanced($formula) 0 9 9
190  
191 # replace other grouping with normal parens
192 9 $formula =~ tr/<>{}[]/()()()/;
193  
194 # get rid of any spaces
195 9 $formula =~ s/\s+//g;
196  
197 # perform macro expansion
198 9 foreach (keys(%macros)) {
199 63 $formula =~ s/$_/$macros{$_}/g;
200 }
201  
202 # determine initial compound coeficent
203 9 ▶ my $coef = ($formula =~ s/^(\d+)//) ? $1 : 1.0;
Branch: 1 branch
BranchTrueFalseTotal
$formula =~ s/^(\d+)// ? : 4 5 9
204  
205 # recursively process rest of formula
206 9 return internal_formula_parser($formula, $coef, %elements);
207 }
208  
209 26 ▶sub internal_formula_parser {
Subroutine internal_formula_parser: called CC=7 SCAR=19.5
Pod undocumented
210 26 my ($formula, $coef, %form) = @_;
211 26 my $tmp_coef;
212  
213 26 my ($extract, $remainder, $prefix) =
214 extract_bracketed($formula, '()', '[^(]*');
215  
216 26 ▶ if (defined($extract) and $extract ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $extract and $extract ne '') { } 14 12 26
Condition66%2/3
defined $extract and $extract ne ""
!ll&&!rl&&r
12014
MC/DC50%1/2
defined $extract and $extract ne ""
defined $extract $extract ne ""
Truth table66%2/3
A and B
A= defined $extractB= $extract ne ""
ABresult
0X0
100
111
217 14 $extract =~ s/^\((.*)\)$/$1/;
218 14 ▶ if ($remainder =~ s/^(\d+)(.*)$/$2/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remainder =~ s/^(\d+)(.*)$/$2/) { } 12 2 14
219 12 $tmp_coef = $1 * $coef;
220 } else {
221 2 $tmp_coef = $coef;
222 }
223  
224 # get formula of prefix ( it has no parens)
225 14 ▶ %form = add_formula_strings($prefix, $coef, %form) if ($prefix ne '');
Branch: 1 branch
BranchTrueFalseTotal
if $prefix ne "" 9 5 14
226  
227 # check remainder for more parens
228 14 ▶ %form = internal_formula_parser($remainder, $coef, %form)
Branch: 1 branch
BranchTrueFalseTotal
if $remainder ne "" 3 11 14
229 if ($remainder ne '');
230  
231 # check extract for more parens
232 14 %form =
233 internal_formula_parser($extract, $tmp_coef, %form);
234 ## we already know this is ne ''
235 } else { # get formula of complete string
236 12 ▶ %form = add_formula_strings($remainder, $coef, %form)
Branch: 1 branch
BranchTrueFalseTotal
if $remainder ne "" 12 0 12
237 if ($remainder ne '');
238 }
239 26 return %form;
240 }
241  
242 21 ▶sub add_formula_strings {
Subroutine add_formula_strings: called CC=5 SCAR=16.1
Pod undocumented
243 21 my ($formula, $coef, %elements) = @_;
244  
245 # print "Getting Formula of $formula\n";
246 21 ▶ $formula =~ /^(?:([A-Z][a-z]*)(\d+)?)+$/o
Branch: 1 branch
BranchTrueFalseTotal
$formula =~ /^(?:([A-Z][a-z]*)(\d+)?)+$/o or croak("Invalid Portion of Formula $formula") 21 0 21
247 or croak "Invalid Portion of Formula $formula";
248 21 ▶ while ($formula =~ m/([A-Z][a-z]*)(\d+)?/go) {
Branch: 1 branch
BranchTrueFalseTotal
if ($formula =~ /([A-Z][a-z]*)(\d+)?/go) 34 21 55
249 34 my ($elm, $count) = ($1, $2);
250 34 ▶ $count = 1 unless defined $count;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $count 20 14 34
251 34 ▶ if (defined $elements{$elm}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $elements{$elm}) { } 16 18 34
252 16 $elements{$elm} += $count * $coef;
253 } else {
254 18 $elements{$elm} = $count * $coef;
255 }
256 }
257 21 return %elements;
258 }
259  
260 9 ▶sub ParensBalanced {
Subroutine ParensBalanced: called CC=6 SCAR=18.1
Pod undocumented
261 9 my ($form) = @_;
262 9 my @stack = ();
263 9 my %pairs = (
264 '<' => '>',
265 '{' => '}',
266 '[' => ']',
267 '(' => ')'
268 );
269  
270 9 ▶ while ($form =~ m/([<>(){}\]\[])/go) {
Branch: 1 branch
BranchTrueFalseTotal
if ($form =~ /([<>(){}\]\[])/go) 22 9 31
271 22 my $current = $1;
272 22 ▶ if ($current =~ /[<({\[]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current =~ /[<({\[]/) 11 11 22
273 11 push(@stack, $current);
274 11 next;
275 }
276 11 ▶ return 0 if (scalar(@stack) == 0);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @stack == 0 0 11 11
277 11 ▶ return 0 if ($current ne $pairs{ pop @stack});
Branch: 1 branch
BranchTrueFalseTotal
if $current ne $pairs{pop @stack} 0 11 11
278 }
279 9 ▶ return @stack ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
@stack ? : 0 9 9
280 }
281  
282 12 1;
283  
284 =head1 VERSION
285  
286 0.35
287  
288 =head1 SEE ALSO
289  
290 L<Chemistry::Mol>, L<Chemistry::File>
291  
292 The PerlMol website L<http://www.perlmol.org/>
293  
294 =head1 AUTHOR
295  
296 Ivan Tubert-Brohman <itub@cpan.org>.
297  
298 Formula parsing code contributed by Brent Gregersen.
299  
300 =head1 COPYRIGHT
301  
302 Copyright (c) 2005 Ivan Tubert-Brohman. All rights reserved. This program is
303 free software; you can redistribute it and/or modify it under the same terms as
304 Perl itself.
305  
306 =cut
307  
« blib/lib/Chemistry/MacroMol.pm ↑ Summary blib/lib/Parse/Yapp/Options.pm »