amchi 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- amchi/__init__.py +30 -0
- amchi/_amchi.py +259 -0
- amchi/_candidates.py +208 -0
- amchi/_canon.py +458 -0
- amchi/_connect.py +105 -0
- amchi/_element.py +106 -0
- amchi/_graph.py +151 -0
- amchi/_layers.py +237 -0
- amchi/_parity.py +169 -0
- amchi/_resonance.py +178 -0
- amchi/_types.py +161 -0
- amchi-0.0.1.dist-info/METADATA +41 -0
- amchi-0.0.1.dist-info/RECORD +15 -0
- amchi-0.0.1.dist-info/WHEEL +4 -0
- amchi-0.0.1.dist-info/licenses/LICENSE +21 -0
amchi/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""amchi."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.0.1"
|
|
4
|
+
|
|
5
|
+
from ._amchi import from_geometry, from_ts_geometries, string
|
|
6
|
+
from ._candidates import add_bond_candidate, candidates, remove_candidate
|
|
7
|
+
from ._connect import connectivity, ts_connectivity
|
|
8
|
+
from ._element import AmchiError, UnsupportedElementError
|
|
9
|
+
from ._parity import ParityMargins, parity_margins
|
|
10
|
+
from ._types import Bond, Candidates, Connectivity, GeometryLike, IllDefinedParityError
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"AmchiError",
|
|
14
|
+
"Bond",
|
|
15
|
+
"Candidates",
|
|
16
|
+
"Connectivity",
|
|
17
|
+
"GeometryLike",
|
|
18
|
+
"IllDefinedParityError",
|
|
19
|
+
"ParityMargins",
|
|
20
|
+
"UnsupportedElementError",
|
|
21
|
+
"add_bond_candidate",
|
|
22
|
+
"candidates",
|
|
23
|
+
"connectivity",
|
|
24
|
+
"from_geometry",
|
|
25
|
+
"from_ts_geometries",
|
|
26
|
+
"parity_margins",
|
|
27
|
+
"remove_candidate",
|
|
28
|
+
"string",
|
|
29
|
+
"ts_connectivity",
|
|
30
|
+
]
|
amchi/_amchi.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""The public pipeline: the AMChI string of a species or a TS from its three inputs.
|
|
2
|
+
|
|
3
|
+
The components are written one by one and joined as the old AutoMol joins them
|
|
4
|
+
(`amchi.base.sorted_join`): sorted by the old sort key, highest first, with repeated
|
|
5
|
+
layers written once behind a multiplier (`2*`).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import itertools
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from ._candidates import candidates as _candidates
|
|
15
|
+
from ._canon import CanonicalForm, canonical_forms
|
|
16
|
+
from ._connect import connectivity as _connectivity
|
|
17
|
+
from ._connect import ts_connectivity as _ts_connectivity
|
|
18
|
+
from ._element import valence
|
|
19
|
+
from ._graph import MolGraph, explicit_graph, implicit_graph
|
|
20
|
+
from ._layers import component_layers, component_string
|
|
21
|
+
from ._parity import stereo_graph
|
|
22
|
+
from ._types import Candidates, Connectivity, GeometryLike
|
|
23
|
+
|
|
24
|
+
_LETTERS = ("c", "h", "b", "t", "m", "s", "k", "f", "r")
|
|
25
|
+
"""The layers after the formula, in the order they are written."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def string(
|
|
29
|
+
geometry: GeometryLike,
|
|
30
|
+
connectivity: Connectivity,
|
|
31
|
+
candidates: Candidates,
|
|
32
|
+
*,
|
|
33
|
+
stereo: bool = True,
|
|
34
|
+
) -> str:
|
|
35
|
+
"""The AMChI string of a species or a transition state (TS).
|
|
36
|
+
|
|
37
|
+
A TS has breaking or forming bonds in its connectivity, and its string has the
|
|
38
|
+
`k` (breaking) and `f` (forming) layers, as read in its canonical direction, and
|
|
39
|
+
an `r` layer if the given direction is the reverse of that (`r1`) or not (`r0`).
|
|
40
|
+
With `stereo=False`, the candidates are ignored, and the string has no `b`, `t`,
|
|
41
|
+
`m` or `s` layer.
|
|
42
|
+
|
|
43
|
+
Raises:
|
|
44
|
+
UnsupportedElementError: A symbol has no element data.
|
|
45
|
+
IllDefinedParityError: A stereocenter's parity is exactly zero.
|
|
46
|
+
ValueError: The inputs don't fit each other: the coordinates aren't N x 3,
|
|
47
|
+
a bond names a missing atom, or a candidate's neighbors aren't the
|
|
48
|
+
neighbors of its atom or bond (for a TS: aren't among them, over the
|
|
49
|
+
breaking and forming bonds too).
|
|
50
|
+
|
|
51
|
+
Examples:
|
|
52
|
+
>>> import amchi
|
|
53
|
+
>>> from types import SimpleNamespace
|
|
54
|
+
>>> water = SimpleNamespace(
|
|
55
|
+
... symbols=["O", "H", "H"],
|
|
56
|
+
... coordinates=[[0, 0, 0], [0.96, 0, 0], [-0.24, 0.93, 0]],
|
|
57
|
+
... )
|
|
58
|
+
>>> connectivity = amchi.Connectivity(bonds=[(0, 1), (0, 2)])
|
|
59
|
+
>>> amchi.string(water, connectivity, amchi.Candidates())
|
|
60
|
+
'AMChI=2S/H2O/h1H2'
|
|
61
|
+
"""
|
|
62
|
+
symbols = list(geometry.symbols)
|
|
63
|
+
if not stereo:
|
|
64
|
+
candidates = Candidates()
|
|
65
|
+
_check(symbols, geometry, connectivity, candidates)
|
|
66
|
+
graph = implicit_graph(explicit_graph(symbols, connectivity))
|
|
67
|
+
graph = stereo_graph(graph, geometry, candidates)
|
|
68
|
+
forms = canonical_forms(graph)
|
|
69
|
+
return _join(graph, forms)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def from_geometry(geometry: GeometryLike, *, stereo: bool = True) -> str:
|
|
73
|
+
"""The AMChI string of a species, with its connectivity and candidates derived.
|
|
74
|
+
|
|
75
|
+
Raises the errors of `string`.
|
|
76
|
+
|
|
77
|
+
Examples:
|
|
78
|
+
>>> import amchi
|
|
79
|
+
>>> from types import SimpleNamespace
|
|
80
|
+
>>> # CHFClBr and its mirror image
|
|
81
|
+
>>> chfclbr = SimpleNamespace(
|
|
82
|
+
... symbols=["C", "H", "F", "Cl", "Br"],
|
|
83
|
+
... coordinates=[
|
|
84
|
+
... [0, 0, 0], [0, 0, 1.09], [1.31, 0, -0.46],
|
|
85
|
+
... [-0.83, 1.44, -0.59], [-0.91, -1.58, -0.65],
|
|
86
|
+
... ],
|
|
87
|
+
... )
|
|
88
|
+
>>> amchi.from_geometry(chfclbr)
|
|
89
|
+
'AMChI=2S/CHBrClF/c2-1(3)4/h1H/t1-/m1/s1'
|
|
90
|
+
>>> chfclbr.coordinates = [[-x, y, z] for x, y, z in chfclbr.coordinates]
|
|
91
|
+
>>> amchi.from_geometry(chfclbr)
|
|
92
|
+
'AMChI=2S/CHBrClF/c2-1(3)4/h1H/t1-/m0/s1'
|
|
93
|
+
>>> amchi.from_geometry(chfclbr, stereo=False)
|
|
94
|
+
'AMChI=2S/CHBrClF/c2-1(3)4/h1H'
|
|
95
|
+
"""
|
|
96
|
+
connectivity = _connectivity(geometry)
|
|
97
|
+
if not stereo:
|
|
98
|
+
return string(geometry, connectivity, Candidates(), stereo=False)
|
|
99
|
+
candidates = _candidates(geometry.symbols, connectivity)
|
|
100
|
+
return string(geometry, connectivity, candidates)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def from_ts_geometries(
|
|
104
|
+
geometry: GeometryLike,
|
|
105
|
+
reactant_geometry: GeometryLike,
|
|
106
|
+
product_geometry: GeometryLike,
|
|
107
|
+
*,
|
|
108
|
+
stereo: bool = True,
|
|
109
|
+
) -> str:
|
|
110
|
+
"""The AMChI string of a TS, with its connectivity and candidates derived.
|
|
111
|
+
|
|
112
|
+
The three geometries are in the same atom order: the TS (for the parities) and
|
|
113
|
+
its reactant side and product side (for the bonds and the candidates). With
|
|
114
|
+
`stereo=False` the string has no `b`, `t`, `m` or `s` layer.
|
|
115
|
+
|
|
116
|
+
Raises the errors of `string`, and `ValueError` if the atoms differ.
|
|
117
|
+
|
|
118
|
+
Examples:
|
|
119
|
+
>>> import amchi
|
|
120
|
+
>>> from types import SimpleNamespace
|
|
121
|
+
>>> symbols = ["C", "H", "H", "H", "H", "O", "H"]
|
|
122
|
+
>>> ring = [[0, 0, 0.3], [1, 0, 0.3], [-0.5, 0.87, 0.3], [-0.5, -0.87, 0.3]]
|
|
123
|
+
>>> # CH3 + H2O: H4 moves from O5 to C0
|
|
124
|
+
>>> ts = SimpleNamespace(
|
|
125
|
+
... symbols=symbols,
|
|
126
|
+
... coordinates=[[0, 0, 0], *ring[1:], [0, 0, -1.3], [0, 0, -2.5],
|
|
127
|
+
... [0.9, 0, -2.8]],
|
|
128
|
+
... )
|
|
129
|
+
>>> reactant = SimpleNamespace(
|
|
130
|
+
... symbols=symbols,
|
|
131
|
+
... coordinates=[[0, 0, 0], *ring[1:], [-0.5, 0.5, -3.2], [0, 0, -2.5],
|
|
132
|
+
... [0.9, 0, -2.8]],
|
|
133
|
+
... )
|
|
134
|
+
>>> product = SimpleNamespace(
|
|
135
|
+
... symbols=symbols,
|
|
136
|
+
... coordinates=[[0, 0, 0], *ring[1:], [0, 0, -1.09], [0, 0, -3.2],
|
|
137
|
+
... [0.9, 0, -3.5]],
|
|
138
|
+
... )
|
|
139
|
+
>>> amchi.from_ts_geometries(ts, reactant, product)
|
|
140
|
+
'AMChI=2S/CH5O/c1-3-2/h2H,1H3/k3-2/f3-1/r0'
|
|
141
|
+
>>> amchi.from_ts_geometries(ts, product, reactant)
|
|
142
|
+
'AMChI=2S/CH5O/c1-3-2/h2H,1H3/k3-2/f3-1/r1'
|
|
143
|
+
"""
|
|
144
|
+
connectivity = _ts_connectivity(reactant_geometry, product_geometry)
|
|
145
|
+
if not stereo:
|
|
146
|
+
return string(geometry, connectivity, Candidates(), stereo=False)
|
|
147
|
+
candidates = _candidates(geometry.symbols, connectivity)
|
|
148
|
+
return string(geometry, connectivity, candidates)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _check(
|
|
152
|
+
symbols: Sequence[str],
|
|
153
|
+
geometry: GeometryLike,
|
|
154
|
+
connectivity: Connectivity,
|
|
155
|
+
candidates: Candidates,
|
|
156
|
+
) -> None:
|
|
157
|
+
"""Check the three inputs against each other."""
|
|
158
|
+
for symbol in set(symbols):
|
|
159
|
+
valence(symbol) # raises UnsupportedElementError
|
|
160
|
+
shape = np.shape(geometry.coordinates)
|
|
161
|
+
if shape != (len(symbols), 3):
|
|
162
|
+
msg = f"Expected {len(symbols)} x 3 coordinates, got {shape}"
|
|
163
|
+
raise ValueError(msg)
|
|
164
|
+
# A species' candidate lists exactly its atom's or bond's neighbors. A TS's
|
|
165
|
+
# lists those of one side or of several, so only some of all its neighbors.
|
|
166
|
+
is_ts = bool(connectivity.breaking or connectivity.forming)
|
|
167
|
+
fits = set.issubset if is_ts else set.__eq__
|
|
168
|
+
neighbors: list[set[int]] = [set() for _ in symbols]
|
|
169
|
+
for i, j in (*connectivity.bonds, *connectivity.breaking, *connectivity.forming):
|
|
170
|
+
if j >= len(symbols):
|
|
171
|
+
msg = f"A bond names a missing atom: {(i, j)}"
|
|
172
|
+
raise ValueError(msg)
|
|
173
|
+
neighbors[i].add(j)
|
|
174
|
+
neighbors[j].add(i)
|
|
175
|
+
for atoms in (candidates.atoms, candidates.reverse_atoms):
|
|
176
|
+
for atom, atom_neighbors in atoms.items():
|
|
177
|
+
if atom >= len(symbols) or not fits(set(atom_neighbors), neighbors[atom]):
|
|
178
|
+
msg = f"An atom candidate's neighbors aren't its atom's: {atom}"
|
|
179
|
+
raise ValueError(msg)
|
|
180
|
+
for (i, j), (side_i, side_j) in candidates.bonds.items():
|
|
181
|
+
if (
|
|
182
|
+
j >= len(symbols)
|
|
183
|
+
or i not in neighbors[j]
|
|
184
|
+
or not fits(set(side_i), neighbors[i] - {j})
|
|
185
|
+
or not fits(set(side_j), neighbors[j] - {i})
|
|
186
|
+
):
|
|
187
|
+
msg = f"A bond candidate's neighbors aren't its bond's: {(i, j)}"
|
|
188
|
+
raise ValueError(msg)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _join(graph: MolGraph, forms: Sequence[CanonicalForm]) -> str:
|
|
192
|
+
"""The string of all components, sorted and joined as the old code does."""
|
|
193
|
+
layers = [component_layers(graph, form) for form in forms]
|
|
194
|
+
symbols = _sorted_symbols({graph.nodes[k]["symbol"] for k in graph} | {"H"})
|
|
195
|
+
keys = [_sort_key(graph, form, symbols) for form in forms]
|
|
196
|
+
order = sorted(range(len(forms)), key=keys.__getitem__, reverse=True)
|
|
197
|
+
layers = [layers[i] for i in order]
|
|
198
|
+
|
|
199
|
+
joined = {"formula": _join_layer([x["formula"] for x in layers], "", ".")}
|
|
200
|
+
for letter in _LETTERS:
|
|
201
|
+
values = [x.get(letter, "") for x in layers]
|
|
202
|
+
if not any(values):
|
|
203
|
+
continue
|
|
204
|
+
if letter == "m":
|
|
205
|
+
joined[letter] = "".join(value or "." for value in values)
|
|
206
|
+
elif letter == "s":
|
|
207
|
+
joined[letter] = max((value for value in values if value), key=int)
|
|
208
|
+
else:
|
|
209
|
+
joined[letter] = _join_layer(values, "*", ";")
|
|
210
|
+
return component_string(joined)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _join_layer(values: Sequence[str], count_separator: str, separator: str) -> str:
|
|
214
|
+
"""Join one layer of each component, with a count before a repeated value.
|
|
215
|
+
|
|
216
|
+
As the old `join_layer_strings`: equal neighbors are counted (`2*1H2`), and an
|
|
217
|
+
empty value is kept as an empty slot between separators.
|
|
218
|
+
"""
|
|
219
|
+
parts = []
|
|
220
|
+
for value, group in itertools.groupby(values):
|
|
221
|
+
count = len(list(group))
|
|
222
|
+
if value:
|
|
223
|
+
parts.append(f"{count}{count_separator}{value}" if count > 1 else value)
|
|
224
|
+
else:
|
|
225
|
+
parts.append(separator * (count - 1))
|
|
226
|
+
return separator.join(parts)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _sorted_symbols(symbols: set[str]) -> list[str]:
|
|
230
|
+
"""C first, then alphabetical: the old `argsort` doesn't put H second."""
|
|
231
|
+
return sorted(symbols, key=lambda s: (s != "C", s))
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _sort_key(graph: MolGraph, form: CanonicalForm, symbols: Sequence[str]) -> tuple:
|
|
235
|
+
"""The old sort key of a component (`amchi.base.argsort`), from its layers.
|
|
236
|
+
|
|
237
|
+
The formula counts, the neighbors and the hydrogen count of each atom by
|
|
238
|
+
canonical number, the bond and atom parities in the order of their layers, and
|
|
239
|
+
whether it is the inverted enantiomer. The charge, always 0 here, is left out.
|
|
240
|
+
"""
|
|
241
|
+
atoms = sorted(form.numbers, key=form.numbers.__getitem__)
|
|
242
|
+
counts = Counter(graph.nodes[k]["symbol"] for k in atoms)
|
|
243
|
+
counts["H"] += sum(graph.nodes[k]["hydrogens"] for k in atoms)
|
|
244
|
+
formula = tuple(counts[s] for s in symbols)
|
|
245
|
+
neighbors = [sorted(form.numbers[n] for n in graph[k]) for k in atoms]
|
|
246
|
+
hydrogens = [graph.nodes[k]["hydrogens"] for k in atoms]
|
|
247
|
+
bond_parities = [
|
|
248
|
+
parity
|
|
249
|
+
for _, parity in sorted(
|
|
250
|
+
(sorted((form.numbers[i], form.numbers[j]), reverse=True), parity)
|
|
251
|
+
for (i, j), parity in form.bond_parities.items()
|
|
252
|
+
)
|
|
253
|
+
]
|
|
254
|
+
atom_parities = [form.atom_parities[k] for k in atoms if k in form.atom_parities]
|
|
255
|
+
# None (no m layer) sorts below both values, where the old code would fail
|
|
256
|
+
inverted = (
|
|
257
|
+
-1 if form.is_canonical_enantiomer is None else not form.is_canonical_enantiomer
|
|
258
|
+
)
|
|
259
|
+
return (formula, neighbors, hydrogens, bond_parities, atom_parities, inverted)
|
amchi/_candidates.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""The stereocenter candidates of a species or a TS, and the edits that correct them.
|
|
2
|
+
|
|
3
|
+
The rules are the old AutoMol's (`tetrahedral_atoms`, `rigid_planar_bonds`,
|
|
4
|
+
`stereocenter_candidates`), on the graph alone: the candidates never change with the
|
|
5
|
+
conformer (W3; decision D21). A TS applies them to each side, reactant and product (W4).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from collections import deque
|
|
9
|
+
from collections.abc import Collection, Iterable, Sequence
|
|
10
|
+
|
|
11
|
+
from ._element import lone_pairs
|
|
12
|
+
from ._graph import MolGraph, explicit_graph, product_graph, reactant_graph
|
|
13
|
+
from ._resonance import rigid_planar_bonds, unsaturations
|
|
14
|
+
from ._types import Bond, Candidates, Connectivity
|
|
15
|
+
|
|
16
|
+
# Valence + lone pairs of a tetrahedral atom, and the largest ring that a stereo bond
|
|
17
|
+
# can't be in
|
|
18
|
+
_OCTET = 4
|
|
19
|
+
_MAX_RING_SIZE = 7
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def candidates(symbols: Sequence[str], connectivity: Connectivity) -> Candidates:
|
|
23
|
+
"""The stereocenter candidates of a species or a TS, with their neighbors.
|
|
24
|
+
|
|
25
|
+
An atom candidate has at least 3 neighbors and neighbors + lone pairs = 4. A bond
|
|
26
|
+
candidate is rigid and planar, has a neighbor on each side, is in no ring of fewer
|
|
27
|
+
than 8 atoms, and doesn't join two atom candidates. The neighbors are listed
|
|
28
|
+
hydrogens first, then the other atoms, each by ascending index (D21).
|
|
29
|
+
|
|
30
|
+
For a TS, the rules apply to each side. An atom's neighbors are those of the
|
|
31
|
+
reactant side if it is a candidate there, else of the product side; an atom that is
|
|
32
|
+
a candidate on both sides with different neighbors also gets the product-side ones
|
|
33
|
+
in `reverse_atoms` (D26). A bond's neighbors are united over the sides where it is
|
|
34
|
+
rigid and planar, and the ring test follows the bonds of the whole TS, leaving and
|
|
35
|
+
reaching the bond through its listed neighbors only.
|
|
36
|
+
|
|
37
|
+
Examples:
|
|
38
|
+
>>> import amchi
|
|
39
|
+
>>> # CHFClBr and FN=NF
|
|
40
|
+
>>> connectivity = amchi.Connectivity(bonds=[(0, 1), (0, 2), (0, 3), (0, 4)])
|
|
41
|
+
>>> amchi.candidates(["C", "F", "Cl", "Br", "H"], connectivity).atoms
|
|
42
|
+
{0: (4, 1, 2, 3)}
|
|
43
|
+
>>> connectivity = amchi.Connectivity(bonds=[(0, 1), (1, 2), (2, 3)])
|
|
44
|
+
>>> amchi.candidates(["F", "N", "N", "F"], connectivity).bonds
|
|
45
|
+
{(1, 2): ((0,), (3,))}
|
|
46
|
+
>>> # An F atom moves from one C of CH3F to the other in the TS F...CH3...F
|
|
47
|
+
>>> connectivity = amchi.Connectivity(
|
|
48
|
+
... bonds=[(0, 1), (0, 2), (0, 3)], breaking=[(0, 4)], forming=[(0, 5)]
|
|
49
|
+
... )
|
|
50
|
+
>>> result = amchi.candidates(["C", "H", "H", "H", "F", "F"], connectivity)
|
|
51
|
+
>>> result.atoms, result.reverse_atoms
|
|
52
|
+
({0: (1, 2, 3, 4)}, {0: (1, 2, 3, 5)})
|
|
53
|
+
"""
|
|
54
|
+
graph = explicit_graph(symbols, connectivity)
|
|
55
|
+
is_ts = bool(connectivity.breaking or connectivity.forming)
|
|
56
|
+
sides = [reactant_graph(graph), product_graph(graph)] if is_ts else [graph]
|
|
57
|
+
|
|
58
|
+
def ordered(neighbors: Iterable[int]) -> tuple[int, ...]:
|
|
59
|
+
return tuple(sorted(neighbors, key=lambda n: (symbols[n] != "H", n)))
|
|
60
|
+
|
|
61
|
+
def tetrahedral(side: MolGraph) -> dict[int, tuple[int, ...]]:
|
|
62
|
+
return {
|
|
63
|
+
atom: ordered(side[atom])
|
|
64
|
+
for atom in side
|
|
65
|
+
if side.degree(atom) >= 3 # noqa: PLR2004
|
|
66
|
+
and side.degree(atom) + lone_pairs(symbols[atom]) == _OCTET
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
on_side = [tetrahedral(side) for side in sides]
|
|
70
|
+
atoms = on_side[-1] | on_side[0] # the reactant side wins
|
|
71
|
+
reverse_atoms = {
|
|
72
|
+
atom: on_side[-1][atom]
|
|
73
|
+
for atom, neighbors in on_side[0].items()
|
|
74
|
+
if atom in on_side[-1] and set(on_side[-1][atom]) != set(neighbors)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
# Each bond's neighbors, united over the sides where it is rigid and planar. The
|
|
78
|
+
# unsaturation test is a cheap filter before the resonance search.
|
|
79
|
+
neighbors: dict[Bond, tuple[set[int], set[int]]] = {}
|
|
80
|
+
for side in sides:
|
|
81
|
+
unsaturation = unsaturations(side)
|
|
82
|
+
unsaturated = [
|
|
83
|
+
(i, j)
|
|
84
|
+
for i, j in (_bond_key(bond) for bond in side.edges)
|
|
85
|
+
if unsaturation[i] > 0 and unsaturation[j] > 0
|
|
86
|
+
]
|
|
87
|
+
for i, j in rigid_planar_bonds(side, unsaturated):
|
|
88
|
+
side_i, side_j = neighbors.setdefault((i, j), (set(), set()))
|
|
89
|
+
side_i |= set(side[i]) - {j}
|
|
90
|
+
side_j |= set(side[j]) - {i}
|
|
91
|
+
bonds = {
|
|
92
|
+
(i, j): (ordered(side_i), ordered(side_j))
|
|
93
|
+
for (i, j), (side_i, side_j) in sorted(neighbors.items())
|
|
94
|
+
if side_i
|
|
95
|
+
and side_j
|
|
96
|
+
and not _in_small_ring(graph, i, j, side_i, side_j)
|
|
97
|
+
and not (i in atoms and j in atoms)
|
|
98
|
+
}
|
|
99
|
+
return Candidates(atoms=atoms, reverse_atoms=reverse_atoms, bonds=bonds)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def add_bond_candidate(
|
|
103
|
+
candidates: Candidates, connectivity: Connectivity, bond: Collection[int]
|
|
104
|
+
) -> Candidates:
|
|
105
|
+
"""Add a bond candidate, with all its neighbors by ascending index.
|
|
106
|
+
|
|
107
|
+
No filter is applied: a caller overrides the perception on purpose. Remove an atom
|
|
108
|
+
candidate of the bond yourself where it applies. For a TS, the bond and its
|
|
109
|
+
neighbors may be breaking or forming bonds.
|
|
110
|
+
|
|
111
|
+
Raises:
|
|
112
|
+
ValueError: The pair isn't a bond, or one of its atoms has no other neighbor.
|
|
113
|
+
|
|
114
|
+
Examples:
|
|
115
|
+
>>> import amchi
|
|
116
|
+
>>> connectivity = amchi.Connectivity(bonds=[(0, 1), (1, 2), (2, 3)])
|
|
117
|
+
>>> amchi.add_bond_candidate(amchi.Candidates(), connectivity, (2, 1)).bonds
|
|
118
|
+
{(1, 2): ((0,), (3,))}
|
|
119
|
+
"""
|
|
120
|
+
i, j = key = _bond_key(bond)
|
|
121
|
+
if key not in _all_bonds(connectivity):
|
|
122
|
+
msg = f"Not a bond: {key}"
|
|
123
|
+
raise ValueError(msg)
|
|
124
|
+
side_i = tuple(sorted(n for n in _neighbors(connectivity, i) if n != j))
|
|
125
|
+
side_j = tuple(sorted(n for n in _neighbors(connectivity, j) if n != i))
|
|
126
|
+
if not (side_i and side_j):
|
|
127
|
+
msg = f"A bond candidate needs a neighbor on each side: {key}"
|
|
128
|
+
raise ValueError(msg)
|
|
129
|
+
bonds = {**candidates.bonds, key: (side_i, side_j)}
|
|
130
|
+
return candidates.model_copy(update={"bonds": dict(sorted(bonds.items()))})
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def remove_candidate(candidates: Candidates, key: int | Collection[int]) -> Candidates:
|
|
134
|
+
"""Remove an atom candidate (an index) or a bond candidate (a pair).
|
|
135
|
+
|
|
136
|
+
An atom candidate is removed with its reverse neighbors, if it has them.
|
|
137
|
+
|
|
138
|
+
Raises:
|
|
139
|
+
KeyError: It isn't a candidate.
|
|
140
|
+
|
|
141
|
+
Examples:
|
|
142
|
+
>>> import amchi
|
|
143
|
+
>>> candidates = amchi.Candidates(
|
|
144
|
+
... atoms={0: (1, 2, 3)}, bonds={(4, 5): ([6], [7])}
|
|
145
|
+
... )
|
|
146
|
+
>>> amchi.remove_candidate(candidates, 0)
|
|
147
|
+
Candidates(atoms={}, reverse_atoms={}, bonds={(4, 5): ((6,), (7,))})
|
|
148
|
+
>>> amchi.remove_candidate(candidates, (5, 4))
|
|
149
|
+
Candidates(atoms={0: (1, 2, 3)}, reverse_atoms={}, bonds={})
|
|
150
|
+
"""
|
|
151
|
+
atoms, bonds = dict(candidates.atoms), dict(candidates.bonds)
|
|
152
|
+
reverse_atoms = dict(candidates.reverse_atoms)
|
|
153
|
+
if isinstance(key, int):
|
|
154
|
+
if key not in atoms:
|
|
155
|
+
msg = f"Not an atom candidate: {key}"
|
|
156
|
+
raise KeyError(msg)
|
|
157
|
+
del atoms[key]
|
|
158
|
+
reverse_atoms.pop(key, None)
|
|
159
|
+
else:
|
|
160
|
+
bond = _bond_key(key)
|
|
161
|
+
if bond not in bonds:
|
|
162
|
+
msg = f"Not a bond candidate: {bond}"
|
|
163
|
+
raise KeyError(msg)
|
|
164
|
+
del bonds[bond]
|
|
165
|
+
return Candidates(atoms=atoms, reverse_atoms=reverse_atoms, bonds=bonds)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _bond_key(bond: Collection[int]) -> Bond:
|
|
169
|
+
i, j = sorted(bond)
|
|
170
|
+
return (i, j)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _all_bonds(connectivity: Connectivity) -> tuple[Bond, ...]:
|
|
174
|
+
return (*connectivity.bonds, *connectivity.breaking, *connectivity.forming)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _neighbors(connectivity: Connectivity, atom: int) -> list[int]:
|
|
178
|
+
return [
|
|
179
|
+
j if i == atom else i for i, j in _all_bonds(connectivity) if atom in (i, j)
|
|
180
|
+
]
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _in_small_ring(
|
|
184
|
+
graph: MolGraph, i: int, j: int, side_i: Collection[int], side_j: Collection[int]
|
|
185
|
+
) -> bool:
|
|
186
|
+
"""Is the bond in a ring of at most 7 atoms through its listed neighbors?
|
|
187
|
+
|
|
188
|
+
That is, a path of 6 or fewer bonds from `i` to `j` that avoids the bond itself,
|
|
189
|
+
leaves `i` through `side_i` and reaches `j` from `side_j`. The graph has all the
|
|
190
|
+
bonds of a TS, reacting ones included.
|
|
191
|
+
"""
|
|
192
|
+
distance = {i: 0}
|
|
193
|
+
queue = deque([i])
|
|
194
|
+
while queue:
|
|
195
|
+
atom = queue.popleft()
|
|
196
|
+
if distance[atom] >= _MAX_RING_SIZE - 1:
|
|
197
|
+
continue
|
|
198
|
+
for neighbor in graph[atom]:
|
|
199
|
+
if atom == i and (neighbor == j or neighbor not in side_i):
|
|
200
|
+
continue
|
|
201
|
+
if neighbor == j:
|
|
202
|
+
if atom in side_j:
|
|
203
|
+
return True
|
|
204
|
+
continue
|
|
205
|
+
if neighbor not in distance:
|
|
206
|
+
distance[neighbor] = distance[atom] + 1
|
|
207
|
+
queue.append(neighbor)
|
|
208
|
+
return False
|