FormulaPattern.pm

filter: Statementstmt 88.7% 103 / 116 Branchbran 68.0% 34 / 50 Conditioncond 60.0% 12 / 20 MC/DCmcdc 33.3% 4 / 12 Subroutinesub 82.3% 14 / 17 Podpod 50.0% 5 / 10 totaltotal 76.4% 172 / 225 CC 35 SCAR 19.2
CC
35
Cov
80%
internal_formula_parser
10.7
match
10.1
parse_formula
9.4
CRAP 6.8
↑ Summary File/FormulaPattern.pm »
1 package Chemistry::FormulaPattern;
2  
3 2 $VERSION = '0.10';
4  
5 # $Id: FormulaPattern.pm,v 1.1.1.1 2004/08/11 23:03:04 itubert Exp $
6  
7 =head1 NAME
8  
9 Chemistry::FormulaPattern - Match molecule by formula
10  
11 =head1 SYNOPSIS
12  
13 use Chemistry::FormulaPattern;
14  
15 # somehow get a bunch of molecules...
16 use Chemistry::File::SDF;
17 my @mols = Chemistry::Mol->read("file.sdf");
18  
19 # we want molecules with six carbons and 8 or more hydrogens
20 my $patt = Chemistry::FormulaPattern->new("C6H8-");
21  
22 for my $mol (@mols) {
23 if ($patt->match($mol)) {
24 print $mol->name, " has a nice formula!\n";
25 }
26 }
27  
28 # a concise way of selecting molecules with grep
29 my @matches = grep { $patt->match($mol) } @mols;
30  
31 =head1 DESCRIPTION
32  
33 This module implements a simple language for describing a range of
34 molecular formulas and allows one to find out whether a molecule matches
35 the formula specification. It can be used for searching for molecules by
36 formula, in a way similar to the NIST WebBook formula search
37 (L<http://webbook.nist.gov/chemistry/form-ser.html>). Note however that the
38 language used by this module is different from the one used by the WebBook!
39  
40 Chemistry::FormulaPattern shares the same interface as L<Chemistry::Pattern>.
41 To perform a pattern matching operation on a molecule, follow these steps.
42  
43 1) Create a pattern object, by parsing a string. Let's assume that the pattern
44 object is stored in $patt and that the molecule is $mol.
45  
46 2) Execute the pattern on the molecule by calling $patt->match($mol).
47  
48 If $patt->match returns true, there was a match. If $patt->match is called two
49 consecutive times with the same molecule, it returns false; then true (if there
50 is a match), then false, etc. This is because the Chemistry::Pattern interface
51 is designed to allow multiple matches for a given molecule, and then returns
52 false when there are no further matches; in the case of a formula pattern,
53 there is only one possible match.
54  
55 $patt->match($mol); # may return true
56 $patt->match($mol); # always false
57 $patt->match($mol); # may return true
58 $patt->match($mol); # always false
59 # ...
60  
61 This allows one two use the standard while loop for all kinds of patterns
62 without having to worry about endless loops:
63  
64 # $patt might be a Chemistry::Pattern, Chemistry::FormulaPattern,
65 # or Chemistry::MidasPattern object
66 while ($patt->match($mol)) {
67 # do something
68 }
69  
70 Also note that formula patterns don't really have the concept of an atom map,
71 so $patt->atom_map and $patt->bond_map always return the empty list.
72  
73 =head1 FORMULA PATTERN LANGUAGE
74  
75 In the simplest case, a formula pattern may be just a regular formula, as
76 used by the L<Chemistry::File::Formula> module. For example, the pattern
77 "C6H6" will only match molecules with six carbons, six hydrogens, and no other
78 atoms.
79  
80 The interesting thing is that one can also specify ranges for the elements,
81 as two hyphen-separated numbers. "C6H8-10" will match molecules with six
82 carbons and eight to ten hydrogens.
83  
84 Ranges may also be open, by omitting the upper part of the range. "C6H0-" will
85 match molecules with six carbons and any number of hydrogens (i.e., zero or
86 more).
87  
88 A formula pattern may also allow for unspecified elements by means of the
89 asterisk special character, which can be placed anywhere in the formula
90 pattern. For example, "C2H6*" (or "C2*H6, etc.) will match C2H6, and also
91 C2H6O, C2H6S, C2H6SO, etc.
92  
93 Ranges can also be used after a subformula in parentheses: "(CH2)1-2" will
94 match molecules with one or two carbons and two to four hydrogens. Note,
95 however, that the "structure" of the bracketed part of the formula is
96 forgotten, i.e., the multiplier applies to each element individually and does
97 not have to be an integer. That is, the above pattern will match CH2, CH3, CH4,
98 C2H2, C2H3, and C2H4.
99  
100 =cut
101  
102  
103 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
104 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
105 2 ▶use Chemistry::Mol;
Subroutine BEGIN: called CC=1 SCAR=0.0
106 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
107 2 ▶use base "Chemistry::Pattern";
Subroutine BEGIN: called CC=1 SCAR=0.0
108 2 ▶use Text::Balanced qw(extract_bracketed);
Subroutine BEGIN: called CC=1 SCAR=0.0
109  
110 2 our $DEBUG = 0;
111  
112 15 ▶sub new {
Subroutine new: called CC=2 SCAR=7.4
Pod documented
113 15 my ($class, $str) = @_;
114 15 ▶ my $self = bless {
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
0150
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
115 atom_map => [],
116 options => {},
117 matched => 0,
118 }, ref $class || $class;
119 15 $self->parse_formula_pattern($str);
120 15 $self;
121 }
122  
123 0 ▶sub atom_map { () }
Subroutine atom_map: not called CC=1 SCAR=6.9
Pod documented
124  
125 0 ▶sub bond_map { () }
Subroutine bond_map: not called CC=1 SCAR=6.9
Pod documented
126  
127 0 ▶sub options {
Subroutine options: not called CC=1 SCAR=6.9
Pod documented
128 0 my $self = shift;
129 0 $self->{options} = {%{$self->{options}}, @_};
130 0 $self;
131 }
132  
133 15 ▶sub parse_formula_pattern {
Subroutine parse_formula_pattern: called CC=2 SCAR=6.9
Pod undocumented
134 15 my ($self, $string) = @_;
135 15 ▶ if ($string =~ s/\*//g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($string =~ s/\*//g) 2 13 15
136 2 $self->{options}{allow_others} = 1;
137 }
138 15 my %formula = parse_formula($string);
139 15 $self->{formula_pattern} = \%formula;
140 }
141  
142 16 ▶sub match {
Subroutine match: called CC=10 SCAR=23.2
Pod documented
143 16 my ($self, $mol) = @_;
144 16 my $tree = $self->{tree};
145 16 my @ret;
146 16 my $first = 1;
147  
148 16 ▶ if ($self->{matched} and $self->{matched} eq $mol) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"matched"} and $self->{"matched"} eq $mol) 5 11 16
Condition66%2/3
$self->{"matched"} and $self->{"matched"} eq $mol
!ll&&!rl&&r
1105
MC/DC50%1/2
$self->{"matched"} and $self->{"matched"} eq $mol
$self->{"matched"} $self->{"matched"} eq $mol
Truth table66%2/3
A and B
A= $self->{"matched"}B= $self->{"matched"} eq $mol
ABresult
0X0
100
111
149 5 $self->{matched} = 0;
150 5 return 0;
151 }
152  
153 11 my $want_formula = $self->{formula_pattern};
154 11 my $have_formula = $mol->formula_hash;
155 11 my $good = 0;
156 11 my @want_keys = keys %$want_formula;
157 11 for my $symbol (@want_keys) {
158 2 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
159 15 ▶ $have_formula->{$symbol} ||= 0;
Condition50%1/2
$have_formula->{$symbol} ||= 0
l!l
150
MC/DC0%0/1
$have_formula->{$symbol} ||= 0
$have_formula->{$symbol}
Truth table50%1/2
A
A= $have_formula->{$symbol}
Aresult
11
00
160 15 ▶ if ($have_formula->{$symbol} >= $want_formula->{$symbol}{low}
Branch: 1 branch
BranchTrueFalseTotal
if ($have_formula->{$symbol} >= $want_formula->{$symbol}{'low'} and $have_formula->{$symbol} <= $want_formula->{$symbol}{'high'}) { } 9 6 15
Condition66%2/3
$have_formula->{$symbol} >= $want_formula->{$symbol}{"low"} and $have_formula->{$symbol} <= $want_formula->{$symbol}{"high"}
!ll&&!rl&&r
609
MC/DC50%1/2
$have_formula->{$symbol} >= $want_formula->{$symbol}{"low"} and $have_formula->{$symbol} <= $want_formula->{$symbol}{"high"}
$have_formula->{$symbol} >= $want_formula->{$symbol}{"low"} $have_formula->{$symbol} <= $want_formula->{$symbol}{"high"}
Truth table66%2/3
A and B
A= $have_formula->{$symbol} >= $want_formula->{$symbol}{"low"}B= $have_formula->{$symbol} <= $want_formula->{$symbol}{"high"}
ABresult
0X0
100
111
161 and $have_formula->{$symbol} <= $want_formula->{$symbol}{high}) {
162 9 $good++;
163 } else {
164 6 last;
165 }
166 }
167 11 my @have_keys = keys %$have_formula;
168 11 ▶ if ($good == @want_keys
Branch: 1 branch
BranchTrueFalseTotal
if ($good == @want_keys and $good == @have_keys || $self->{"options"}{"allow_others"}) 5 6 11
Condition66%4/6
$good == @want_keys and $good == @have_keys || $self->{"options"}{"allow_others"}
!ll&&!rl&&r
605
$good == @have_keys or $self->{"options"}{"allow_others"}
l!l&&r!l&&!r
410
MC/DC33%1/3
$good == @want_keys and $good == @have_keys || $self->{"options"}{"allow_others"}
$good == @want_keys $good == @have_keys $self->{"options"}{"allow_others"}
Truth table75%3/4
A and B or C
A= $good == @want_keysB= $good == @have_keysC= $self->{"options"}{"allow_others"}
ABCresult
0XX0
1000
11X1
1011
169 and ($good == @have_keys or $self->{options}{allow_others})) {
170 5 $self->{matched} = $mol;
171 5 return 1;
172 }
173 6 0;
174 }
175  
176 ### Code derived from formula.pl by Brent Gregersen follows
177  
178 2 my %macros = (
179 Me => '(CH3)',
180 Et => '(CH3CH2)',
181 Bu => '(C4H9)',
182 Bn => '(C6H5CH2)',
183 Cp => '(C5H5)',
184 Ph => '(C6H5)',
185 Bz => '(C6H5CO)',
186 # Ac is an element
187 # Pr is an element
188 );
189  
190  
191 15 ▶sub parse_formula {
Subroutine parse_formula: called CC=6 SCAR=22.4
Pod undocumented
192 15 my ($formula) = @_;
193 15 my (%elements);
194  
195 #check balancing
196 15 ▶ return %elements if (!ParensBalanced($formula));
Branch: 1 branch
BranchTrueFalseTotal
unless ParensBalanced($formula) 0 15 15
197  
198 # replace other grouping with normal parens
199 15 $formula =~ tr/<>{}[]/()()()/;
200  
201 # get rid of any spaces
202 15 $formula =~ s/\s+//g;
203  
204 # perform macro expansion
205 15 foreach (keys(%macros)) {
206 105 $formula =~ s/$_/$macros{$_}/g;
207 }
208  
209 # determine initial compound coeficent
210 15 my ($low, $high, $is_range) = (1,1);
211 15 ▶ if ($formula =~ s/^(\d+)(-?)(\d*)//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($formula =~ s/^(\d+)(-?)(\d*)//) 0 15 15
212 0 ($low, $is_range, $high) = ($1, $2, $3);
213 0 ▶ if ($is_range) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_range) { } 0 0 0
214 0 ▶ $high = 1E10 unless length $high;
Branch: 1 branch
BranchTrueFalseTotal
unless length $high 0 0 0
215 } else {
216 0 $high = $low;
217 }
218 }
219  
220 # recursively process rest of formula
221 15 return internal_formula_parser($formula, $low, $high, %elements);
222 }
223  
224 17 ▶sub internal_formula_parser {
Subroutine internal_formula_parser: called CC=9 SCAR=23.7
Pod undocumented
225 17 my ($formula, $low, $high, %form) = @_;
226 17 my ($tmp_low, $tmp_high, $tmp_is_range);
227  
228 17 my ($extract, $remainder, $prefix) =
229 extract_bracketed($formula, '()', '[^(]*');
230  
231 17 ▶ if (defined($extract) and $extract ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $extract and $extract ne '') { } 2 15 17
Condition66%2/3
defined $extract and $extract ne ""
!ll&&!rl&&r
1502
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
232 2 $extract =~ s/^\((.*)\)$/$1/;
233 2 ▶ if ($remainder =~ s/^(\d+)(-?)(\d*)//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remainder =~ s/^(\d+)(-?)(\d*)//) { } 2 0 2
234 2 ($tmp_low, $tmp_is_range, $tmp_high) = ($1, $2, $3);
235 2 ▶ if ($tmp_is_range) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tmp_is_range) { } 2 0 2
236 2 ▶ $tmp_high = 1E10 unless length $tmp_high;
Branch: 1 branch
BranchTrueFalseTotal
unless length $tmp_high 0 2 2
237 } else {
238 0 $tmp_high = $tmp_low;
239 }
240 2 $tmp_low = $tmp_low * $low;
241 2 $tmp_high = $tmp_high * $high;
242 } else {
243 0 $tmp_low = $low;
244 0 $tmp_high = $high;
245 }
246  
247 # get formula of prefix ( it has no parens)
248 2 ▶ %form = add_formula_strings($prefix, $low, $high, %form) if ($prefix ne '');
Branch: 1 branch
BranchTrueFalseTotal
if $prefix ne "" 0 2 2
249  
250 # check remainder for more parens
251 2 ▶ %form = internal_formula_parser($remainder, $low, $high, %form)
Branch: 1 branch
BranchTrueFalseTotal
if $remainder ne "" 0 2 2
252 if ($remainder ne '');
253  
254 # check extract for more parens
255 2 %form =
256 internal_formula_parser($extract, $tmp_low, $tmp_high, %form);
257 ## we already know this is ne ''
258 } else { # get formula of complete string
259 15 ▶ %form = add_formula_strings($remainder, $low, $high, %form)
Branch: 1 branch
BranchTrueFalseTotal
if $remainder ne "" 15 0 15
260 if ($remainder ne '');
261 }
262 17 return %form;
263 }
264  
265 15 ▶sub add_formula_strings {
Subroutine add_formula_strings: called CC=6 SCAR=17.9
Pod undocumented
266 15 my ($formula, $low_coef, $high_coef, %elements) = @_;
267  
268 # print "Getting Formula of $formula\n";
269 15 ▶ $formula =~ /^(?:([A-Z][a-z]*)(\d+-?\d*)?)+$/o
Branch: 1 branch
BranchTrueFalseTotal
$formula =~ /^(?:([A-Z][a-z]*)(\d+-?\d*)?)+$/o or croak("Invalid Portion of Formula $formula") 15 0 15
270 or croak "Invalid Portion of Formula $formula";
271 15 ▶ while ($formula =~ m/([A-Z][a-z]*)(?:(\d+)(-?)(\d*))?/go) {
Branch: 1 branch
BranchTrueFalseTotal
if ($formula =~ /([A-Z][a-z]*)(?:(\d+)(-?)(\d*))?/go) 33 15 48
272 33 my ($elm, $low, $is_range, $high) = ($1, $2, $3, $4);
273 33 ▶ $low = 1 unless defined $low;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $low 15 18 33
274 33 ▶ if ($is_range) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_range) { } 10 23 33
275 10 ▶ $high = 1E10 unless length $high;
Branch: 1 branch
BranchTrueFalseTotal
unless length $high 3 7 10
276 } else {
277 23 $high = $low;
278 }
279 33 $elements{$elm}{low} += $low_coef * $low;
280 33 $elements{$elm}{high} += $high_coef * $high;
281 }
282 15 return %elements;
283 }
284  
285 15 ▶sub ParensBalanced {
Subroutine ParensBalanced: called CC=6 SCAR=18.1
Pod undocumented
286 15 my ($form) = @_;
287 15 my @stack = ();
288 15 my %pairs = (
289 '<' => '>',
290 '{' => '}',
291 '[' => ']',
292 '(' => ')'
293 );
294  
295 15 ▶ while ($form =~ m/([<>(){}\]\[])/go) {
Branch: 1 branch
BranchTrueFalseTotal
if ($form =~ /([<>(){}\]\[])/go) 4 15 19
296 4 my $current = $1;
297 4 ▶ if ($current =~ /[<({\[]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current =~ /[<({\[]/) 2 2 4
298 2 push(@stack, $current);
299 2 next;
300 }
301 2 ▶ return 0 if (scalar(@stack) == 0);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @stack == 0 0 2 2
302 2 ▶ return 0 if ($current ne $pairs{ pop @stack});
Branch: 1 branch
BranchTrueFalseTotal
if $current ne $pairs{pop @stack} 0 2 2
303 }
304 15 ▶ return @stack ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
@stack ? : 0 15 15
305 }
306  
307  
308  
309  
310 2 1;
311  
312  
313  
314 =head1 VERSION
315  
316 0.10
317  
318 =head1 SEE ALSO
319  
320 L<Chemistry::Pattern>
321  
322 The PerlMol website L<http://www.perlmol.org/>
323  
324 =head1 AUTHOR
325  
326 Ivan Tubert-Brohman E<lt>itub@cpan.orgE<gt>
327  
328 =head1 COPYRIGHT
329  
330 Copyright (c) 2004 Ivan Tubert-Brohman. All rights reserved. This program is
331 free software; you can redistribute it and/or modify it under the same terms as
332 Perl itself.
333  
334 =cut
335  
336  
↑ Summary File/FormulaPattern.pm »