blib/lib/Chemistry/Mol.pm

filter: Statementstmt 73.0% 244 / 334 Branchbran 58.1% 43 / 74 Conditioncond 28.5% 2 / 7 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 84.2% 48 / 57 Podpod 83.3% 35 / 42 totaltotal 71.8% 372 / 518 CC 75 SCAR 21.5
CC
75
Cov
70%
distance
72.0
charge
30.0
sprintf
9.8
CRAP 8.6
« blib/lib/Chemistry/File.pm ↑ Summary blib/lib/Parse/Yapp/Lalr.pm »
1 package Chemistry::Mol;
2 27 $VERSION = '0.35';
3 # $Id: Mol.pm,v 1.48 2005/05/20 19:01:04 itubert Exp $
4  
5 =head1 NAME
6  
7 Chemistry::Mol - Molecule object toolkit
8  
9 =head1 SYNOPSIS
10  
11 use Chemistry::Mol;
12  
13 $mol = Chemistry::Mol->new(id => "mol_id", name => "my molecule");
14 $c = $mol->new_atom(symbol => "C", coords => [0,0,0]);
15 $o = $mol->new_atom(symbol => "O", coords => [0,0,1.23]);
16 $mol->new_bond(atoms => [$c, $o], order => 3);
17  
18 print $mol->print;
19  
20 =head1 DESCRIPTION
21  
22 This package, along with Chemistry::Atom and Chemistry::Bond, includes basic
23 objects and methods to describe molecules.
24  
25 The core methods try not to enforce a particular convention. This means that
26 only a minimal set of attributes is provided by default, and some attributes
27 have very loosely defined meaning. This is because each program and file type
28 has different idea of what each concept (such as bond and atom type) means.
29 Bonds are defined as a list of atoms (typically two) with an arbitrary type.
30 Atoms are defined by a symbol and a Z, and may have 3D and internal coordinates
31 (2D coming soon).
32  
33 =cut
34  
35 27 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 27 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 27 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 27 ▶use Chemistry::Atom;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 27 ▶use Chemistry::Bond;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 27 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 27 ▶use base qw(Chemistry::Obj Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
42 27 ▶use Storable 'dclone';
Subroutine BEGIN: called CC=1 SCAR=0.0
43  
44 27 our @EXPORT_OK = qw(read_mol);
45 27 our @EXPORT = ();
46 27 our %EXPORT_TAGS = (
47 all => [@EXPORT, @EXPORT_OK],
48 );
49  
50  
51  
52 27 my %FILE_FORMATS = ();
53  
54 =head1 METHODS
55  
56 See also L<Chemistry::Obj> for generic attributes.
57  
58 =over 4
59  
60 =item Chemistry::Mol->new(name => value, ...)
61  
62 Create a new Mol object with the specified attributes.
63  
64 $mol = Chemistry::Mol->new(id => 'm123', name => 'my mol')
65  
66 is the same as
67  
68 Chemistry::Mol->new()
69 $mol->id('m123')
70 $mol->name('my mol')
71  
72 =cut
73  
74 46 ▶sub new {
Subroutine new: called CC=3 SCAR=11.0
Pod documented
75 46 my $class = shift;
76 46 my %args = @_;
77 46 ▶ my $self = bless {
Condition66%2/3
ref $class || $class
l!l&&r!l&&!r
2440
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table66%2/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
78 id => $class->nextID,
79 byId => {},
80 atoms => [],
81 bonds => [],
82 name => "",
83 }, ref $class || $class;
84 46 $self->$_($args{$_}) for (keys %args);
85 46 return $self;
86 }
87  
88 27 my $N = 0; # atom ID counter
89 47 ▶sub nextID { "mol".++$N; }
Subroutine nextID: called CC=1 SCAR=0.0
Pod undocumented
90 0 ▶sub reset_id { $N = 0; }
Subroutine reset_id: not called CC=1 SCAR=6.9
Pod undocumented
91  
92 =item $mol->add_atom($atom, ...)
93  
94 Add one or more Atom objects to the molecule. Returns the last atom added.
95  
96 =cut
97  
98 674 ▶sub add_atom {
Subroutine add_atom: called CC=2 SCAR=6.9
Pod documented
99 674 my $self = shift;
100 674 for my $atom (@_){
101 #if ($self->by_id($atom->id)) {
102 #croak "Duplicate ID when adding atom '$atom' to mol '$self'";
103 #}
104 675 push @{$self->{atoms}}, $atom;
105 675 $self->{byId}{$atom->id} = $atom;
106 675 $atom->parent($self);
107 }
108 674 $_[-1];
109 }
110  
111 0 ▶sub add_atom_np {
Subroutine add_atom_np: not called CC=2 SCAR=17.9
Pod undocumented
112 0 my $self = shift;
113 0 for my $atom (@_){
114 0 push @{$self->{atoms}}, $atom;
115 0 $self->{byId}{$atom->id} = $atom;
116 }
117 0 $_[-1];
118 }
119  
120 =item $mol->atom_class
121  
122 Returns the atom class that a molecule or molecule class expects to use by
123 default. L<Chemistry::Mol> objects return "Chemistry::Atom", but subclasses
124 will likely override this method.
125  
126 =cut
127  
128 141 ▶sub atom_class {
Subroutine atom_class: called CC=1 SCAR=0.0
Pod documented
129 141 "Chemistry::Atom";
130 }
131  
132 =item $mol->new_atom(name => value, ...)
133  
134 Shorthand for C<< $mol->add_atom($mol->atom_class->new(name => value, ...)) >>.
135  
136 =cut
137  
138 141 ▶sub new_atom {
Subroutine new_atom: called CC=1 SCAR=0.0
Pod documented
139 141 my $self = shift;
140 141 $self->add_atom($self->atom_class->new(@_));
141 }
142  
143 =item $mol->delete_atom($atom, ...)
144  
145 Deletes an atom from the molecule. It automatically deletes all the bonds in
146 which the atom participates as well. $atom should be a Chemistry::Atom
147 reference. This method also accepts the atom index, but this use is deprecated
148 (and buggy if multiple indices are given, unless they are in descending order).
149  
150 =cut
151  
152 2 ▶sub delete_atom {
Subroutine delete_atom: called CC=4 SCAR=13.9
Pod documented
153 2 my $self = shift;
154 2 for my $i (@_) {
155 2 my ($atom);
156 2 ▶ if (ref $i) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $i) { } 1 1 2
157 1 $atom = $i;
158 } else {
159 1 ▶ $atom = $self->atoms($i)
Branch: 1 branch
BranchTrueFalseTotal
$atom = $self->atoms($i) or croak("$self->delete_atom: no such atom $i\n") 1 0 1
160 or croak "$self->delete_atom: no such atom $i\n";
161 }
162 2 $atom->delete($i);
163 }
164 }
165  
166 # takes an atom ref to delete and optionally the atom index
167 # 1) deletes bonds that belonged to atom
168 # 2) deletes atom
169 7 ▶sub _delete_atom {
Subroutine _delete_atom: called CC=2 SCAR=7.0
170 7 my ($self, $atom) = @_;
171 7 ▶ my $index = $self->get_atom_index($atom)
Branch: 1 branch
BranchTrueFalseTotal
my $index = $self->get_atom_index($atom) or croak("$self->delete_atom: no such atom $atom\n") 7 0 7
172 or croak "$self->delete_atom: no such atom $atom\n";
173 7 my $id = $atom->id;
174 7 $self->delete_bond($atom->bonds);
175 7 delete $self->{byId}{$id};
176 7 splice @{$self->{atoms}}, $index - 1, 1;
177 }
178  
179 =item $mol->add_bond($bond, ...)
180  
181 Add one or more Bond objects to the molecule. Returns the last bond added.
182  
183 =cut
184  
185 160 ▶sub add_bond {
Subroutine add_bond: called CC=4 SCAR=13.9
Pod documented
186 160 my $self = shift;
187 160 for my $bond (@_){
188 #if ($self->by_id($bond->id)) {
189 #croak "Duplicate ID when adding bond '$bond' to mol '$self'";
190 #}
191 160 push @{$self->{bonds}}, $bond;
192 160 $self->{byId}{$bond->id} = $bond;
193 160 ▶ if ($bond->{deleted}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bond->{"deleted"}) 1 159 160
194 1 $_->add_bond($bond) for $bond->atoms;
195 1 $bond->{deleted} = 0;
196 }
197 160 $bond->parent($self);
198 }
199 160 $_[-1];
200 }
201  
202 0 ▶sub add_bond_np {
Subroutine add_bond_np: not called CC=2 SCAR=17.9
Pod undocumented
203 0 my $self = shift;
204 0 for my $bond (@_){
205 0 push @{$self->{bonds}}, $bond;
206 0 $self->{byId}{$bond->id} = $bond;
207 }
208 0 $_[-1];
209 }
210  
211 =item $mol->bond_class
212  
213 Returns the bond class that a molecule or molecule class expects to use by
214 default. L<Chemistry::Mol> objects return "Chemistry::Bond", but subclasses
215 will likely override this method.
216  
217 =cut
218  
219 121 ▶sub bond_class {
Subroutine bond_class: called CC=1 SCAR=0.0
Pod documented
220 121 "Chemistry::Bond";
221 }
222  
223 =item $mol->new_bond(name => value, ...)
224  
225 Shorthand for C<< $mol->add_bond($mol->bond_class->new(name => value, ...)) >>.
226  
227 =cut
228  
229 121 ▶sub new_bond {
Subroutine new_bond: called CC=1 SCAR=0.0
Pod documented
230 121 my $self = shift;
231 121 $self->add_bond($self->bond_class->new(@_));
232 }
233  
234 14 ▶sub get_bond_index {
Subroutine get_bond_index: called CC=3 SCAR=11.0
Pod undocumented
235 14 my ($self, $bond) = @_;
236 14 my $i;
237 14 for ($self->bonds) {
238 42 ++$i;
239 42 ▶ return $i if ($_ eq $bond);
Branch: 1 branch
BranchTrueFalseTotal
if $_ eq $bond 14 28 42
240 }
241 0 undef;
242 }
243  
244 7 ▶sub get_atom_index {
Subroutine get_atom_index: called CC=3 SCAR=11.0
Pod undocumented
245 7 my ($self, $atom) = @_;
246 7 my $i;
247 7 for ($self->atoms) {
248 12 ++$i;
249 12 ▶ return $i if ($_ eq $atom);
Branch: 1 branch
BranchTrueFalseTotal
if $_ eq $atom 7 5 12
250 }
251 0 undef;
252 }
253  
254 =item $mol->delete_bond($bond, ...)
255  
256 Deletes a bond from the molecule. $bond should be a L<Chemistry::Bond> object.
257  
258 =cut
259  
260 # mol deletes bond
261 # bond tells atoms involved to forget about it
262  
263 7 ▶sub delete_bond {
Subroutine delete_bond: called CC=4 SCAR=15.6
Pod documented
264 7 my $self = shift;
265 7 for my $i (@_){
266 11 my ($bond);
267 11 ▶ if (ref $i) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $i) { } 11 0 11
268 11 $bond = $i;
269 } else {
270 0 ▶ $bond = $self->bonds($i)
Branch: 1 branch
BranchTrueFalseTotal
$bond = $self->bonds($i) or croak("$self->delete_bond: no such bond $i\n") 0 0 0
271 or croak "$self->delete_bond: no such bond $i\n";
272 }
273 11 $bond->delete;
274 }
275 }
276  
277 14 ▶sub _delete_bond {
Subroutine _delete_bond: called CC=2 SCAR=7.0
278 14 my ($self, $bond) = @_;
279 14 ▶ my $index = $self->get_bond_index($bond)
Branch: 1 branch
BranchTrueFalseTotal
my $index = $self->get_bond_index($bond) or croak("$self->delete_bond: no such bond $bond\n") 14 0 14
280 or croak "$self->delete_bond: no such bond $bond\n";
281 14 my $id = $bond->id;
282 14 delete $self->{byId}{$id};
283 14 splice @{$self->{bonds}}, $index - 1, 1;
284 14 $bond->delete_atoms;
285 }
286  
287 =item $mol->by_id($id)
288  
289 Return the atom or bond object with the corresponding id.
290  
291 =cut
292  
293 59 ▶sub by_id {
Subroutine by_id: called CC=1 SCAR=0.0
Pod documented
294 59 my $self = shift;
295 59 my ($id) = @_;
296 59 $self->{byId}{$id};
297 }
298  
299 4 ▶sub _change_id {
Subroutine _change_id: called CC=1 SCAR=0.0
300 4 my ($self, $old_id, $new_id) = @_;
301 4 my $ref = $self->{byId}{$old_id};
302 4 $self->{byId}{$new_id} = $ref;
303 4 delete $self->{byId}{$old_id};
304 }
305  
306 =item $mol->atoms($n1, ...)
307  
308 Returns the atoms with the given indices, or all by default.
309 Indices start from one, not from zero.
310  
311 =cut
312  
313 4089 ▶sub atoms {
Subroutine atoms: called CC=2 SCAR=6.9
Pod documented
314 4089 my $self = shift;
315 4089 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 46 4043 4089
316 46 my @ats = map {$_ - 1} @_;
317 46 @{$self->{atoms}}[@ats];
318 } else {
319 4043 @{$self->{atoms}};
320 }
321 }
322  
323 =item $mol->atoms_by_name($name)
324  
325 Returns the atoms with the given name (treated as an anchored regular
326 expression).
327  
328 =cut
329  
330 1 ▶sub atoms_by_name {
Subroutine atoms_by_name: called CC=2 SCAR=7.0
Pod documented
331 1 my $self = shift;
332 1 my $re = qr/^$_[0]$/;
333 27 ▶ no warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
334 1 my @ret = grep {$_->name =~ $re} $self->atoms;
335 1 ▶ wantarray ? @ret : $ret[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 1 1
336 }
337  
338 =item $mol->sort_atoms($sub_ref)
339  
340 Sort the atoms in the molecule by using the comparison function given in
341 $sub_ref. This function should take two atoms as parameters and return -1, 0,
342 or 1 depending on whether the first atom should go before, same, or after the
343 second atom. For example, to sort by atomic number, you could use the
344 following:
345  
346 $mol->sort_atoms( sub { $_[0]->Z <=> $_[1]->Z } );
347  
348 Note that the atoms are passed as parameters and not as the package variables
349 $a and $b like the core sort function does. This is because $mol->sort will
350 likely be called from another package and we don't want to play with another
351 package's symbol table.
352  
353 =cut
354  
355 0 ▶sub sort_atoms {
Subroutine sort_atoms: not called CC=1 SCAR=6.9
Pod documented
356 0 my ($self, $sub) = @_;
357 0 my @a = $self->atoms;
358 0 @a = sort { $sub->($a,$b) } @a;
359 0 $self->{atoms} = \@a;
360 0 $self;
361 }
362  
363 =item $mol->bonds($n1, ...)
364  
365 Returns the bonds with the given indices, or all by default.
366 Indices start from one, not from zero.
367  
368 =cut
369  
370 2995 ▶sub bonds {
Subroutine bonds: called CC=2 SCAR=6.9
Pod documented
371 2995 my $self = shift;
372 2995 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 6 2989 2995
373 6 my @bonds = map {$_ - 1} @_;
374 6 @{$self->{bonds}}[@bonds];
375 } else {
376 2989 @{$self->{bonds}};
377 }
378 }
379  
380 =item $mol->print(option => value...)
381  
382 Convert the molecule to a string representation. If no options are given,
383 a default YAML-like format is used (this may change in the future). Otherwise,
384 the format should be specified by using the C<format> option.
385  
386 =cut
387  
388 15 ▶sub print {
Subroutine print: called CC=4 SCAR=21.3
Pod documented
389 15 my $self = shift;
390 15 my (%opts) = @_;
391 15 my $ret;
392 15 local $" = ""; #"
393  
394 15 ▶ if ($opts{format}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"format"}) 15 0 15
395 15 return $self->formats($opts{format})->write_string($self, %opts);
396 }
397 # else use default printout
398 0 $ret = <<END;
399 $self->{id}:
400 name: $self->{name}
401 END
402 0 $ret .= " attr:\n";
403 0 $ret .= $self->print_attr(2);
404 0 $ret .= " atoms:\n";
405 0 for my $a (@{$self->{atoms}}) { $ret .= $a->print(2) }
406 0 $ret .= " bonds:\n";
407 0 for my $b (@{$self->{bonds}}) { $ret .= $b->print(2) }
408 0 $ret;
409 }
410  
411 =item $s = $mol->sprintf($format)
412  
413 Format interesting molecular information in a concise way, as specified by
414 a printf-like format.
415  
416 %n - name
417 %f - formula
418 %f{formula with format} - (note: right braces within
419 the format should be escaped with a backslash)
420 %s - SMILES representation
421 %S - canonical SMILES representation
422 %m - mass
423 %8.3m - mass, formatted as %8.3f with core sprintf
424 %q - formal charge
425 %a - atom count
426 %b - bond count
427 %t - type
428 %i - id
429 %% - %
430  
431 For example, if you want just about everything:
432  
433 $mol->sprintf("%s - %n (%f). %a atoms, %b bonds; "
434 . "mass=%m; charge =%q; type=%t; id=%i");
435  
436 Note that you have to C<use Chemistry::File::SMILES> before using C<%s> or
437 C<%S> on C<< $mol->sprintf >>.
438  
439 =cut
440  
441 0 ▶sub sprintf {
Subroutine sprintf: not called CC=3 SCAR=22.8
Pod documented
442 0 my ($mol, $format) = @_;
443 27 ▶ no warnings 'uninitialized'; # don't care if some properties are undefined
Subroutine BEGIN: called CC=1 SCAR=0.0
444 0 ▶ $format ||= "%f";
Condition0%0/2
$format ||= "%f"
l!l
00
MC/DC0%0/1
$format ||= "%f"
$format
Truth table0%0/2
A
A= $format
Aresult
11
00
445 0 $format =~ s/%%/\\%/g; # escape %% with a \
446 0 $format =~ s/(?<!\\)%f\{(.*?)(?<!\\)\}/$mol->formula($1)/eg; # %f{}
447 0 $format =~ s/(?<!\\)%f/$mol->formula/eg; # %f
448 0 $format =~ s/(?<!\\)%s/$mol->print(format=>'smiles')/eg; # %s
449 0 $format =~ s/(?<!\\)%S/$mol->print(format=>'smiles', unique => 1)/eg; # %s
450 0 $format =~ s/(?<!\\)%n/$mol->name/eg; # %n
451 0 $format =~ s/(?<!\\)%(\d*\.?\d*)m/
452 0 ▶ $1 ? sprintf "%$1f", $mol->mass : $mol->mass/eg; # %m
Branch: 1 branch
BranchTrueFalseTotal
$1 ? : 0 0 0
453 0 $format =~ s/(?<!\\)%q/$mol->charge/eg; # %q
454 0 $format =~ s/(?<!\\)%a/$mol->atoms/eg; # %a
455 0 $format =~ s/(?<!\\)%b/$mol->bonds/eg; # %b
456 0 $format =~ s/(?<!\\)%t/$mol->type/eg; # %t
457 0 $format =~ s/(?<!\\)%i/$mol->id/eg; # %i
458 0 $format =~ s/\\(.)/$1/g; # other \ escapes
459 0 $format;
460 }
461  
462 =item $mol->printf($format)
463  
464 Same as C<< $mol->sprintf >>, but prints to standard output automatically.
465 Used for quick and dirty molecular information dumping.
466  
467 =cut
468  
469 0 ▶sub printf {
Subroutine printf: not called CC=1 SCAR=6.9
Pod documented
470 0 my ($mol, $format) = @_;
471 0 print $mol->sprintf($format);
472 }
473  
474 =item Chemistry::Mol->parse($string, option => value...)
475  
476 Parse the molecule encoded in C<$string>. The format should be specified
477 with the the C<format> option; otherwise, it will be guessed.
478  
479 =cut
480  
481 34 ▶sub parse {
Subroutine parse: called CC=2 SCAR=7.6
Pod documented
482 34 my $self = shift;
483 34 my $s = shift;
484 34 my %opts = (mol_class => $self, @_);
485  
486 34 ▶ if ($opts{format}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{'format'}) { } 34 0 34
487 34 return $self->formats($opts{format})->parse_string($s, %opts);
488 } else {
489 0 croak "Parse does not support autodetection yet.",
490 "Please specify a format.";
491 }
492 0 return;
493 }
494  
495 =item Chemistry::Mol->read($fname, option => value ...)
496  
497 Read a file and return a list of Mol objects, or croaks if there was a problem.
498 The type of file will be guessed if not specified via the C<format> option.
499  
500 Note that only registered file readers will be used. Readers may be registered
501 using C<register_type()>; modules that include readers (such as
502 L<Chemistry::File::PDB>) usually register them automatically when they are
503 loaded.
504  
505 Automatic decompression of gzipped files is supported if the L<Compress::Zlib>
506 module is installed. Files ending in .gz are assumed to be compressed;
507 otherwise it is possible to force decompression by passing the gzip => 1
508 option (or no decompression with gzip => 0).
509  
510 =cut
511  
512 0 ▶sub read_mol { # for backwards compatibility
Subroutine read_mol: not called CC=1 SCAR=6.9
Pod undocumented
513 0 my ($fname, $type) = shift;
514 0 __PACKAGE__->read($fname, format => $type);
515 }
516  
517 15 ▶sub read {
Subroutine read: called CC=4 SCAR=13.9
Pod documented
518 15 my $self = shift;
519 15 my $fname = shift;
520 15 my %opts = (mol_class => $self, @_);
521  
522 15 ▶ if ($opts{format}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{'format'}) { } 6 9 15
523 6 return $self->formats($opts{format})->parse_file($fname, %opts);
524 } else { # guess format
525 9 for my $type ($self->formats) {
526 9 ▶ if ($self->formats($type)->file_is($fname)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->formats($type)->file_is($fname)) 8 1 9
527 8 return $self->formats($type)->parse_file($fname, %opts);
528 }
529 }
530 }
531 1 croak "Couldn't guess format of file '$fname'";
532 }
533  
534 =item $mol->write($fname, option => value ...)
535  
536 Write a molecule file, or croak if there was a problem. The type of file will
537 be guessed if not specified via the C<format> option.
538  
539 Note that only registered file formats will be used.
540  
541 Automatic gzip compression is supported if the IO::Zlib module is installed.
542 Files ending in .gz are assumed to be compressed; otherwise it is possible to
543 force compression by passing the gzip => 1 option (or no compression with gzip
544 => 0). Specific compression levels between 2 (fastest) and 9 (most compressed)
545 may also be used (e.g., gzip => 9).
546  
547 =cut
548  
549 4 ▶sub write {
Subroutine write: called CC=4 SCAR=13.9
Pod documented
550 4 my ($self, $fname, %opts) = (@_);
551  
552 4 ▶ if ($opts{format}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{'format'}) { } 2 2 4
553 2 return $self->formats($opts{format})->write_file(@_);
554 } else { # guess format
555 2 for my $type ($self->formats) {
556 2 ▶ if ($self->formats($type)->name_is($fname)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->formats($type)->name_is($fname)) 1 1 2
557 1 return $self->formats($type)->write_file(@_);
558 }
559 }
560 }
561 1 croak "Couldn't guess format for writing file '$fname'";
562 }
563  
564 =item Chemistry::Mol->file($file, option => value ...)
565  
566 Create a L<Chemistry::File>-derived object for reading or writing to a file.
567 The object can then be used to read the molecules or other information in the
568 file.
569  
570 This has more flexibility than calling C<< Chemistry::Mol->read >> when
571 dealing with multi-molecule files or files that have higher structure or that
572 have information that does not belong to the molecules themselves. For
573 example, a reaction file may have a list of molecules, but also general
574 information like the reaction name, yield, etc. as well as the classification
575 of the molecules as reactants or products. The exact information that is
576 available will depend on the file reader class that is being used. The
577 following is a hypothetical example for reading MDL rxnfiles.
578  
579 # assuming this module existed...
580 use Chemistry::File::Rxn;
581  
582 my $rxn = Chemistry::Mol->file('test.rxn');
583 $rxn->read;
584 $name = $rxn->name;
585 @reactants = $rxn->reactants; # mol objects
586 @products = $rxn->products;
587 $yield = $rxn->yield; # a number
588  
589 Note that only registered file readers will be used. Readers may be registered
590 using register_type(); modules that include readers (such as
591 Chemistry::File::PDB) usually register them automatically.
592  
593 =cut
594  
595 1 ▶sub file {
Subroutine file: called CC=4 SCAR=15.2
Pod documented
596 1 my ($self, $file, %opts) = @_;
597 1 %opts = (mol_class => $self, %opts);
598  
599 1 ▶ if ($opts{format}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{'format'}) { } 0 1 1
600 0 return $self->formats($opts{format})->new(file => $file,
601 opts => \%opts);
602 } else { # guess format
603 1 for my $type ($self->formats) {
604 1 ▶ if ($self->formats($type)->file_is($file)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->formats($type)->file_is($file)) 1 0 1
605 1 return $self->formats($type)->new(file => $file,
606 opts => \%opts);
607 }
608 }
609 }
610 0 croak "Couldn't guess format of file '$file'";
611 }
612  
613 =item Chemistry::Mol->register_format($name, $ref)
614  
615 Register a file type. The identifier $name must be unique. $ref is either a
616 class name (a package) or an object that complies with the L<Chemistry::File>
617 interface (e.g., a subclass of Chemistry::File). If $ref is omitted, the
618 calling package is used automatically. More than one format can be registered
619 at a time, but then $ref must be included for each format (e.g.,
620 Chemistry::Mol->register_format(format1 => "package1", format2 => package2).
621  
622 The typical user doesn't have to care about this function. It is used
623 automatically by molecule file I/O modules.
624  
625 =cut
626  
627 135 ▶sub register_format {
Subroutine register_format: called CC=3 SCAR=11.0
Pod documented
628 135 my $class = shift;
629 135 ▶ if (@_ == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1) 41 94 135
630 41 $FILE_FORMATS{$_[0]} = caller;
631 41 return;
632 }
633 94 my %opts = @_;
634 94 $FILE_FORMATS{$_} = $opts{$_} for keys %opts;
635 }
636  
637 =item Chemistry::Mol->formats
638  
639 Returns a list of the file formats that have been installed by
640 register_type()
641  
642 =cut
643  
644 91 ▶sub formats {
Subroutine formats: called CC=3 SCAR=11.0
Pod documented
645 91 my $self = shift;
646 91 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 79 12 91
647 79 my ($type) = @_;
648 79 my $file_class = $FILE_FORMATS{$type};
649 79 ▶ unless ($file_class) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($file_class) 1 78 79
650 1 croak "No class installed for type '$type'";
651 }
652 78 return $file_class;
653 } else {
654 12 return sort keys %FILE_FORMATS;
655 }
656 }
657  
658 =item $mol->mass
659  
660 Return the molar mass. This is just the sum of the masses of the atoms. See
661 L<Chemistry::Atom>::mass for details such as the handling of isotopes.
662  
663 =cut
664  
665 2 ▶sub mass {
Subroutine mass: called CC=2 SCAR=6.9
Pod documented
666 2 my ($self) = @_;
667 2 my $mass = 0;
668 2 for my $atom ($self->atoms) {
669 6 $mass += $atom->mass;
670 }
671 2 $mass;
672 }
673  
674 =item $mol->charge
675  
676 Return the charge of the molecule. By default it returns the sum of the formal
677 charges of the atoms. However, it is possible to set an arbitrary charge by
678 calling C<< $mol->charge($new_charge) >>
679  
680 =cut
681  
682 0 ▶sub charge {
Subroutine charge: not called CC=5 SCAR=34.0
Pod documented
683 0 my ($self) = shift;
684 0 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 0 0 0
685 0 $self->{charge} = shift;
686 0 $self;
687 } else {
688 0 ▶ return $self->{charge} if defined $self->{charge};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"charge"} 0 0 0
689 0 my $charge = 0;
690 0 ▶ $charge += $_->formal_charge || 0 for $self->atoms;
Condition0%0/2
$_->formal_charge || 0
l!l
00
MC/DC0%0/1
$_->formal_charge || 0
$_->formal_charge
Truth table0%0/2
A
A= $_->formal_charge
Aresult
11
00
691 0 $charge;
692 }
693 }
694  
695 =item $mol->formula_hash
696  
697 Returns a hash reference describing the molecular formula. For methane it would
698 return { C => 1, H => 4 }.
699  
700 =cut
701  
702 12 ▶sub formula_hash {
Subroutine formula_hash: called CC=3 SCAR=11.0
Pod documented
703 12 my ($self) = @_;
704 12 my $formula = {};
705 12 for my $atom ($self->atoms) {
706 500 $formula->{$atom->symbol}++;
707 500 ▶ $formula->{H} += $atom->hydrogens if $atom->hydrogens;
Branch: 1 branch
BranchTrueFalseTotal
if $atom->hydrogens 0 500 500
708 }
709 12 $formula;
710 }
711  
712 =item $mol->formula($format)
713  
714 Returns a string with the formula. The format can be specified as a printf-like
715 string with the control sequences specified in the L<Chemistry::File::Formula>
716 documentation.
717  
718 =cut
719  
720 5 ▶sub formula {
Subroutine formula: called CC=1 SCAR=0.0
Pod documented
721 5 my ($self, $format) = @_;
722 5 require Chemistry::File::Formula;
723 5 $self->print(format => "formula", formula_format => $format);
724 }
725  
726 =item my $mol2 = $mol->clone;
727  
728 Makes a copy of a molecule. Note that this is a B<deep> copy; if your molecule
729 has a pointer to the rest of the universe, the entire universe will be cloned!
730  
731 =cut
732  
733 8 ▶sub clone {
Subroutine clone: called CC=2 SCAR=7.0
Pod documented
734 8 my ($self) = @_;
735 8 my $clone = dclone $self;
736 8 ▶ $clone->_weaken if Storable->VERSION < 2.14;
Branch: 1 branch
BranchTrueFalseTotal
if "Storable"->VERSION < "2.14" 0 8 8
737 8 $clone;
738 }
739  
740 =item my $mol2 = $mol->safe_clone;
741  
742 Like clone, it makes a deep copy of a molecule. The difference is that the copy
743 is not "exact" in that new molecule and its atoms and bonds get assigned new
744 IDs. This makes it safe to combine cloned molecules. For example, this is an
745 error:
746  
747 # XXX don't try this at home!
748 my $mol2 = Chemistry::Mol->combine($mol1, $mol1);
749 # the atoms in $mol1 will clash
750  
751 But this is ok:
752  
753 # the "safe clone" of $mol1 will have new IDs
754 my $mol2 = Chemistry::Mol->combine($mol1, $mol1->safe_clone);
755  
756 =cut
757  
758 1 ▶sub safe_clone {
Subroutine safe_clone: called CC=2 SCAR=6.9
Pod documented
759 1 my ($mol) = @_;
760 1 my $clone = $mol->clone;
761 1 for ($clone, $clone->atoms, $clone->bonds) {
762 4 $_->id($_->nextID);
763 }
764 1 $clone;
765 }
766  
767 15 ▶sub _weaken {
Subroutine _weaken: called CC=2 SCAR=6.9
768 15 my ($self) = @_;
769 15 for ($self->atoms, $self->bonds) {
770 205 $_->_weaken;
771 }
772 15 $self;
773 }
774  
775 =item ($distance, $atom_here, $atom_there) = $mol->distance($obj)
776  
777 Returns the minimum distance to $obj, which can be an atom, a molecule, or a
778 vector. In scalar context it returns only the distance; in list context it
779 also returns the atoms involved. The current implementation for calculating
780 the minimum distance between two molecules compares every possible pair of
781 atoms, so it's not efficient for large molecules.
782  
783 =cut
784  
785 0 ▶sub distance {
Subroutine distance: not called CC=8 SCAR=42.8
Pod documented
786 0 my ($self, $other) = @_;
787 0 ▶ if ($other->isa("Chemistry::Mol")) {
Branch: 3 branches
BranchTrueFalseTotal
if ($other->isa('Chemistry::Mol')) { } 0 0 0
elsif ($other->isa('Chemistry::Atom')) { } 0 0 0
elsif ($other->isa('Math::VectorReal')) { } 0 0 0
788 0 my @atoms = $self->atoms;
789 0 ▶ my $atom = shift @atoms or return; # need at least one atom
Branch: 1 branch
BranchTrueFalseTotal
my $atom = shift @atoms or return 0 0 0
790 0 my $closest_here = $atom;
791 0 my ($min_length, $closest_there) = $atom->distance($other);
792 0 for $atom (@atoms) {
793 0 my ($d, $o) = $atom->distance($other);
794 0 ▶ if ($d < $min_length) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d < $min_length) 0 0 0
795 0 ($min_length, $closest_there, $closest_here) = ($d, $o, $atom);
796 }
797 }
798 return wantarray ?
799 0 ▶ ($min_length, $closest_here, $closest_there) : $min_length;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
800 } elsif ($other->isa("Chemistry::Atom")) {
801 0 return $other->distance($self);
802 } elsif ($other->isa("Math::VectorReal")) {
803 0 return Chemistry::Atom->new(coords => $other)->distance($self);
804 }
805 }
806  
807 =item my $bigmol = Chemistry::Mol->combine($mol1, $mol2, ...)
808  
809 =item $mol1->combine($mol2, $mol3, ...)
810  
811 Combines several molecules in one bigger molecule. If called as a class method,
812 as in the first example, it returns a new combined molecule without altering
813 any of the parameters. If called as an instance method, as in the second
814 example, all molecules are combined into $mol1 (but $mol2, $mol3, ...) are not
815 altered. B<Note>: Make sure you don't combine molecules which contain atoms
816 with duplicate IDs (for example, if they were cloned).
817  
818 =cut
819  
820 # joins several molecules into one
821 2 ▶sub combine {
Subroutine combine: called CC=5 SCAR=16.1
Pod documented
822 2 my ($self, @others) = @_;
823 2 my $mol;
824 2 ▶ if (ref $self) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self) { } 1 1 2
825 1 $mol = $self;
826 } else {
827 1 $mol = $self->new;
828 }
829 2 for my $other (@others) {
830 3 my $mol2 = $other->clone;
831 3 for my $atom ($mol2->atoms) {
832 12 $mol->add_atom($atom);
833 }
834 3 for my $bond ($mol2->bonds) {
835 9 $mol->add_bond($bond);
836 }
837 }
838 2 $mol;
839 }
840  
841 =item my @mols = $mol->separate
842  
843 Separates a molecule into "connected fragments". The original object is not
844 modified; the fragments are clones of the original ones. Example: if you have
845 ethane (H3CCH3) and you delete the C-C bond, you have two CH3 radicals within
846 one molecule object ($mol). When you call $mol->separate you get two molecules,
847 each one with a CH3.
848  
849 =cut
850  
851 # splits a molecule into connected fragments
852 # returns a list of molecules. Does not touch the original copy.
853 1 ▶sub separate {
Subroutine separate: called CC=6 SCAR=17.9
Pod documented
854 1 my ($self) = @_;
855 1 $self = $self->clone;
856 1 $self->{_paint_tab} = {};
857 1 my $color = 0;
858 1 for my $atom ($self->atoms) {
859 8 ▶ next if defined $self->{_paint_tab}{$atom->id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_paint_tab"}{$atom->id} 6 2 8
860 2 $self->_paint($atom, $color++);
861 }
862 1 my @mols;
863 1 push @mols, $self->new for (1 .. $color);
864 1 for my $atom ($self->atoms) {
865 8 $mols[$self->{_paint_tab}{$atom->id}]->add_atom($atom);
866 }
867 1 for my $bond ($self->bonds) {
868 6 $mols[$self->{_paint_tab}{$bond->id}]->add_bond($bond);
869 }
870 1 @mols;
871 }
872  
873 # this method fills the _paint_tab attribute for every atom connected
874 # to the given start atom $atom with $color. Used for separating
875 # connected fragments. Uses a depth-first search
876 14 ▶sub _paint {
Subroutine _paint: called CC=4 SCAR=13.9
877 14 my ($self, $atom, $color) = @_;
878 14 ▶ return if defined $self->{_paint_tab}{$atom->id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_paint_tab"}{$atom->id} 6 8 14
879 8 $self->{_paint_tab}{$atom->id} = $color;
880 8 $self->{_paint_tab}{$_->id} = $color for ($atom->bonds);
881 8 for my $neighbor ($atom->neighbors) {
882 12 $self->_paint($neighbor, $color);
883 }
884 }
885  
886 =item $mol->sprout_hydrogens
887  
888 Convert all the implicit hydrogen atoms in the molecule to explicit atoms.
889 It does B<not> generate coordinates for the atoms.
890  
891 =cut
892  
893 15 ▶sub sprout_hydrogens {
Subroutine sprout_hydrogens: called CC=2 SCAR=6.9
Pod documented
894 15 my ($self) = @_;
895 15 $_->sprout_hydrogens for $self->atoms;
896 }
897  
898 =item $mol->collapse_hydrogens
899  
900 Convert all the explicit hydrogen atoms in the molecule to implicit hydrogens.
901 (Exception: hydrogen atoms that are adjacent to a hydrogen atom are not
902 collapsed.)
903  
904 =cut
905  
906 15 ▶sub collapse_hydrogens {
Subroutine collapse_hydrogens: called CC=2 SCAR=6.9
Pod documented
907 15 my ($self) = @_;
908 15 for my $atom (grep { $_->symbol ne 'H' } $self->atoms) {
909 39 $atom->collapse_hydrogens;
910 }
911 }
912  
913 =item $mol->add_implicit_hydrogens
914  
915 Use heuristics to figure out how many implicit hydrogens should each atom in
916 the molecule have to satisfy its normal "organic" valence.
917  
918 =cut
919  
920 1 ▶sub add_implicit_hydrogens {
Subroutine add_implicit_hydrogens: called CC=2 SCAR=6.9
Pod documented
921 1 my ($self) = @_;
922 1 $_->add_implicit_hydrogens for $self->atoms;
923 }
924  
925 27 1;
926  
927 =back
928  
929 =head1 VERSION
930  
931 0.35
932  
933 =head1 SEE ALSO
934  
935 L<Chemistry::Atom>, L<Chemistry::Bond>, L<Chemistry::File>,
936 L<Chemistry::Tutorial>
937  
938 The PerlMol website L<http://www.perlmol.org/>
939  
940 =head1 AUTHOR
941  
942 Ivan Tubert-Brohman E<lt>itub@cpan.orgE<gt>
943  
944 =head1 COPYRIGHT
945  
946 Copyright (c) 2005 Ivan Tubert-Brohman. All rights reserved. This program is
947 free software; you can redistribute it and/or modify it under the same terms as
948 Perl itself.
949  
950 =cut
951  
« blib/lib/Chemistry/File.pm ↑ Summary blib/lib/Parse/Yapp/Lalr.pm »