-
Notifications
You must be signed in to change notification settings - Fork 90
/
molecule.py
6187 lines (5140 loc) · 221 KB
/
molecule.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Molecular chemical entity representation and routines to interface with cheminformatics toolkits
.. todo::
* Our main philosophy here is to keep the object contents of topology objects easily serializable/deserializable
* Have ``Molecule`` raise an exception if loading/creating molecules with unspecified stereochemistry?
* Create ``FrozenMolecule`` to represent immutable molecule
* Make ``Atom`` and ``Bond`` an inner class of Molecule?
* Add ``Molecule.from_smarts()`` or ``.from_tagged_smiles()`` to allow a tagged SMARTS string
(where tags are zero-indexed atom indices) to be used to create a molecule with the given atom numbering.
* How can we make the ``Molecule`` API more useful to codes like perses that modify molecules on the fly?
* Use `attrs <http://www.attrs.org/>`_ for convenient class initialization?
* JSON/BSON representations of objects?
* Generalize Molecule infrastructure to provide "plug-in" support for cheminformatics toolkits
* Do we need a way to write a bunch of molecules to a file, or serialize a set of molecules to a file?
We currently don't have a way to do that through the ``Molecule`` API, even though there is a way to
read multiple molecules via ``Molecules.from_file()``.
* Should we allow the removal of atoms too?
* Should invalidation of cached properties be handled via something like a tracked list?
* Refactor toolkit encapsulation to generalize and provide only a few major toolkit methods and toolkit objects
that can be queried for features
* Speed up overall import time by putting non-global imports only where they are needed
"""
import json
import operator
import pathlib
import warnings
from collections import UserDict
from copy import deepcopy
from functools import cmp_to_key
from typing import (
IO,
TYPE_CHECKING,
Any,
DefaultDict,
Generator,
Iterable,
Literal,
Optional,
Sequence,
TextIO,
TypeVar,
Union,
overload,
)
import numpy as np
from openff.units.elements import MASSES, SYMBOLS
from openff.utilities.exceptions import MissingOptionalDependencyError
from typing_extensions import TypeAlias
from openff.toolkit import Quantity, unit
from openff.toolkit.utils.constants import DEFAULT_AROMATICITY_MODEL
from openff.toolkit.utils.exceptions import (
AtomMappingWarning,
BondExistsError,
HierarchyIteratorNameConflictError,
HierarchySchemeNotFoundException,
HierarchySchemeWithIteratorNameAlreadyRegisteredException,
IncompatibleShapeError,
IncompatibleTypeError,
IncompatibleUnitError,
InvalidAtomMetadataError,
InvalidBondOrderError,
InvalidConformerError,
InvalidQCInputError,
MissingCMILESError,
MissingConformersError,
MissingPartialChargesError,
MoleculeParseError,
MultipleMoleculesInPDBError,
RemapIndexError,
SmilesParsingError,
UnsupportedFileTypeError,
)
from openff.toolkit.utils.serialization import Serializable
from openff.toolkit.utils.toolkits import (
GLOBAL_TOOLKIT_REGISTRY,
InvalidToolkitRegistryError,
OpenEyeToolkitWrapper,
RDKitToolkitWrapper,
ToolkitRegistry,
ToolkitWrapper,
UndefinedStereochemistryError,
)
from openff.toolkit.utils.utils import get_data_file_path, requires_package
if TYPE_CHECKING:
import IPython.display
import networkx as nx
import nglview
from rdkit.Chem import Mol as RDMol
from openff.toolkit.topology._mm_molecule import _SimpleAtom, _SimpleMolecule
# TODO: Can we have the `ALLOWED_*_MODELS` list automatically appear in the docstrings below?
# TODO: Should `ALLOWED_*_MODELS` be objects instead of strings?
# TODO: Allow all OpenEye aromaticity models to be used with OpenEye names?
# Only support OEAroModel_MDL in RDKit version?
# TODO: These aliases are duplicated in a few places, might make sense to consolidate them
# into a single location, but that'd weirdly nudge them towards first-class existence
TKR: TypeAlias = Union[ToolkitRegistry, ToolkitWrapper]
MoleculeLike: TypeAlias = Union["Molecule", "FrozenMolecule", "_SimpleMolecule"]
FM = TypeVar("FM", bound="FrozenMolecule")
P = TypeVar("P", bound="Particle")
A = TypeVar("A", bound="Atom")
B = TypeVar("B", bound="Bond")
class MoleculeDeprecationWarning(UserWarning):
"""Warning for deprecated portions of the Molecule API."""
class Particle(Serializable):
"""
Base class for all particles in a molecule.
A particle object could be an ``Atom`` or similar.
.. warning :: This API is experimental and subject to change.
"""
_molecule: "FrozenMolecule"
@property
def molecule(self) -> "FrozenMolecule":
r"""
The ``Molecule`` this particle is part of.
.. todo::
* Should we have a single unique ``Molecule`` for each molecule
type in the system, or if we have multiple copies of the same
molecule, should we have multiple ``Molecule``\ s?
"""
return self._molecule
@molecule.setter
def molecule(self, molecule: "FrozenMolecule"):
"""
Set the particle's molecule pointer. Note that this will only work if the particle currently
doesn't have a molecule
"""
assert (
self._molecule is None
), f"{type(self).__name__} already has an associated molecule"
self._molecule = molecule
@property
def molecule_particle_index(self) -> int:
"""
Returns the index of this particle in its molecule
"""
return self._molecule.atoms.index(self)
@property
def name(self) -> str:
"""
The name of the particle
"""
return self._name
@name.setter
def name(self, name: str):
"""
Set the name of the particle
"""
self._name = name
def to_dict(self) -> dict:
"""Convert to dictionary representation."""
# Implement abstract method Serializable.to_dict()
raise NotImplementedError() # TODO
@classmethod
def from_dict(cls: type[P], d: dict) -> P:
"""Static constructor from dictionary representation."""
# Implement abstract method Serializable.to_dict()
raise NotImplementedError() # TODO
class AtomMetadataDict(UserDict):
def __init__(self, *args, **kwargs):
self.data = {}
self.update(dict(*args, **kwargs))
def __setitem__(self, key, value):
if not isinstance(key, str):
raise InvalidAtomMetadataError(
f"Attempted to set atom metadata with a non-string key. (key: {key}"
)
if not isinstance(value, (str, int)):
raise InvalidAtomMetadataError(
f"Attempted to set atom metadata with a non-string or integer "
f"value. (value: {value})"
)
super().__setitem__(key, value)
class Atom(Particle):
"""
A chemical atom.
.. todo::
* Do we want to support the addition of arbitrary additional properties,
such as floating point quantities (e.g. ``charge``), integral
quantities (such as ``id`` or ``serial`` index in a PDB file),
or string labels (such as Lennard-Jones types)?
.. warning :: This API is experimental and subject to change.
"""
def __init__(
self,
atomic_number: int,
formal_charge: Union[int, Quantity],
is_aromatic: bool,
name: Optional[str] = None,
molecule=None,
stereochemistry: Optional[str] = None,
metadata: Optional[dict[str, Union[int, str]]] = None,
):
"""
Create an immutable Atom object.
Object is serializable and immutable.
Parameters
----------
atomic_number
Atomic number of the atom. Must be non-negative and non-zero.
formal_charge
Formal charge of the atom
is_aromatic
If True, atom is aromatic; if False, not aromatic
stereochemistry
Either 'R' or 'S' for specified stereochemistry, or None for ambiguous stereochemistry
name
An optional name to be associated with the atom
metadata
An optional dictionary where keys are strings and values are strings or ints. This is intended
to record atom-level information used to inform hierarchy definition and iteration, such as
grouping atom by residue and chain.
Examples
--------
Create a non-aromatic carbon atom
>>> atom = Atom(6, 0, False)
Create a chiral carbon atom
>>> atom = Atom(6, 0, False, stereochemistry='R', name='CT')
"""
if not isinstance(atomic_number, int):
raise ValueError(f"atomic number must be int, found {type(atomic_number)}")
if atomic_number <= 0:
raise ValueError(f"atomic number must be positive, given {atomic_number}.")
self._atomic_number = atomic_number
# Use the setter here, since it will handle either ints or Quantities
# and it is designed to quickly process ints
self.formal_charge = formal_charge
self._is_aromatic = is_aromatic
self._stereochemistry = stereochemistry
if name is None:
name = ""
self._name = name
self._molecule = molecule
# From Jeff: I'm going to assume that this is implicit in the parent Molecule's ordering of atoms
# self._molecule_atom_index = molecule_atom_index
self._bonds: list["Bond"] = list()
if metadata is None:
self._metadata = AtomMetadataDict()
else:
self._metadata = AtomMetadataDict(metadata)
# TODO: We can probably avoid an explicit call and determine this dynamically
# from self._molecule (maybe caching the result) to get rid of some bookkeeping.
# TODO: Should stereochemistry be reset/cleared/recomputed upon addition of a bond?
def add_bond(self, bond: "Bond"):
"""Adds a bond that this atom is involved in
.. todo :: Is this how we want to keep records?
Parameters
----------
bond
A bond involving this atom
"""
self._bonds.append(bond)
def to_dict(self) -> dict[str, Union[None, str, int, bool, dict[Any, Any]]]:
"""Return a dict representation of the atom."""
# TODO: Should this be implicit in the atom ordering when saved?
# atom_dict['molecule_atom_index'] = self._molecule_atom_index
return {
"atomic_number": self._atomic_number,
"formal_charge": self._formal_charge.m, # Trust that the unit is e
"is_aromatic": self._is_aromatic,
"stereochemistry": self._stereochemistry,
"name": self._name,
"metadata": dict(self._metadata),
}
@classmethod
def from_dict(cls: type[A], atom_dict: dict) -> A:
"""Create an Atom from a dict representation."""
return cls(**atom_dict)
@property
def metadata(self):
"""
The atom's metadata dictionary
"""
return self._metadata
@property
def formal_charge(self):
"""
The atom's formal charge
"""
return self._formal_charge
@formal_charge.setter
def formal_charge(self, other):
"""
Set the atom's formal charge. Accepts either ints or unit-wrapped ints with units of charge.
"""
if isinstance(other, int):
self._formal_charge = Quantity(other, unit.elementary_charge)
elif isinstance(other, Quantity):
# Faster to check equality than convert, so short-circuit
if other.units is unit.elementary_charge:
self.formal_charge = other
elif other.units in unit.elementary_charge.compatible_units():
self._formal_charge = other
else:
raise IncompatibleUnitError(
f"Cannot set formal charge with a quantity with units {other.units}"
)
elif hasattr(other, "unit"):
from openmm import unit as openmm_unit
if not isinstance(other, openmm_unit.Quantity):
raise IncompatibleUnitError(
"Unsupported type passed to formal_charge setter. "
f"Found object of type {type(other)}."
)
from openff.units.openmm import from_openmm
converted = from_openmm(other)
if converted.units in unit.elementary_charge.compatible_units():
self._formal_charge = converted
else:
raise IncompatibleUnitError(
f"Cannot set formal charge with a quantity with units {converted.units}"
)
else:
raise ValueError
@property
def partial_charge(self):
"""
The partial charge of the atom, if any.
Returns
-------
unit-wrapped float with dimension of atomic charge, or None if no charge has been specified
"""
if self._molecule._partial_charges is None:
return None
else:
index = self.molecule_atom_index
return self._molecule._partial_charges[index]
@partial_charge.setter
def partial_charge(self, charge):
if self.molecule.partial_charges is None:
raise MissingPartialChargesError(
"Cannot set individual atom's partial charge if it is in a molecule with no partial charges. "
"Instead, use the `Molecule.partial_charges` setter. If this behavior is important to you, "
"please raise an issue describing your use case."
)
if not isinstance(charge, (Quantity, float)):
raise ValueError(
"Cannot set partial charge with an object that is not a openff.unit.Quantity or float. "
f"Found object of type {type(charge)}."
)
if isinstance(charge, float):
charge = Quantity(charge, unit.elementary_charge)
if not isinstance(charge.m, float):
raise ValueError(
"Cannot set partial charge with an object that is not a wrapped int or float. "
f"Found unit-wrapped {type(charge.m)}."
)
molecule_partial_charges = self.molecule.partial_charges
molecule_partial_charges[self.molecule_atom_index] = charge
self.molecule.partial_charges = molecule_partial_charges
@property
def is_aromatic(self):
"""
The atom's is_aromatic flag
"""
return self._is_aromatic
@property
def stereochemistry(self):
"""
The atom's stereochemistry (if defined, otherwise None)
"""
return self._stereochemistry
@stereochemistry.setter
def stereochemistry(self, value: Literal["CW", "CCW", None]):
"""Set the atoms stereochemistry
Parameters
----------
value
The stereochemistry around this atom, allowed values are "CW", "CCW", or None,
"""
# if (value != 'CW') and (value != 'CCW') and not(value is None):
# raise Exception(
# "Atom stereochemistry setter expected 'CW', 'CCW', or None. ""
# "Received {} (type {})".format(value, type(value))"
# )
self._stereochemistry = value
@property
def atomic_number(self) -> int:
"""
The integer atomic number of the atom.
"""
return self._atomic_number
@property
def symbol(self) -> str:
"""
Return the symbol implied by the atomic number of this atom
"""
return SYMBOLS[self.atomic_number]
@property
def mass(self) -> Quantity:
"""
The standard atomic weight (abundance-weighted isotopic mass) of the atomic site.
The mass is reported in units of Dalton.
"""
# This is assumed elsewhere in the codebase to be in units of Dalton, which is what is
# reported by MASSES as of openff-units v0.1.5. There may be performance implications if
# other functions need to verify or convert units.
# https://github.com/openforcefield/openff-toolkit/pull/1182#discussion_r802078273
return MASSES[self.atomic_number]
@property
def name(self):
"""
The name of this atom, if any
"""
return self._name
@name.setter
def name(self, other: str):
"""
Parameters
----------
other
The new name for this atom
"""
if type(other) is not str:
raise ValueError(
f"In setting atom name. Expected str, received {other} (type {type(other)})."
)
self._name = other
@property
def bonds(self):
"""
The list of ``Bond`` objects this atom is involved in.
"""
return self._bonds
@property
def bonded_atoms(self) -> Generator["Atom", None, None]:
"""
The list of ``Atom`` objects this atom is involved in bonds with
"""
for bond in self._bonds:
for atom in bond.atoms:
if atom is not self:
# TODO: This seems dangerous. Ask John for a better way
yield atom
def is_bonded_to(self, atom2):
"""
Determine whether this atom is bound to another atom
Parameters
----------
atom2
a different atom in the same molecule
Returns
-------
bool
Whether this atom is bound to atom2
"""
# TODO: Sanity check (check for same molecule?)
assert self != atom2
for bond in self._bonds:
for bonded_atom in bond.atoms:
if atom2 == bonded_atom:
return True
return False
def is_in_ring(
self,
toolkit_registry: ToolkitRegistry = GLOBAL_TOOLKIT_REGISTRY,
) -> bool:
"""
Return whether or not this atom is in a ring(s) (of any size)
This Atom is expected to be attached to a molecule (`Atom.molecule`).
Parameters
----------
toolkit_registry
:class:`ToolkitRegistry` to use to enumerate the tautomers.
"""
_is_in_ring = toolkit_registry.call("atom_is_in_ring", self)
return _is_in_ring
@property
def molecule_atom_index(self) -> int:
"""
The index of this Atom within the the list of atoms in the parent ``Molecule``.
"""
if self._molecule is None:
raise ValueError("This Atom does not belong to a Molecule object")
if "_molecule_atom_index" in self.__dict__:
return self._molecule_atom_index # type: ignore[has-type]
self._molecule_atom_index = self._molecule.atoms.index(self)
return self._molecule_atom_index
def __repr__(self):
# TODO: Also include which molecule this atom belongs to?
return f"Atom(name={self._name}, atomic number={self._atomic_number})"
def __str__(self):
# TODO: Also include which molecule this atom belongs to?
return "<Atom name='{}' atomic number='{}'>".format(
self._name, self._atomic_number
)
# =============================================================================================
# Bond Stereochemistry
# =============================================================================================
# class BondStereochemistry(Serializable):
# """
# Bond stereochemistry representation
# """
# def __init__(self, stereo_type, neighbor1, neighbor2):
# """
#
# Parameters
# ----------
# stereo_type
# neighbor1
# neighbor2
# """
# assert isinstance(neighbor1, Atom)
# assert isinstance(neighbor2, Atom)
# # Use stereo_type @setter to check stereo type is a permitted value
# self.stereo_type = stereo_type
# self._neighbor1 = neighbor1
# self._neighbor2 = neighbor2
# def to_dict(self):
# bs_dict = dict()
# bs_dict['stereo_type'] = self._stereo_type
# bs_dict['neighbor1_index'] = self._neighbor1.molecule_atom_index
# bs_dict['neighbor2_index'] = self._neighbor2.molecule_atom_index
# return bs_dict
# classmethod
# def from_dict(cls, molecule, bs_dict):
# neighbor1 = molecule.atoms[bs_dict['neighbor1_index']]
# neighbor2 = molecule.atoms[bs_dict['neighbor2_index']]
# return cls.__init__(bs_dict['stereo_type'], neighbor1, neighbor2)
# @property
# def stereo_type(self):
# return self._stereo_type
# @stereo_type.setter
# def stereo_type(self, value):
# assert (value == 'CIS') or (value == 'TRANS') or (value is None)
# self._stereo_type = value
# @property
# def neighbor1(self):
# return self._neighbor1
# @property
# def neighbor2(self):
# return self._neighbor2
# @property
# def neighbors(self):
# return (self._neighbor1, self._neighbor2)
class Bond(Serializable):
"""
Chemical bond representation.
.. warning :: This API is experimental and subject to change.
.. todo :: Allow bonds to have associated properties.
Attributes
----------
atom1, atom2
Atoms involved in the bond
bond_order
The (integer) bond order of this bond.
is_aromatic
Whether or not this bond is aromatic.
fractional_bond_order
The fractional bond order, or partial bond order of this bond.
stereochemstry
A string representing this stereochemistry of this bond.
.. warning :: This API is experimental and subject to change.
"""
def __init__(
self,
atom1,
atom2,
bond_order,
is_aromatic,
fractional_bond_order=None,
stereochemistry=None,
):
"""
Create a new chemical bond.
"""
assert type(atom1) is Atom
assert type(atom2) is Atom
assert atom1.molecule is atom2.molecule
assert isinstance(atom1.molecule, FrozenMolecule)
self._molecule = atom1.molecule
self._atom1 = atom1
self._atom2 = atom2
atom1.add_bond(self)
atom2.add_bond(self)
# TODO: Check bondtype and fractional_bond_order are valid?
# TODO: Dative bonds
self._fractional_bond_order = fractional_bond_order
self._bond_order = bond_order
self._is_aromatic = is_aromatic
self._stereochemistry = stereochemistry
def to_dict(self) -> dict[str, Union[int, bool, str, float]]:
"""
Return a dict representation of the bond.
"""
return {
"atom1": self.atom1.molecule_atom_index,
"atom2": self.atom2.molecule_atom_index,
"bond_order": self._bond_order,
"is_aromatic": self._is_aromatic,
"stereochemistry": self._stereochemistry,
"fractional_bond_order": self._fractional_bond_order,
}
@classmethod
def from_dict(cls: type[B], molecule: FM, d: dict) -> B: # type: ignore[override]
"""Create a Bond from a dict representation."""
# TODO: This is not used anywhere (`Molecule._initialize_bonds_from_dict()` just calls grabs
# the two atoms and calls `Molecule._add_bond`). Remove or change that?
# TODO: There is no point in feeding in a `molecule` argument since `Bond.__init__` already
# requires (and checks) that the two atoms are part of the same molecule
d["atom1"] = molecule.atoms[d["atom1"]]
d["atom2"] = molecule.atoms[d["atom2"]]
return cls(
atom1=d["atom1"],
atom2=d["atom2"],
bond_order=d["bond_order"],
is_aromatic=d["is_aromatic"],
stereochemistry=d["stereochemistry"],
fractional_bond_order=d["fractional_bond_order"],
)
@property
def atom1(self):
return self._atom1
@property
def atom2(self):
return self._atom2
@property
def atom1_index(self) -> int:
return self.molecule.atoms.index(self._atom1)
@property
def atom2_index(self) -> int:
return self.molecule.atoms.index(self._atom2)
@property
def atoms(self):
return (self._atom1, self._atom2)
@property
def bond_order(self):
return self._bond_order
@bond_order.setter
def bond_order(self, value):
if isinstance(value, int):
self._bond_order = value
else:
raise InvalidBondOrderError(
"Only integer bond orders may be passed to `Bond.bond_order` setter. "
"For aromatic bonds, instead kekulize the input structure and use "
"the resulting integer bond orders. If performing partial bond "
"order-based parameter interpolation, consider using "
"`Bond.fractional_bond_order`."
)
@property
def fractional_bond_order(self):
return self._fractional_bond_order
@fractional_bond_order.setter
def fractional_bond_order(self, value):
self._fractional_bond_order = value
@property
def stereochemistry(self):
return self._stereochemistry
@property
def is_aromatic(self) -> bool:
return self._is_aromatic
@property
def molecule(self) -> "FrozenMolecule":
return self._molecule
@molecule.setter
def molecule(self, value):
"""
Sets the Bond's parent molecule. Can not be changed after assignment
"""
# TODO: This is an impossible state (the constructor requires that atom1 and atom2
# are in a molecule, the same molecule, and sets that as self._molecule).
# Should we remove this?
assert (
self._molecule is None
), "Bond.molecule is already set and can only be set once"
self._molecule = value
@property
def molecule_bond_index(self) -> int:
"""
The index of this Bond within the the list of bonds in ``Molecules``.
"""
if self._molecule is None:
# TODO: This is unreachable; see `Bond.molecule` setter
raise ValueError("This Atom does not belong to a Molecule object")
return self._molecule.bonds.index(self)
def is_in_ring(
self,
toolkit_registry: ToolkitRegistry = GLOBAL_TOOLKIT_REGISTRY,
) -> bool:
"""
Return whether or not this bond is in a ring(s) (of any size)
This Bond is expected to be attached to a molecule (`Bond.molecule`).
Note: Bonds containing atoms that are only in separate rings, i.e. the central bond in a biphenyl,
are not considered to be bonded by this criteria.
Parameters
----------
toolkit_registry
:class:`ToolkitRegistry` to use to enumerate the tautomers.
Returns
-------
is_in_ring
Whether or not this bond is in a ring.
"""
_is_in_ring = toolkit_registry.call("bond_is_in_ring", self)
return _is_in_ring
def __repr__(self):
return f"Bond(atom1 index={self.atom1_index}, atom2 index={self.atom2_index})"
def __str__(self):
return (
f"<Bond atom1 index='{self.atom1_index}', atom2 index='{self.atom2_index}'>"
)
# TODO: How do we automatically trigger invalidation of cached properties if an ``Atom`` or ``Bond`` is modified,
# rather than added/deleted via the API? The simplest resolution is simply to make them immutable.
class FrozenMolecule(Serializable):
"""
Immutable chemical representation of a molecule, such as a small molecule or biopolymer.
.. todo :: What other API calls would be useful for supporting biopolymers
as small molecules? Perhaps iterating over chains and residues?
Examples
--------
Create a molecule from a sdf file
>>> from openff.toolkit.utils import get_data_file_path
>>> sdf_filepath = get_data_file_path('molecules/ethanol.sdf')
>>> molecule = FrozenMolecule.from_file(sdf_filepath)
Convert to OpenEye OEMol object
>>> oemol = molecule.to_openeye()
Create a molecule from an OpenEye molecule
>>> molecule = FrozenMolecule.from_openeye(oemol)
Convert to RDKit Mol object
>>> rdmol = molecule.to_rdkit()
Create a molecule from an RDKit molecule
>>> molecule = FrozenMolecule.from_rdkit(rdmol)
Create a molecule from IUPAC name (requires the OpenEye toolkit)
>>> molecule = FrozenMolecule.from_iupac('imatinib')
Create a molecule from SMILES
>>> molecule = FrozenMolecule.from_smiles('Cc1ccccc1')
.. warning :: This API is experimental and subject to change.
"""
_partial_charges: Optional[Quantity]
_conformers: Optional[list[Quantity]]
_properties: dict
_hierarchy_schemes: dict
def __init__(
self,
other=None,
file_format: Optional[str] = None,
toolkit_registry: TKR = GLOBAL_TOOLKIT_REGISTRY,
allow_undefined_stereo: bool = False,
):
r"""
Create a new FrozenMolecule object
.. todo ::
* If a filename or file-like object is specified but the file
contains more than one molecule, what is the proper behavior?
Read just the first molecule, or raise an exception if more
than one molecule is found?
* Should we also support SMILES strings or IUPAC names for
``other``\ ?
Parameters
----------
other
If specified, attempt to construct a copy of the molecule from
the specified object. This can be any one of the following:
* a :class:`Molecule` object
* a file that can be used to construct a :class:`Molecule` object
* an ``openeye.oechem.OEMol``
* an ``rdkit.Chem.rdchem.Mol``
* a serialized :class:`Molecule` object
file_format
If providing a file-like object, you must specify the format
of the data. If providing a file, the file format will attempt
to be guessed from the suffix.
toolkit_registry
A registry to use for I/O operations
allow_undefined_stereo
If loaded from a file and ``False``, raises an exception if
undefined stereochemistry is detected during the molecule's
construction.
Examples
--------
Create an empty molecule:
>>> empty_molecule = FrozenMolecule()
Create a molecule from a file that can be used to construct a molecule,
using either a filename or file-like object:
>>> from openff.toolkit.utils import get_data_file_path
>>> sdf_filepath = get_data_file_path('molecules/ethanol.sdf')
>>> molecule = FrozenMolecule(sdf_filepath)
>>> molecule = FrozenMolecule(open(sdf_filepath, 'r'), file_format='sdf')
>>> import gzip
>>> mol2_gz_filepath = get_data_file_path('molecules/toluene.mol2.gz')
>>> molecule = FrozenMolecule(gzip.GzipFile(mol2_gz_filepath, 'r'), file_format='mol2')
Create a molecule from another molecule:
>>> molecule_copy = FrozenMolecule(molecule)
Convert to OpenEye OEMol object
>>> oemol = molecule.to_openeye()
Create a molecule from an OpenEye molecule:
>>> molecule = FrozenMolecule(oemol)
Convert to RDKit Mol object
>>> rdmol = molecule.to_rdkit()
Create a molecule from an RDKit molecule:
>>> molecule = FrozenMolecule(rdmol)
Convert the molecule into a dictionary and back again:
>>> serialized_molecule = molecule.to_dict()
>>> molecule_copy = FrozenMolecule(serialized_molecule)
"""
self._cached_smiles: dict[str, str] = dict()
self._ordered_connection_table_hash: Optional[int] = None
# Figure out if toolkit_registry is a whole registry, or just a single wrapper
if isinstance(toolkit_registry, ToolkitRegistry):
pass
elif isinstance(toolkit_registry, ToolkitWrapper):
toolkit = toolkit_registry
toolkit_registry = ToolkitRegistry(toolkit_precedence=[])