protomol 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.
- protomol/__init__.py +84 -0
- protomol/_backend.py +208 -0
- protomol/_ccv.py +416 -0
- protomol/_display.py +107 -0
- protomol/_json.py +43 -0
- protomol/_reaction.py +274 -0
- protomol/_smiles.py +249 -0
- protomol/_stereo.py +468 -0
- protomol/_types.py +600 -0
- protomol/_vendor/__init__.py +7 -0
- protomol/_vendor/stereomolgraph/LICENSE +21 -0
- protomol/_vendor/stereomolgraph/__init__.py +23 -0
- protomol/_vendor/stereomolgraph/algorithms/__init__.py +0 -0
- protomol/_vendor/stereomolgraph/algorithms/_bond_orders.py +648 -0
- protomol/_vendor/stereomolgraph/algorithms/canon.py +469 -0
- protomol/_vendor/stereomolgraph/algorithms/circular.py +725 -0
- protomol/_vendor/stereomolgraph/algorithms/isomorphism.py +731 -0
- protomol/_vendor/stereomolgraph/algorithms/symmetry.py +295 -0
- protomol/_vendor/stereomolgraph/coords.py +434 -0
- protomol/_vendor/stereomolgraph/experimental/__init__.py +20 -0
- protomol/_vendor/stereomolgraph/experimental/_isomers.py +180 -0
- protomol/_vendor/stereomolgraph/experimental/_json.py +204 -0
- protomol/_vendor/stereomolgraph/graph2rdmol.py +542 -0
- protomol/_vendor/stereomolgraph/graphs/__init__.py +19 -0
- protomol/_vendor/stereomolgraph/graphs/crg.py +370 -0
- protomol/_vendor/stereomolgraph/graphs/mg.py +743 -0
- protomol/_vendor/stereomolgraph/graphs/scrg.py +574 -0
- protomol/_vendor/stereomolgraph/graphs/smg.py +456 -0
- protomol/_vendor/stereomolgraph/ipython.py +267 -0
- protomol/_vendor/stereomolgraph/periodic_table.py +81 -0
- protomol/_vendor/stereomolgraph/py.typed +0 -0
- protomol/_vendor/stereomolgraph/rdmol2graph.py +547 -0
- protomol/_vendor/stereomolgraph/stereodescriptors.py +674 -0
- protomol/_vendor/stereomolgraph/xyz2graph.py +288 -0
- protomol/examples.py +56 -0
- protomol-0.0.1.dist-info/METADATA +85 -0
- protomol-0.0.1.dist-info/RECORD +39 -0
- protomol-0.0.1.dist-info/WHEEL +4 -0
- protomol-0.0.1.dist-info/licenses/LICENSE +21 -0
protomol/__init__.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""protomol: placeholder graph types for AutoStorage and AutoEngine."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.0.1"
|
|
4
|
+
|
|
5
|
+
from . import examples
|
|
6
|
+
from ._ccv import ts_graphs
|
|
7
|
+
from ._display import display
|
|
8
|
+
from ._json import from_json, to_json
|
|
9
|
+
from ._reaction import (
|
|
10
|
+
products,
|
|
11
|
+
reactants,
|
|
12
|
+
reaction_graph,
|
|
13
|
+
relabel,
|
|
14
|
+
reverse,
|
|
15
|
+
without_stereo,
|
|
16
|
+
)
|
|
17
|
+
from ._smiles import from_smiles
|
|
18
|
+
from ._stereo import (
|
|
19
|
+
AtomStereo,
|
|
20
|
+
AtropBond,
|
|
21
|
+
BondStereo,
|
|
22
|
+
Octahedral,
|
|
23
|
+
PlanarBond,
|
|
24
|
+
SquarePlanar,
|
|
25
|
+
Stereo,
|
|
26
|
+
StereoChange,
|
|
27
|
+
Tetrahedral,
|
|
28
|
+
TrigonalBipyramidal,
|
|
29
|
+
invert,
|
|
30
|
+
isomers,
|
|
31
|
+
site,
|
|
32
|
+
)
|
|
33
|
+
from ._types import (
|
|
34
|
+
AnyGraph,
|
|
35
|
+
GraphError,
|
|
36
|
+
MolGraph,
|
|
37
|
+
ReactionGraph,
|
|
38
|
+
StereoMolGraph,
|
|
39
|
+
StereoReactionGraph,
|
|
40
|
+
is_determined,
|
|
41
|
+
neighbors,
|
|
42
|
+
remove_stereo,
|
|
43
|
+
stereo_at,
|
|
44
|
+
with_stereo,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"AnyGraph",
|
|
49
|
+
"AtomStereo",
|
|
50
|
+
"AtropBond",
|
|
51
|
+
"BondStereo",
|
|
52
|
+
"GraphError",
|
|
53
|
+
"MolGraph",
|
|
54
|
+
"Octahedral",
|
|
55
|
+
"PlanarBond",
|
|
56
|
+
"ReactionGraph",
|
|
57
|
+
"SquarePlanar",
|
|
58
|
+
"Stereo",
|
|
59
|
+
"StereoChange",
|
|
60
|
+
"StereoMolGraph",
|
|
61
|
+
"StereoReactionGraph",
|
|
62
|
+
"Tetrahedral",
|
|
63
|
+
"TrigonalBipyramidal",
|
|
64
|
+
"display",
|
|
65
|
+
"examples",
|
|
66
|
+
"from_json",
|
|
67
|
+
"from_smiles",
|
|
68
|
+
"invert",
|
|
69
|
+
"is_determined",
|
|
70
|
+
"isomers",
|
|
71
|
+
"neighbors",
|
|
72
|
+
"products",
|
|
73
|
+
"reactants",
|
|
74
|
+
"reaction_graph",
|
|
75
|
+
"relabel",
|
|
76
|
+
"remove_stereo",
|
|
77
|
+
"reverse",
|
|
78
|
+
"site",
|
|
79
|
+
"stereo_at",
|
|
80
|
+
"to_json",
|
|
81
|
+
"ts_graphs",
|
|
82
|
+
"with_stereo",
|
|
83
|
+
"without_stereo",
|
|
84
|
+
]
|
protomol/_backend.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Conversion to and from stereomolgraph, the back end (P3, P7).
|
|
2
|
+
|
|
3
|
+
The only module that imports `protomol._vendor.stereomolgraph`; its types never leave
|
|
4
|
+
this module's private functions. Atom ids are the same ints in both, and the LS kinds
|
|
5
|
+
map 1:1 by name. A change's slots map to stereomolgraph's `Change`: `reactant` to
|
|
6
|
+
`BROKEN`, `product` to `FORMED` and `ts` to `FLEETING`.
|
|
7
|
+
|
|
8
|
+
stereomolgraph can't hold a chain LS (a cumulated chain), so `to_smg` drops one with a
|
|
9
|
+
warning.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import warnings
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from ._stereo import (
|
|
16
|
+
AtropBond,
|
|
17
|
+
Octahedral,
|
|
18
|
+
PlanarBond,
|
|
19
|
+
SquarePlanar,
|
|
20
|
+
StereoChange,
|
|
21
|
+
Tetrahedral,
|
|
22
|
+
TrigonalBipyramidal,
|
|
23
|
+
)
|
|
24
|
+
from ._types import (
|
|
25
|
+
AnyGraph,
|
|
26
|
+
MolGraph,
|
|
27
|
+
ReactionGraph,
|
|
28
|
+
StereoMolGraph,
|
|
29
|
+
StereoReactionGraph,
|
|
30
|
+
)
|
|
31
|
+
from ._vendor.stereomolgraph import stereodescriptors as smg_ls
|
|
32
|
+
from ._vendor.stereomolgraph.graphs.crg import Change
|
|
33
|
+
from ._vendor.stereomolgraph.graphs.crg import CondensedReactionGraph as _SmgCRG
|
|
34
|
+
from ._vendor.stereomolgraph.graphs.mg import MolGraph as _SmgMG
|
|
35
|
+
from ._vendor.stereomolgraph.graphs.scrg import (
|
|
36
|
+
StereoCondensedReactionGraph as _SmgSCRG,
|
|
37
|
+
)
|
|
38
|
+
from ._vendor.stereomolgraph.graphs.smg import StereoMolGraph as _SmgSMG
|
|
39
|
+
from ._vendor.stereomolgraph.periodic_table import SYMBOLS
|
|
40
|
+
|
|
41
|
+
type _LS = (
|
|
42
|
+
Tetrahedral
|
|
43
|
+
| SquarePlanar
|
|
44
|
+
| TrigonalBipyramidal
|
|
45
|
+
| Octahedral
|
|
46
|
+
| PlanarBond
|
|
47
|
+
| AtropBond
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# protomol LS class → stereomolgraph LS class, matched by name
|
|
51
|
+
_LS_KINDS: tuple[type[_LS], ...] = (
|
|
52
|
+
Tetrahedral,
|
|
53
|
+
SquarePlanar,
|
|
54
|
+
TrigonalBipyramidal,
|
|
55
|
+
Octahedral,
|
|
56
|
+
PlanarBond,
|
|
57
|
+
AtropBond,
|
|
58
|
+
)
|
|
59
|
+
_TO_SMG_LS: dict[type[_LS], Any] = {
|
|
60
|
+
cls: getattr(smg_ls, cls.__name__) for cls in _LS_KINDS
|
|
61
|
+
}
|
|
62
|
+
_FROM_SMG_LS: dict[Any, type[_LS]] = {
|
|
63
|
+
getattr(smg_ls, cls.__name__): cls for cls in _LS_KINDS
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def to_smg(gra: AnyGraph) -> Any: # noqa: ANN401 (stereomolgraph is untyped here)
|
|
68
|
+
"""The stereomolgraph graph of `gra` (of the matching type).
|
|
69
|
+
|
|
70
|
+
A chain LS is dropped with a warning: stereomolgraph can't hold one.
|
|
71
|
+
"""
|
|
72
|
+
reaction = isinstance(gra, ReactionGraph | StereoReactionGraph)
|
|
73
|
+
stereo = isinstance(gra, StereoMolGraph | StereoReactionGraph)
|
|
74
|
+
cls: Any = {
|
|
75
|
+
(False, False): _SmgMG,
|
|
76
|
+
(False, True): _SmgSMG,
|
|
77
|
+
(True, False): _SmgCRG,
|
|
78
|
+
(True, True): _SmgSCRG,
|
|
79
|
+
}[reaction, stereo]
|
|
80
|
+
smg = cls()
|
|
81
|
+
for i, symbol in enumerate(gra.symbols):
|
|
82
|
+
smg.add_atom(i, symbol)
|
|
83
|
+
_add_bonds(smg, gra)
|
|
84
|
+
if isinstance(gra, StereoMolGraph | StereoReactionGraph):
|
|
85
|
+
_add_stereo(smg, gra)
|
|
86
|
+
return smg
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def from_smg(
|
|
90
|
+
smg: Any, # noqa: ANN401 (stereomolgraph is untyped here)
|
|
91
|
+
*,
|
|
92
|
+
charge: int,
|
|
93
|
+
spin: int,
|
|
94
|
+
) -> AnyGraph:
|
|
95
|
+
"""The protomol graph of a stereomolgraph graph, whose atoms are 0 to n - 1.
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
ValueError: If the atoms are not 0 to n - 1, a bond is fleeting, or an LS is of
|
|
99
|
+
a kind protomol doesn't have (pydantic's `ValidationError` for an invalid
|
|
100
|
+
graph is a `ValueError` too).
|
|
101
|
+
"""
|
|
102
|
+
atoms = sorted(smg.atoms)
|
|
103
|
+
if atoms != list(range(len(atoms))):
|
|
104
|
+
msg = f"stereomolgraph atoms must be 0 to n - 1, got {atoms}"
|
|
105
|
+
raise ValueError(msg)
|
|
106
|
+
data: dict[str, Any] = {
|
|
107
|
+
"symbols": [SYMBOLS[smg.get_atom_type(i)] for i in atoms],
|
|
108
|
+
"bonds": [tuple(bond) for bond in smg.bonds],
|
|
109
|
+
"charge": charge,
|
|
110
|
+
"spin": spin,
|
|
111
|
+
}
|
|
112
|
+
reaction = isinstance(smg, _SmgCRG)
|
|
113
|
+
stereo = isinstance(smg, _SmgSMG)
|
|
114
|
+
if reaction:
|
|
115
|
+
if smg.get_fleeting_bonds():
|
|
116
|
+
msg = "protomol has no fleeting bonds"
|
|
117
|
+
raise ValueError(msg)
|
|
118
|
+
data["breaking"] = [tuple(bond) for bond in smg.get_broken_bonds()]
|
|
119
|
+
data["forming"] = [tuple(bond) for bond in smg.get_formed_bonds()]
|
|
120
|
+
if stereo:
|
|
121
|
+
data["atom_stereo"] = [_from_smg_ls(ls) for ls in smg.atom_stereo.values()]
|
|
122
|
+
data["bond_stereo"] = [_from_smg_ls(ls) for ls in smg.bond_stereo.values()]
|
|
123
|
+
if reaction and stereo:
|
|
124
|
+
changes = [*smg.atom_stereo_changes.values(), *smg.bond_stereo_changes.values()]
|
|
125
|
+
data["stereo_changes"] = [_from_smg_change(change) for change in changes]
|
|
126
|
+
return StereoReactionGraph(**data)
|
|
127
|
+
if reaction:
|
|
128
|
+
return ReactionGraph(**data)
|
|
129
|
+
if stereo:
|
|
130
|
+
return StereoMolGraph(**data)
|
|
131
|
+
return MolGraph(**data)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _add_bonds(smg: Any, gra: AnyGraph) -> None: # noqa: ANN401
|
|
135
|
+
if isinstance(gra, MolGraph | StereoMolGraph):
|
|
136
|
+
for bond in gra.bonds:
|
|
137
|
+
smg.add_bond(*bond)
|
|
138
|
+
return
|
|
139
|
+
breaking, forming = set(gra.breaking), set(gra.forming)
|
|
140
|
+
for bond in gra.bonds:
|
|
141
|
+
if bond in breaking:
|
|
142
|
+
smg.add_broken_bond(*bond)
|
|
143
|
+
elif bond in forming:
|
|
144
|
+
smg.add_formed_bond(*bond)
|
|
145
|
+
else:
|
|
146
|
+
smg.add_bond(*bond)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _add_stereo(smg: Any, gra: StereoMolGraph | StereoReactionGraph) -> None: # noqa: ANN401
|
|
150
|
+
for ls in (*gra.atom_stereo, *gra.bond_stereo):
|
|
151
|
+
smg_ls_ = _to_smg_ls(ls)
|
|
152
|
+
if smg_ls_ is None:
|
|
153
|
+
continue
|
|
154
|
+
if isinstance(ls, PlanarBond | AtropBond):
|
|
155
|
+
smg.set_bond_stereo(smg_ls_)
|
|
156
|
+
else:
|
|
157
|
+
smg.set_atom_stereo(smg_ls_)
|
|
158
|
+
if isinstance(gra, StereoReactionGraph):
|
|
159
|
+
for change in gra.stereo_changes:
|
|
160
|
+
_set_change(smg, change)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _to_smg_ls(ls: _LS) -> Any: # noqa: ANN401
|
|
164
|
+
"""The stereomolgraph LS, or None (with a warning) for a chain LS."""
|
|
165
|
+
if isinstance(ls, PlanarBond | AtropBond) and ls.chain:
|
|
166
|
+
warnings.warn(
|
|
167
|
+
f"stereomolgraph can't hold a chain LS; dropped {ls}",
|
|
168
|
+
stacklevel=3,
|
|
169
|
+
)
|
|
170
|
+
return None
|
|
171
|
+
return _TO_SMG_LS[type(ls)](ls.atoms, ls.parity)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _from_smg_ls(ls: Any) -> _LS: # noqa: ANN401
|
|
175
|
+
cls = _FROM_SMG_LS.get(type(ls))
|
|
176
|
+
if cls is None:
|
|
177
|
+
msg = f"protomol has no LS kind for {ls!r}"
|
|
178
|
+
raise ValueError(msg)
|
|
179
|
+
return cls(atoms=ls.atoms, parity=ls.parity)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _set_change(smg: Any, change: StereoChange) -> None: # noqa: ANN401
|
|
183
|
+
slots = {
|
|
184
|
+
"broken": change.reactant,
|
|
185
|
+
"formed": change.product,
|
|
186
|
+
"fleeting": change.ts,
|
|
187
|
+
}
|
|
188
|
+
smg_slots = {name: _to_smg_ls(ls) for name, ls in slots.items() if ls is not None}
|
|
189
|
+
smg_slots = {name: ls for name, ls in smg_slots.items() if ls is not None}
|
|
190
|
+
if not smg_slots:
|
|
191
|
+
return
|
|
192
|
+
some = next(ls for ls in slots.values() if ls is not None)
|
|
193
|
+
if isinstance(some, PlanarBond | AtropBond):
|
|
194
|
+
smg.set_bond_stereo_change(**smg_slots)
|
|
195
|
+
else:
|
|
196
|
+
smg.set_atom_stereo_change(**smg_slots)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _from_smg_change(change: Any) -> StereoChange: # noqa: ANN401
|
|
200
|
+
def slot(key: Change) -> _LS | None:
|
|
201
|
+
ls = change.get(key)
|
|
202
|
+
return None if ls is None else _from_smg_ls(ls)
|
|
203
|
+
|
|
204
|
+
return StereoChange(
|
|
205
|
+
reactant=slot(Change.BROKEN),
|
|
206
|
+
product=slot(Change.FORMED),
|
|
207
|
+
ts=slot(Change.FLEETING),
|
|
208
|
+
)
|
protomol/_ccv.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"""TS channels by the constructive count vector (CCV) algorithm (P18).
|
|
2
|
+
|
|
3
|
+
Ported from autoccv's `ccv.py` (fewest-bonds-first CCV): only the graph structure
|
|
4
|
+
changes. The search runs on unfrozen networkx copies of `_nx(gra)`, with `symbol` on
|
|
5
|
+
the nodes and, for reaction graphs, `change` on the edges.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import functools
|
|
9
|
+
import itertools
|
|
10
|
+
from collections import Counter, defaultdict
|
|
11
|
+
from collections.abc import Iterator, Sequence
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import overload
|
|
14
|
+
|
|
15
|
+
import more_itertools as mit
|
|
16
|
+
import networkx as nx
|
|
17
|
+
from networkx.algorithms.isomorphism import GraphMatcher
|
|
18
|
+
from rdkit import Chem
|
|
19
|
+
|
|
20
|
+
from ._backend import to_smg
|
|
21
|
+
from ._reaction import products as _products
|
|
22
|
+
from ._reaction import reactants as _reactants
|
|
23
|
+
from ._reaction import reaction_graph, relabel, reverse
|
|
24
|
+
from ._stereo import AtropBond, PlanarBond, StereoChange, Tetrahedral, isomers
|
|
25
|
+
from ._types import (
|
|
26
|
+
_LS,
|
|
27
|
+
AnyGraph,
|
|
28
|
+
GraphError,
|
|
29
|
+
MolGraph,
|
|
30
|
+
ReactionGraph,
|
|
31
|
+
StereoMolGraph,
|
|
32
|
+
StereoReactionGraph,
|
|
33
|
+
_nx,
|
|
34
|
+
_site,
|
|
35
|
+
with_stereo,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
type _Pair = tuple[int, int]
|
|
39
|
+
type _BondSymbol = tuple[str, str]
|
|
40
|
+
|
|
41
|
+
_PERIODIC_TABLE = Chem.GetPeriodicTable()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@overload
|
|
45
|
+
def ts_graphs(
|
|
46
|
+
reactants: StereoMolGraph, products: StereoMolGraph, *, extra_breaks: int = 2
|
|
47
|
+
) -> list[StereoReactionGraph]: ...
|
|
48
|
+
@overload
|
|
49
|
+
def ts_graphs(
|
|
50
|
+
reactants: MolGraph, products: MolGraph, *, extra_breaks: int = 2
|
|
51
|
+
) -> list[ReactionGraph]: ...
|
|
52
|
+
def ts_graphs(
|
|
53
|
+
reactants: MolGraph | StereoMolGraph,
|
|
54
|
+
products: MolGraph | StereoMolGraph,
|
|
55
|
+
*,
|
|
56
|
+
extra_breaks: int = 2,
|
|
57
|
+
) -> list[ReactionGraph] | list[StereoReactionGraph]:
|
|
58
|
+
"""The topologically distinct TS channels from reactants to products (CCV).
|
|
59
|
+
|
|
60
|
+
Each graph is in the reactants' atom order, and each channel is one elementary step
|
|
61
|
+
that changes something (P44): the channel where nothing changes is never returned,
|
|
62
|
+
so a degenerate reaction (CH4 + CH3 → CH3 + CH4) gives its bond-changing channels.
|
|
63
|
+
|
|
64
|
+
With stereo inputs, the channels are the stereo-distinct ones whose two sides are
|
|
65
|
+
the given reactants and products (stereo-aware isomorphism). If the two sides
|
|
66
|
+
differ only in stereo, a channel with no bond changes and exactly one stereo change
|
|
67
|
+
that needs no bonds (a rotation about a bond LS, or an inversion at a lone-pair
|
|
68
|
+
centre) comes first. Otherwise, each topological channel's LS are enumerated at the
|
|
69
|
+
sites its reaction touches, so diastereotopic atoms give separate channels (the two
|
|
70
|
+
H of C3 in (R)-butan-2-ol, say), and every other LS stays unchanged: a channel that
|
|
71
|
+
would need a stereo change at an untouched site is not one step, and is dropped.
|
|
72
|
+
The `ts` slots stay empty: fleeting stereo comes in Phase 5.
|
|
73
|
+
|
|
74
|
+
`extra_breaks` is the most bonds the search breaks and re-forms beyond those the
|
|
75
|
+
bond counts require.
|
|
76
|
+
|
|
77
|
+
Raises:
|
|
78
|
+
TypeError: If the two graphs are not both `MolGraph`s or both
|
|
79
|
+
`StereoMolGraph`s.
|
|
80
|
+
GraphError: If their charge or spin differ.
|
|
81
|
+
"""
|
|
82
|
+
if not (
|
|
83
|
+
type(reactants) is type(products)
|
|
84
|
+
and isinstance(reactants, MolGraph | StereoMolGraph)
|
|
85
|
+
):
|
|
86
|
+
msg = (
|
|
87
|
+
"Expected two MolGraphs or two StereoMolGraphs, got "
|
|
88
|
+
f"{type(reactants).__name__} and {type(products).__name__}"
|
|
89
|
+
)
|
|
90
|
+
raise TypeError(msg)
|
|
91
|
+
for name in ("charge", "spin"):
|
|
92
|
+
if getattr(reactants, name) != getattr(products, name):
|
|
93
|
+
msg = (
|
|
94
|
+
f"Reactants and products differ in {name}: "
|
|
95
|
+
f"{getattr(reactants, name)} and {getattr(products, name)}"
|
|
96
|
+
)
|
|
97
|
+
raise GraphError(msg)
|
|
98
|
+
if isinstance(reactants, MolGraph):
|
|
99
|
+
return [
|
|
100
|
+
gra
|
|
101
|
+
for gra, _ in _CCV(reactants, products).results(extra_breaks=extra_breaks)
|
|
102
|
+
]
|
|
103
|
+
assert isinstance(products, StereoMolGraph) # noqa: S101 (for the type checker)
|
|
104
|
+
if _is_isomorphic(_nx(reactants), _nx(products)) and _frozen_smg(
|
|
105
|
+
reactants
|
|
106
|
+
) != _frozen_smg(products):
|
|
107
|
+
rotations = _no_bond_change_channels(reactants, products)
|
|
108
|
+
if rotations:
|
|
109
|
+
return rotations
|
|
110
|
+
results = _CCV(reactants, products).results(extra_breaks=extra_breaks)
|
|
111
|
+
n = len(reactants.symbols)
|
|
112
|
+
return [
|
|
113
|
+
srg
|
|
114
|
+
for _, mapping in results
|
|
115
|
+
for srg in _stereo_channels(
|
|
116
|
+
reactants,
|
|
117
|
+
products,
|
|
118
|
+
reaction_graph(
|
|
119
|
+
reactants, relabel(products, [mapping[k] for k in range(n)])
|
|
120
|
+
),
|
|
121
|
+
)
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _no_bond_change_channels(
|
|
126
|
+
reactants: StereoMolGraph, products: StereoMolGraph
|
|
127
|
+
) -> list[StereoReactionGraph]:
|
|
128
|
+
"""The channels with no bond changes and one stereo change that needs no bonds.
|
|
129
|
+
|
|
130
|
+
The change is another configuration of one determined LS of the reactants: a bond
|
|
131
|
+
LS (a rotation) or a `Tetrahedral` with a lone-pair slot (an inversion). The
|
|
132
|
+
product side must be stereo-isomorphic to `products`, and the channels are
|
|
133
|
+
deduplicated as in `_stereo_channels`. The caller checks that the inputs are not
|
|
134
|
+
stereo-isomorphic: a trivial LS (a terminal =CH2) would otherwise give a rotation.
|
|
135
|
+
"""
|
|
136
|
+
unchanged = reaction_graph(reactants, reactants)
|
|
137
|
+
want = _frozen_smg(products)
|
|
138
|
+
found: dict[object, StereoReactionGraph] = {}
|
|
139
|
+
for ls in (*reactants.atom_stereo, *reactants.bond_stereo):
|
|
140
|
+
if ls.parity is None or not (
|
|
141
|
+
isinstance(ls, PlanarBond | AtropBond)
|
|
142
|
+
or (isinstance(ls, Tetrahedral) and None in ls.atoms)
|
|
143
|
+
):
|
|
144
|
+
continue
|
|
145
|
+
for alt in isomers(ls):
|
|
146
|
+
if alt == ls:
|
|
147
|
+
continue
|
|
148
|
+
cand = with_stereo(unchanged, StereoChange(reactant=ls, product=alt))
|
|
149
|
+
if _frozen_smg(_products(cand)) == want:
|
|
150
|
+
found.setdefault(_frozen_smg(cand), cand)
|
|
151
|
+
return list(found.values())
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _stereo_channels(
|
|
155
|
+
reactants: StereoMolGraph, products: StereoMolGraph, srg: StereoReactionGraph
|
|
156
|
+
) -> list[StereoReactionGraph]:
|
|
157
|
+
"""The stereo-distinct versions of one channel whose sides match the inputs.
|
|
158
|
+
|
|
159
|
+
`srg` is the channel with one atom mapping. The changes at the sites its reaction
|
|
160
|
+
touches (its centre, or a bond's end, is in a breaking or forming bond) get every
|
|
161
|
+
configuration on each side; a side whose LS is undetermined stays undetermined.
|
|
162
|
+
The other sites keep their reactant LS on both sides (P44: no stereo change at an
|
|
163
|
+
untouched site), so the result is empty if the inputs need one.
|
|
164
|
+
Candidates are deduplicated, as in stereomolgraph's `generate_stereoisomers`, by
|
|
165
|
+
frozen stereomolgraph graphs, whose hash and `==` are stereo-aware isomorphism.
|
|
166
|
+
"""
|
|
167
|
+
reacting = {atom for bond in (*srg.breaking, *srg.forming) for atom in bond}
|
|
168
|
+
touched: list[list[StereoChange]] = []
|
|
169
|
+
untouched: list[_LS] = []
|
|
170
|
+
for item in (*srg.atom_stereo, *srg.bond_stereo, *srg.stereo_changes):
|
|
171
|
+
if isinstance(item, StereoChange):
|
|
172
|
+
if _touches(item, reacting):
|
|
173
|
+
touched.append(_change_configurations(item))
|
|
174
|
+
elif item.reactant is not None:
|
|
175
|
+
untouched.append(item.reactant)
|
|
176
|
+
else:
|
|
177
|
+
untouched.append(item)
|
|
178
|
+
|
|
179
|
+
want = (_frozen_smg(reactants), _frozen_smg(products))
|
|
180
|
+
found: dict[object, StereoReactionGraph] = {}
|
|
181
|
+
for changes in itertools.product(*touched):
|
|
182
|
+
cand = with_stereo(srg, *untouched, *changes)
|
|
183
|
+
sides = (_frozen_smg(_reactants(cand)), _frozen_smg(_products(cand)))
|
|
184
|
+
if sides == want:
|
|
185
|
+
found.setdefault(_frozen_smg(cand), cand)
|
|
186
|
+
return list(found.values())
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _touches(change: StereoChange, reacting: set[int]) -> bool:
|
|
190
|
+
"""Whether a change is structural, not a pure inversion.
|
|
191
|
+
|
|
192
|
+
It is if its site (its centre, or a bond's ends) is a reacting atom, or if its LS
|
|
193
|
+
has no counterpart on the other side, or other atoms there (a double bond that
|
|
194
|
+
moves, say).
|
|
195
|
+
"""
|
|
196
|
+
r, p = change.reactant, change.product
|
|
197
|
+
if r is None or p is None or set(r.atoms) != set(p.atoms):
|
|
198
|
+
return True
|
|
199
|
+
site = _site(change)
|
|
200
|
+
return any(
|
|
201
|
+
atom in reacting for atom in ((site,) if isinstance(site, int) else site)
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _change_configurations(change: StereoChange) -> list[StereoChange]:
|
|
206
|
+
"""Every configuration of a change's reactant and product LS (`ts` kept).
|
|
207
|
+
|
|
208
|
+
A side whose LS is undetermined keeps it undetermined.
|
|
209
|
+
"""
|
|
210
|
+
sides = [
|
|
211
|
+
[ls] if ls is None or ls.parity is None else list(isomers(ls))
|
|
212
|
+
for ls in (change.reactant, change.product)
|
|
213
|
+
]
|
|
214
|
+
return [
|
|
215
|
+
StereoChange(reactant=r, product=p, ts=change.ts)
|
|
216
|
+
for r, p in itertools.product(*sides)
|
|
217
|
+
]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _frozen_smg(gra: AnyGraph) -> object:
|
|
221
|
+
"""The frozen stereomolgraph graph (hash and `==`: stereo-aware isomorphism)."""
|
|
222
|
+
smg = to_smg(gra)
|
|
223
|
+
smg.freeze()
|
|
224
|
+
return smg
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@dataclass(frozen=True)
|
|
228
|
+
class _CCV:
|
|
229
|
+
"""The CCV search from reactants to products (autoccv's `CCV`)."""
|
|
230
|
+
|
|
231
|
+
reactants: MolGraph | StereoMolGraph
|
|
232
|
+
products: MolGraph | StereoMolGraph
|
|
233
|
+
|
|
234
|
+
@functools.cached_property
|
|
235
|
+
def reactant_bond_symbols(self) -> dict[_Pair, _BondSymbol]:
|
|
236
|
+
return _bond_symbols(self.reactants)
|
|
237
|
+
|
|
238
|
+
@functools.cached_property
|
|
239
|
+
def product_bond_symbols(self) -> dict[_Pair, _BondSymbol]:
|
|
240
|
+
return _bond_symbols(self.products)
|
|
241
|
+
|
|
242
|
+
@functools.cached_property
|
|
243
|
+
def reactant_bond_count_vector(self) -> Counter[_BondSymbol]:
|
|
244
|
+
return Counter(self.reactant_bond_symbols.values())
|
|
245
|
+
|
|
246
|
+
@functools.cached_property
|
|
247
|
+
def product_bond_count_vector(self) -> Counter[_BondSymbol]:
|
|
248
|
+
return Counter(self.product_bond_symbols.values())
|
|
249
|
+
|
|
250
|
+
def results(
|
|
251
|
+
self,
|
|
252
|
+
*,
|
|
253
|
+
extra_breaks: int = 2,
|
|
254
|
+
unique_isomorphs: bool = True,
|
|
255
|
+
unique_bond_changes: bool = True,
|
|
256
|
+
maximum_bond_score: bool = True,
|
|
257
|
+
) -> list[tuple[ReactionGraph, dict[int, int]]]:
|
|
258
|
+
"""The TS graphs and their mappings (reactant atom → product atom), filtered.
|
|
259
|
+
|
|
260
|
+
The filters keep the isomorphically distinct graphs, the graphs with distinct
|
|
261
|
+
bond changes, and the graphs with the highest bonding score (the most open
|
|
262
|
+
valences used: radical sites and multiple bonds).
|
|
263
|
+
"""
|
|
264
|
+
max_score = None
|
|
265
|
+
if maximum_bond_score:
|
|
266
|
+
max_score = max(
|
|
267
|
+
(
|
|
268
|
+
_bonding_score(gra)
|
|
269
|
+
for gra, _ in self.all_results(
|
|
270
|
+
extra_breaks=extra_breaks, unique_bond_changes=True
|
|
271
|
+
)
|
|
272
|
+
),
|
|
273
|
+
default=None,
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
kept: list[tuple[ReactionGraph, dict[int, int]]] = []
|
|
277
|
+
for gra, mapping in self.all_results(
|
|
278
|
+
extra_breaks=extra_breaks, unique_bond_changes=unique_bond_changes
|
|
279
|
+
):
|
|
280
|
+
if maximum_bond_score and _bonding_score(gra) != max_score:
|
|
281
|
+
continue
|
|
282
|
+
if unique_isomorphs and any(
|
|
283
|
+
_is_isomorphic(_nx(gra), _nx(g)) for g, _ in kept
|
|
284
|
+
):
|
|
285
|
+
continue
|
|
286
|
+
kept.append((gra, mapping))
|
|
287
|
+
return kept
|
|
288
|
+
|
|
289
|
+
def all_results(
|
|
290
|
+
self, *, extra_breaks: int = 2, unique_bond_changes: bool = False
|
|
291
|
+
) -> Iterator[tuple[ReactionGraph, dict[int, int]]]:
|
|
292
|
+
"""Every result with the fewest extra broken bonds that gives any."""
|
|
293
|
+
seen: list[tuple[frozenset[_Pair], frozenset[_Pair]]] | None = (
|
|
294
|
+
[] if unique_bond_changes else None
|
|
295
|
+
)
|
|
296
|
+
for num_extra in range(extra_breaks + 1):
|
|
297
|
+
for extra_cv in self._extra_breaking_bond_count_vectors(num_extra):
|
|
298
|
+
results = itertools.chain.from_iterable(
|
|
299
|
+
self._transition_graphs(b1, b2, seen)
|
|
300
|
+
for b1, b2 in self._breaking_bond_patterns(extra_cv)
|
|
301
|
+
)
|
|
302
|
+
first = next(results, None)
|
|
303
|
+
if first is None:
|
|
304
|
+
continue
|
|
305
|
+
yield first
|
|
306
|
+
yield from results
|
|
307
|
+
return
|
|
308
|
+
|
|
309
|
+
def _extra_breaking_bond_count_vectors(
|
|
310
|
+
self, num: int
|
|
311
|
+
) -> Iterator[Counter[_BondSymbol]]:
|
|
312
|
+
rcv = self.reactant_bond_count_vector
|
|
313
|
+
pcv = self.product_bond_count_vector
|
|
314
|
+
cv = rcv - (rcv - pcv)
|
|
315
|
+
symbs = sorted(cv.keys(), key=lambda x: (-x.count("H"), x))
|
|
316
|
+
pool = list(
|
|
317
|
+
itertools.chain.from_iterable(itertools.repeat(s, cv[s]) for s in symbs)
|
|
318
|
+
)
|
|
319
|
+
return map(Counter, mit.unique_everseen(itertools.combinations(pool, num)))
|
|
320
|
+
|
|
321
|
+
def _breaking_bond_patterns(
|
|
322
|
+
self, extra_cv: Counter[_BondSymbol]
|
|
323
|
+
) -> Iterator[tuple[tuple[_Pair, ...], tuple[_Pair, ...]]]:
|
|
324
|
+
rcv0 = self.reactant_bond_count_vector
|
|
325
|
+
pcv0 = self.product_bond_count_vector
|
|
326
|
+
rcv = (rcv0 - pcv0) + extra_cv
|
|
327
|
+
pcv = (pcv0 - rcv0) + extra_cv
|
|
328
|
+
return itertools.product(
|
|
329
|
+
_count_vector_bond_combinations(rcv, self.reactant_bond_symbols),
|
|
330
|
+
_count_vector_bond_combinations(pcv, self.product_bond_symbols),
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
def _transition_graphs(
|
|
334
|
+
self,
|
|
335
|
+
break_bonds1: Sequence[_Pair],
|
|
336
|
+
break_bonds2: Sequence[_Pair],
|
|
337
|
+
seen: list[tuple[frozenset[_Pair], frozenset[_Pair]]] | None,
|
|
338
|
+
) -> Iterator[tuple[ReactionGraph, dict[int, int]]]:
|
|
339
|
+
"""The TS graphs whose broken reactants match the broken products."""
|
|
340
|
+
gra1 = nx.Graph(_nx(self.reactants))
|
|
341
|
+
gra1.remove_edges_from(break_bonds1)
|
|
342
|
+
gra2 = nx.Graph(_nx(self.products))
|
|
343
|
+
gra2.remove_edges_from(break_bonds2)
|
|
344
|
+
for mapping in _matcher(gra1, gra2).isomorphisms_iter():
|
|
345
|
+
inverse = {v: k for k, v in mapping.items()}
|
|
346
|
+
breaking = frozenset(break_bonds1)
|
|
347
|
+
forming = frozenset(
|
|
348
|
+
(min(inverse[i], inverse[j]), max(inverse[i], inverse[j]))
|
|
349
|
+
for i, j in break_bonds2
|
|
350
|
+
)
|
|
351
|
+
# Nothing changes, or a bond breaks and re-forms: not a channel (P44)
|
|
352
|
+
if not (breaking or forming) or breaking & forming:
|
|
353
|
+
continue
|
|
354
|
+
if seen is not None:
|
|
355
|
+
if (breaking, forming) in seen:
|
|
356
|
+
continue
|
|
357
|
+
seen.append((breaking, forming))
|
|
358
|
+
gra = ReactionGraph(
|
|
359
|
+
symbols=self.reactants.symbols,
|
|
360
|
+
bonds={*self.reactants.bonds, *forming},
|
|
361
|
+
charge=self.reactants.charge,
|
|
362
|
+
spin=self.reactants.spin,
|
|
363
|
+
breaking=breaking,
|
|
364
|
+
forming=forming,
|
|
365
|
+
)
|
|
366
|
+
yield gra, mapping
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _bond_symbols(gra: MolGraph | StereoMolGraph) -> dict[_Pair, _BondSymbol]:
|
|
370
|
+
"""The sorted pair of element symbols of each bond."""
|
|
371
|
+
s = gra.symbols
|
|
372
|
+
return {(i, j): (min(s[i], s[j]), max(s[i], s[j])) for i, j in gra.bonds}
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _count_vector_bond_combinations(
|
|
376
|
+
cv: Counter[_BondSymbol], symbs: dict[_Pair, _BondSymbol]
|
|
377
|
+
) -> Iterator[tuple[_Pair, ...]]:
|
|
378
|
+
"""The bond combinations with the counts of `cv`."""
|
|
379
|
+
keys: defaultdict[_BondSymbol, list[_Pair]] = defaultdict(list)
|
|
380
|
+
for key, symb in symbs.items():
|
|
381
|
+
keys[symb].append(key)
|
|
382
|
+
per_symbol = [itertools.combinations(keys[s], count) for s, count in cv.items()]
|
|
383
|
+
for combination in itertools.product(*per_symbol):
|
|
384
|
+
yield tuple(itertools.chain.from_iterable(combination))
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _open_valences(gra: MolGraph, atoms: Sequence[int]) -> list[int]:
|
|
388
|
+
"""The default valence (RDKit's) minus the degree, for each atom."""
|
|
389
|
+
nxg = _nx(gra)
|
|
390
|
+
return [
|
|
391
|
+
_PERIODIC_TABLE.GetDefaultValence(gra.symbols[i]) - nxg.degree[i] for i in atoms
|
|
392
|
+
]
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _forward_bonding_score(gra: ReactionGraph) -> int:
|
|
396
|
+
"""The open valences on the reactant side of the atoms of the forming bonds."""
|
|
397
|
+
atoms = sorted(set(itertools.chain.from_iterable(gra.forming)))
|
|
398
|
+
return sum(_open_valences(_reactants(gra), atoms))
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _bonding_score(gra: ReactionGraph) -> int:
|
|
402
|
+
return _forward_bonding_score(gra) + _forward_bonding_score(reverse(gra))
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _matcher(gra1: nx.Graph, gra2: nx.Graph) -> GraphMatcher:
|
|
406
|
+
"""A matcher on the `symbol` of nodes and the `change` of edges."""
|
|
407
|
+
return GraphMatcher(
|
|
408
|
+
gra1,
|
|
409
|
+
gra2,
|
|
410
|
+
node_match=lambda a, b: a["symbol"] == b["symbol"],
|
|
411
|
+
edge_match=lambda a, b: a.get("change") == b.get("change"),
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _is_isomorphic(gra1: nx.Graph, gra2: nx.Graph) -> bool:
|
|
416
|
+
return _matcher(gra1, gra2).is_isomorphic()
|