chython 2.4__cp312-cp312-win_amd64.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.
Files changed (171) hide show
  1. chython/__init__.py +31 -0
  2. chython/_functions.py +69 -0
  3. chython/algorithms/__init__.py +18 -0
  4. chython/algorithms/_isomorphism.cp312-win_amd64.pyd +0 -0
  5. chython/algorithms/_isomorphism.pyx +189 -0
  6. chython/algorithms/aromatics/__init__.py +27 -0
  7. chython/algorithms/aromatics/_rules.py +124 -0
  8. chython/algorithms/aromatics/kekule.py +530 -0
  9. chython/algorithms/aromatics/test/__init__.py +18 -0
  10. chython/algorithms/aromatics/test/test_kekule.py +160 -0
  11. chython/algorithms/aromatics/test/test_thiele.py +263 -0
  12. chython/algorithms/aromatics/thiele.py +226 -0
  13. chython/algorithms/calculate2d/__init__.py +23 -0
  14. chython/algorithms/calculate2d/clean2d.js +1 -0
  15. chython/algorithms/calculate2d/molecule.py +149 -0
  16. chython/algorithms/calculate2d/reaction.py +80 -0
  17. chython/algorithms/depict.py +523 -0
  18. chython/algorithms/fingerprints/__init__.py +48 -0
  19. chython/algorithms/fingerprints/linear.py +208 -0
  20. chython/algorithms/fingerprints/morgan.py +137 -0
  21. chython/algorithms/fingerprints/test/__init__.py +18 -0
  22. chython/algorithms/fingerprints/test/test_linear.py +127 -0
  23. chython/algorithms/fingerprints/test/test_morgan.py +79 -0
  24. chython/algorithms/isomorphism.py +667 -0
  25. chython/algorithms/mapping/__init__.py +28 -0
  26. chython/algorithms/mapping/_groups.py +94 -0
  27. chython/algorithms/mapping/_reactions.py +72 -0
  28. chython/algorithms/mapping/attention.py +216 -0
  29. chython/algorithms/mapping/fixmapper.py +84 -0
  30. chython/algorithms/mapping/groups.py +137 -0
  31. chython/algorithms/mcs.py +202 -0
  32. chython/algorithms/morgan.py +82 -0
  33. chython/algorithms/rings.py +551 -0
  34. chython/algorithms/smiles.py +556 -0
  35. chython/algorithms/standardize/__init__.py +30 -0
  36. chython/algorithms/standardize/_charged.py +115 -0
  37. chython/algorithms/standardize/_groups.py +926 -0
  38. chython/algorithms/standardize/_metal_organics.py +189 -0
  39. chython/algorithms/standardize/_reagents.py +44 -0
  40. chython/algorithms/standardize/_salts.py +68 -0
  41. chython/algorithms/standardize/molecule.py +479 -0
  42. chython/algorithms/standardize/reaction.py +429 -0
  43. chython/algorithms/standardize/resonance.py +196 -0
  44. chython/algorithms/standardize/salts.py +128 -0
  45. chython/algorithms/standardize/saturation.py +378 -0
  46. chython/algorithms/standardize/test/__init__.py +18 -0
  47. chython/algorithms/standardize/test/test_groups.py +118 -0
  48. chython/algorithms/stereo.py +1222 -0
  49. chython/algorithms/tautomers/__init__.py +171 -0
  50. chython/algorithms/tautomers/_acid.py +59 -0
  51. chython/algorithms/tautomers/_base.py +116 -0
  52. chython/algorithms/tautomers/_keto_enol.py +107 -0
  53. chython/algorithms/tautomers/acid_base.py +214 -0
  54. chython/algorithms/tautomers/heteroarenes.py +108 -0
  55. chython/algorithms/tautomers/keto_enol.py +148 -0
  56. chython/algorithms/tautomers/test/__init__.py +18 -0
  57. chython/algorithms/tautomers/test/test_tautomers.py +80 -0
  58. chython/algorithms/test/__init__.py +18 -0
  59. chython/algorithms/test/test_isomorphism.py +58 -0
  60. chython/algorithms/test/test_smiles.py +76 -0
  61. chython/algorithms/x3dom.py +355 -0
  62. chython/containers/__init__.py +43 -0
  63. chython/containers/_pack_v2.cp312-win_amd64.pyd +0 -0
  64. chython/containers/_pack_v2.pyx +271 -0
  65. chython/containers/_unpack_v0v2.cp312-win_amd64.pyd +0 -0
  66. chython/containers/_unpack_v0v2.pyx +300 -0
  67. chython/containers/bonds.py +255 -0
  68. chython/containers/cgr.py +115 -0
  69. chython/containers/graph.py +200 -0
  70. chython/containers/molecule.py +695 -0
  71. chython/containers/query.py +66 -0
  72. chython/containers/reaction.py +324 -0
  73. chython/exceptions.py +114 -0
  74. chython/files/MRVrw.py +523 -0
  75. chython/files/PDBrw.py +257 -0
  76. chython/files/RDFrw.py +298 -0
  77. chython/files/SDFrw.py +221 -0
  78. chython/files/__init__.py +29 -0
  79. chython/files/_convert.py +207 -0
  80. chython/files/_mapping.py +117 -0
  81. chython/files/_xyz.cp312-win_amd64.pyd +0 -0
  82. chython/files/_xyz.pyx +74 -0
  83. chython/files/daylight/__init__.py +24 -0
  84. chython/files/daylight/parser.py +157 -0
  85. chython/files/daylight/smarts.py +107 -0
  86. chython/files/daylight/smiles.py +245 -0
  87. chython/files/daylight/test/__init__.py +18 -0
  88. chython/files/daylight/test/test_daylight_smarts.py +289 -0
  89. chython/files/daylight/test/test_daylight_smiles.py +101 -0
  90. chython/files/daylight/test/test_parser.py +118 -0
  91. chython/files/daylight/test/test_tokenize.py +77 -0
  92. chython/files/daylight/tokenize.py +376 -0
  93. chython/files/libinchi/__init__.py +22 -0
  94. chython/files/libinchi/libinchi.dll +0 -0
  95. chython/files/libinchi/wrapper.py +555 -0
  96. chython/files/mdl/__init__.py +25 -0
  97. chython/files/mdl/emol.py +209 -0
  98. chython/files/mdl/erxn.py +67 -0
  99. chython/files/mdl/mol.py +144 -0
  100. chython/files/mdl/read.py +225 -0
  101. chython/files/mdl/rxn.py +67 -0
  102. chython/files/mdl/stereo.py +63 -0
  103. chython/files/mdl/write.py +165 -0
  104. chython/files/xyz.py +78 -0
  105. chython/periodictable/__init__.py +69 -0
  106. chython/periodictable/base/__init__.py +25 -0
  107. chython/periodictable/base/dynamic.py +149 -0
  108. chython/periodictable/base/element.py +452 -0
  109. chython/periodictable/base/groups.py +90 -0
  110. chython/periodictable/base/periods.py +46 -0
  111. chython/periodictable/base/query.py +473 -0
  112. chython/periodictable/base/vector.py +119 -0
  113. chython/periodictable/groupI.py +252 -0
  114. chython/periodictable/groupII.py +223 -0
  115. chython/periodictable/groupIII.py +1154 -0
  116. chython/periodictable/groupIV.py +210 -0
  117. chython/periodictable/groupIX.py +196 -0
  118. chython/periodictable/groupV.py +192 -0
  119. chython/periodictable/groupVI.py +183 -0
  120. chython/periodictable/groupVII.py +162 -0
  121. chython/periodictable/groupVIII.py +161 -0
  122. chython/periodictable/groupX.py +166 -0
  123. chython/periodictable/groupXI.py +164 -0
  124. chython/periodictable/groupXII.py +158 -0
  125. chython/periodictable/groupXIII.py +239 -0
  126. chython/periodictable/groupXIV.py +262 -0
  127. chython/periodictable/groupXV.py +276 -0
  128. chython/periodictable/groupXVI.py +457 -0
  129. chython/periodictable/groupXVII.py +324 -0
  130. chython/periodictable/groupXVIII.py +260 -0
  131. chython/reactor/__init__.py +24 -0
  132. chython/reactor/base.py +212 -0
  133. chython/reactor/deprotection.py +565 -0
  134. chython/reactor/groups.py +128 -0
  135. chython/reactor/reactions/__init__.py +157 -0
  136. chython/reactor/reactions/_amidation.py +58 -0
  137. chython/reactor/reactions/_amine_isocyanate.py +52 -0
  138. chython/reactor/reactions/_buchwald_hartwig.py +50 -0
  139. chython/reactor/reactions/_esterification.py +49 -0
  140. chython/reactor/reactions/_macmillan.py +43 -0
  141. chython/reactor/reactions/_reductive_amination.py +50 -0
  142. chython/reactor/reactions/_sonogashira.py +49 -0
  143. chython/reactor/reactions/_sulfonamidation.py +52 -0
  144. chython/reactor/reactions/_suzuki_miyaura.py +88 -0
  145. chython/reactor/reactions/ufe.py +99 -0
  146. chython/reactor/reactor.py +170 -0
  147. chython/reactor/retro/__init__.py +77 -0
  148. chython/reactor/retro/_amidation.py +39 -0
  149. chython/reactor/retro/_aryl_amination.py +32 -0
  150. chython/reactor/retro/_mitsunobu.py +49 -0
  151. chython/reactor/retro/_sonogashira.py +49 -0
  152. chython/reactor/retro/_suzuki_miyaura.py +54 -0
  153. chython/reactor/scaffold.py +122 -0
  154. chython/reactor/test/__init__.py +18 -0
  155. chython/reactor/test/test_deprotection.py +57 -0
  156. chython/reactor/test/test_reactor.py +40 -0
  157. chython/reactor/test/test_scaffold.py +57 -0
  158. chython/reactor/test/test_transformer.py +40 -0
  159. chython/reactor/transformer.py +62 -0
  160. chython/utils/__init__.py +57 -0
  161. chython/utils/free_wilson.py +114 -0
  162. chython/utils/grid.py +130 -0
  163. chython/utils/rdkit.py +165 -0
  164. chython/utils/retro.py +139 -0
  165. chython/utils/svg.py +57 -0
  166. chython/utils/test/__init__.py +18 -0
  167. chython/utils/test/test_rdkit.py +71 -0
  168. chython-2.4.dist-info/LICENSE +165 -0
  169. chython-2.4.dist-info/METADATA +101 -0
  170. chython-2.4.dist-info/RECORD +171 -0
  171. chython-2.4.dist-info/WHEEL +4 -0
@@ -0,0 +1,1222 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright 2019-2024 Ramil Nugmanov <nougmanoff@protonmail.com>
4
+ # This file is part of chython.
5
+ #
6
+ # chython is free software; you can redistribute it and/or modify
7
+ # it under the terms of the GNU Lesser General Public License as published by
8
+ # the Free Software Foundation; either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU Lesser General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU Lesser General Public License
17
+ # along with this program; if not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ from collections import defaultdict
20
+ from functools import cached_property
21
+ from itertools import combinations, product
22
+ from logging import getLogger, INFO
23
+ from typing import Dict, Set, Tuple, Union, List, Optional, TYPE_CHECKING
24
+ from .morgan import _morgan
25
+ from ..exceptions import AtomNotFound, IsChiral, NotChiral
26
+
27
+
28
+ logger = getLogger('chython.stereo')
29
+ logger.setLevel(INFO)
30
+
31
+
32
+ if TYPE_CHECKING:
33
+ from chython import MoleculeContainer
34
+
35
+
36
+ # atomic number constants
37
+ H = 1
38
+ C = 6
39
+
40
+ # 1 2
41
+ # \ |
42
+ # \|
43
+ # n---3
44
+ # /
45
+ # /
46
+ # 0
47
+ _tetrahedron_translate = {(0, 1, 2): False, (1, 2, 0): False, (2, 0, 1): False,
48
+ (0, 2, 1): True, (1, 0, 2): True, (2, 1, 0): True,
49
+ (0, 3, 1): False, (3, 1, 0): False, (1, 0, 3): False,
50
+ (0, 1, 3): True, (1, 3, 0): True, (3, 0, 1): True,
51
+ (0, 2, 3): False, (2, 3, 0): False, (3, 0, 2): False,
52
+ (0, 3, 2): True, (3, 2, 0): True, (2, 0, 3): True,
53
+ (1, 3, 2): False, (3, 2, 1): False, (2, 1, 3): False,
54
+ (1, 2, 3): True, (2, 3, 1): True, (3, 1, 2): True}
55
+ # 2 1
56
+ # \ /
57
+ # n---m
58
+ # / \
59
+ # 0 3
60
+ _alkene_translate = {(0, 1): False, (1, 0): False, (0, 3): True, (3, 0): True,
61
+ (2, 3): False, (3, 2): False, (2, 1): True, (1, 2): True}
62
+
63
+
64
+ def _pyramid_sign(n, u, v, w):
65
+ #
66
+ # | n /
67
+ # | |\
68
+ # | | \
69
+ # | /| \
70
+ # | / u---v
71
+ # |/___\_/___
72
+ # w
73
+ #
74
+ nx, ny, nz = n
75
+ ux, uy, uz = u
76
+ vx, vy, vz = v
77
+ wx, wy, wz = w
78
+
79
+ q1x = ux - nx
80
+ q1y = uy - ny
81
+ q1z = uz - nz
82
+ q2x = vx - nx
83
+ q2y = vy - ny
84
+ q2z = vz - nz
85
+ q3x = wx - nx
86
+ q3y = wy - ny
87
+ q3z = wz - nz
88
+
89
+ vol = q1x * (q2y * q3z - q2z * q3y) + q1y * (q2z * q3x - q2x * q3z) + q1z * (q2x * q3y - q2y * q3x)
90
+ if vol > 0:
91
+ return 1
92
+ elif vol < 0:
93
+ return -1
94
+ return 0
95
+
96
+
97
+ def _cis_trans_sign(n, u, v, w):
98
+ # n w
99
+ # \ /
100
+ # u--v
101
+ # / \
102
+ # x x
103
+ nx, ny = n
104
+ ux, uy = u
105
+ vx, vy = v
106
+ wx, wy = w
107
+
108
+ q1x = ux - nx
109
+ q1y = uy - ny
110
+ q2x = vx - ux
111
+ q2y = vy - uy
112
+ q3x = wx - vx
113
+ q3y = wy - vy
114
+
115
+ # cross vectors
116
+ q1q2z = q1x * q2y - q1y * q2x
117
+ q2q3z = q2x * q3y - q2y * q3x
118
+
119
+ dot = q1q2z * q2q3z
120
+ if dot > 0:
121
+ return 1
122
+ elif dot < 0:
123
+ return -1
124
+ return 0
125
+
126
+
127
+ def _allene_sign(mark, u, v, w):
128
+ # n w
129
+ # | /
130
+ # u--v
131
+ ux, uy = u
132
+ vx, vy = v
133
+ wx, wy = w
134
+
135
+ q2x = vx - ux
136
+ q2y = vy - uy
137
+ q3x = wx - vx
138
+ q3y = wy - vy
139
+
140
+ # cross vectors
141
+ q2q3z = q2x * q3y - q2y * q3x
142
+
143
+ dot = -mark * q2q3z
144
+ if dot > 0:
145
+ return 1
146
+ elif dot < 0:
147
+ return -1
148
+ return 0
149
+
150
+
151
+ class MoleculeStereo:
152
+ __slots__ = ()
153
+
154
+ def clean_stereo(self: 'MoleculeContainer'):
155
+ """
156
+ Remove stereo data.
157
+ """
158
+ for _, a in self.atoms():
159
+ a._stereo = None
160
+ for *_, b in self.bonds():
161
+ b._stereo = None
162
+ self.flush_cache(keep_sssr=True, keep_components=True)
163
+
164
+ @cached_property
165
+ def tetrahedrons(self: 'MoleculeContainer') -> Tuple[int, ...]:
166
+ """
167
+ Carbon sp3 atom numbers.
168
+ """
169
+ tetra = []
170
+ for n, atom in self.atoms():
171
+ if atom == C and not atom.charge and not atom.is_radical:
172
+ env = self._bonds[n]
173
+ if all(b == 1 for b in env.values()):
174
+ if sum(int(b) for b in env.values()) > 4:
175
+ continue
176
+ tetra.append(n)
177
+ return tuple(tetra)
178
+
179
+ @cached_property
180
+ def cumulenes(self: 'MoleculeContainer') -> List[Tuple[int, ...]]:
181
+ """
182
+ All double-bonds chains (e.g. alkenes, allenes, cumulenes).
183
+ """
184
+ atoms = self._atoms
185
+ bonds = self._bonds
186
+
187
+ adj = defaultdict(set) # double bonds adjacency matrix
188
+ for n, atom in atoms.items():
189
+ if atom.is_forming_double_bonds:
190
+ adj_n = adj[n].add
191
+ for m, bond in bonds[n].items():
192
+ if bond == 2 and atoms[m].is_forming_double_bonds:
193
+ adj_n(m)
194
+ if not adj:
195
+ return []
196
+
197
+ terminals = [x for x, y in adj.items() if len(y) == 1] # list to keep atoms order!
198
+ cumulenes = []
199
+ while terminals:
200
+ n = terminals.pop(0)
201
+ m = adj[n].pop()
202
+ path = [n, m]
203
+ while m not in terminals:
204
+ if len(bonds[m]) > 2: # not cumulene. SO3, SO4- etc.
205
+ cumulenes.extend(zip(path, path[1:])) # keep single double bonds instead of cumulene chain.
206
+ break
207
+ adj_m = adj[m]
208
+ adj_m.discard(n)
209
+ n, m = m, adj_m.pop()
210
+ path.append(m)
211
+ else:
212
+ terminals.remove(m)
213
+ adj[m].pop()
214
+ cumulenes.append(tuple(path))
215
+ return cumulenes
216
+
217
+ @cached_property
218
+ def stereogenic_tetrahedrons(self: 'MoleculeContainer') -> Dict[int, Union[Tuple[int, int, int], Tuple[int, int, int, int]]]:
219
+ """
220
+ Tetrahedrons which contains at least 3 non-hydrogen neighbors and corresponding neighbors order.
221
+ """
222
+ # 2
223
+ # |
224
+ # 1--K--3
225
+ # |
226
+ # 4?
227
+ atoms = self._atoms
228
+ bonds = self._bonds
229
+ tetrahedrons = {}
230
+ for n in self.tetrahedrons:
231
+ if any(not atoms[x].is_forming_single_bonds for x in bonds[n]):
232
+ continue # skip metal-carbon complexes
233
+ env = tuple(x for x in bonds[n] if atoms[x] != H)
234
+ if len(env) in (3, 4):
235
+ tetrahedrons[n] = env
236
+ return tetrahedrons
237
+
238
+ @cached_property
239
+ def stereogenic_cumulenes(self: 'MoleculeContainer') -> Dict[Tuple[int, ...], Tuple[int, int, Optional[int], Optional[int]]]:
240
+ """
241
+ Cumulenes which contains at least one non-hydrogen neighbor on both ends and corresponding neighbors order.
242
+ """
243
+ # 5 4
244
+ # \ /
245
+ # 2---3
246
+ # / \
247
+ # 1 6
248
+ bonds = self._bonds
249
+ atoms = self._atoms
250
+ cumulenes = {}
251
+ for path in self.cumulenes:
252
+ nf = bonds[path[0]]
253
+ nl = bonds[path[-1]]
254
+ n1, m1 = path[1], path[-2]
255
+ if any(b == 3 or not atoms[m].is_forming_single_bonds and b != 8
256
+ for m, b in nf.items() if m != n1):
257
+ continue # skip X=C=C structures and metal-carbon complexes
258
+ if any(b == 3 or not atoms[m].is_forming_single_bonds and b != 8
259
+ for m, b in nl.items() if m != m1):
260
+ continue # skip X=C=C structures and metal-carbon complexes
261
+ nn = [x for x, b in nf.items() if x != n1 and atoms[x] != H and b != 8]
262
+ mn = [x for x, b in nl.items() if x != m1 and atoms[x] != H and b != 8]
263
+ if nn and mn:
264
+ sn = nn[1] if len(nn) == 2 else None
265
+ sm = mn[1] if len(mn) == 2 else None
266
+ cumulenes[path] = (nn[0], mn[0], sn, sm)
267
+ return cumulenes
268
+
269
+ @cached_property
270
+ def stereogenic_allenes(self) -> Dict[int, Tuple[int, int, Optional[int], Optional[int]]]:
271
+ """
272
+ Allenes which contains at least one non-hydrogen neighbor on both ends and corresponding neighbors order.
273
+ """
274
+ return {path[len(path) // 2]: env for path, env in self.stereogenic_cumulenes.items() if len(path) % 2}
275
+
276
+ @cached_property
277
+ def stereogenic_cis_trans(self) -> Dict[Tuple[int, int], Tuple[int, int, Optional[int], Optional[int]]]:
278
+ """
279
+ Cis-trans bonds which contains at least one non-hydrogen neighbor on both ends and corresponding neighbors order.
280
+ """
281
+ stereo = {}
282
+ for path, env in self.stereogenic_cumulenes.items():
283
+ if len(path) % 2:
284
+ continue
285
+ stereo[(path[0], path[-1])] = env
286
+ return stereo
287
+
288
+ @cached_property
289
+ def ring_tetrahedrons(self: 'MoleculeContainer') -> Dict[int, Union[Tuple[int, int], Tuple[int], Tuple]]:
290
+ """
291
+ Tetrahedrons in rings, except ring-linkers. Values are non-ring atoms.
292
+ """
293
+ out = {}
294
+ atoms_rings = self.atoms_rings
295
+ tetrahedrons = self.stereogenic_tetrahedrons
296
+ points = self.rings_linker_tetrahedrons
297
+ environment = self.not_special_connectivity
298
+ for n, r in atoms_rings.items():
299
+ if n in tetrahedrons and n not in points:
300
+ out[n] = tuple(environment[n].difference(atoms_rings))
301
+ return out
302
+
303
+ @cached_property
304
+ def rings_linker_tetrahedrons(self: 'MoleculeContainer') -> Dict[int, Tuple[int, int, int, int]]:
305
+ """
306
+ A dictionary where the keys are tetrahedron atoms shared between two rings (not condensed rings) and the values
307
+ are tuples representing their neighbors in the first and second rings respectively.
308
+ """
309
+ out = {}
310
+ tetrahedrons = self.stereogenic_tetrahedrons
311
+ for n, r in self.atoms_rings.items():
312
+ if n in tetrahedrons:
313
+ for nr, mr in combinations(r, 2):
314
+ if len(set(nr).intersection(mr)) == 1:
315
+ ni = nr.index(n)
316
+ mi = mr.index(n)
317
+ out[n] = (nr[ni - 1], nr[ni - len(nr) + 1], mr[mi - 1], mr[mi - len(mr) + 1])
318
+ break
319
+ return out
320
+
321
+ @cached_property
322
+ def ring_cumulenes_terminals(self: 'MoleculeContainer') -> Set[Tuple[int, int]]:
323
+ """
324
+ Terminal atoms of inside ring cumulenes.
325
+ """
326
+ out = set()
327
+ ar = self.atoms_rings
328
+ for n, *_, m in self.stereogenic_cumulenes:
329
+ if n in ar and m in ar and not set(ar[n]).isdisjoint(ar[m]):
330
+ out.add((n, m))
331
+ return out
332
+
333
+ @cached_property
334
+ def rings_linker_cumulenes_terminals(self: 'MoleculeContainer') -> Dict[Tuple[int, int], Tuple[int, int, int, int]]:
335
+ """
336
+ Terminal atoms of cumulenes connecting two rings. Values are neighbors in first and second rings.
337
+ """
338
+ out = {}
339
+ ar = self.atoms_rings
340
+ chord = self.ring_cumulenes_terminals
341
+ for (n, *_, m), (n1, m1, n2, m2) in self.stereogenic_cumulenes.items():
342
+ if n in ar and m in ar and (n, m) not in chord:
343
+ out[(n, m)] = (n1, n2, m1, m2)
344
+ return out
345
+
346
+ @cached_property
347
+ def ring_attached_cumulenes(self: 'MoleculeContainer') -> Dict[Tuple[int, int], Union[Tuple[int, int], Tuple[int]]]:
348
+ """
349
+ Cumulenes attached to rings from one side. Values are out of ring neighbor atoms.
350
+ """
351
+ ar = self.atoms_rings
352
+ out = {}
353
+ for (n, *_, m), (n1, m1, n2, m2) in self.stereogenic_cumulenes.items():
354
+ if n in ar:
355
+ if m in ar:
356
+ continue
357
+ if m2:
358
+ out[(n, m)] = (m1, m2)
359
+ else:
360
+ out[(n, m)] = (m1,)
361
+ elif m in ar:
362
+ if n2:
363
+ out[(n, m)] = (n1, n2)
364
+ else:
365
+ out[(n, m)] = (n1,)
366
+ return out
367
+
368
+ @property
369
+ def chiral_tetrahedrons(self) -> Set[int]:
370
+ """
371
+ Chiral tetrahedrons except already labeled ones.
372
+ """
373
+ return self.__chiral_centers[0]
374
+
375
+ @property
376
+ def chiral_cis_trans(self) -> Set[Tuple[int, int]]:
377
+ """
378
+ Chiral cis-trans bonds except already labeled ones.
379
+ """
380
+ return self.__chiral_centers[1]
381
+
382
+ @property
383
+ def chiral_allenes(self) -> Set[int]:
384
+ """
385
+ Chiral allenes except already labeled ones.
386
+ """
387
+ return self.__chiral_centers[2]
388
+
389
+ def add_wedge(self: 'MoleculeContainer', n: int, m: int, mark: int, *, clean_cache=True):
390
+ """
391
+ Add stereo data by wedge notation of bonds. Use it for tetrahedrons of allenes.
392
+
393
+ :param n: number of atom from which wedge bond started
394
+ :param m: number of atom to which wedge bond coming
395
+ :param mark: up bond is 1, down is -1
396
+ """
397
+ atoms = self._atoms
398
+ if n not in atoms or m not in atoms or m not in self._bonds[n]:
399
+ raise AtomNotFound
400
+ elif atoms[n].stereo is not None:
401
+ raise IsChiral
402
+ elif c := self._stereo_allenes_centers.get(n):
403
+ # allenes
404
+ if atoms[c].stereo is not None:
405
+ raise IsChiral
406
+ elif c not in self.chiral_allenes:
407
+ raise NotChiral
408
+
409
+ t1, t2 = self._stereo_allenes_terminals[c]
410
+ order = self.stereogenic_allenes[c]
411
+ if atoms[m] == H:
412
+ if t1 == n:
413
+ m1 = order[1]
414
+ else:
415
+ t1, t2 = t2, t1
416
+ m1 = order[0]
417
+ r = True
418
+ else:
419
+ w = order.index(m)
420
+ if w == 0:
421
+ m1 = order[1]
422
+ r = False
423
+ elif w == 1:
424
+ m1 = order[0]
425
+ t1, t2 = t2, t1
426
+ r = False
427
+ elif w == 2:
428
+ m1 = order[1]
429
+ r = True
430
+ else:
431
+ m1 = order[0]
432
+ t1, t2 = t2, t1
433
+ r = True
434
+ if s := _allene_sign(mark, atoms[t1].xy, atoms[t2].xy, atoms[m1].xy):
435
+ atoms[c]._stereo = s < 0 if r else s > 0
436
+ if clean_cache:
437
+ self.flush_cache(keep_sssr=True, keep_components=True)
438
+ # tetrahedrons
439
+ elif n in self.chiral_tetrahedrons:
440
+ th = self.stereogenic_tetrahedrons[n]
441
+ am = atoms[m]
442
+ if am == H:
443
+ order = []
444
+ for x in th:
445
+ ax = atoms[x]
446
+ order.append((ax.x, ax.y, 0))
447
+ s = _pyramid_sign((am.x, am.y, mark), *order)
448
+ else:
449
+ order = []
450
+ for x in th:
451
+ ax = atoms[x]
452
+ order.append((ax.x, ax.y, mark if x == m else 0))
453
+ if len(order) == 3:
454
+ if len(self._bonds[n]) == 4: # explicit hydrogen
455
+ x = next(x for x in self._bonds[n] if x not in th)
456
+ ax = atoms[x]
457
+ s = _pyramid_sign((ax.x, ax.y, 0), *order)
458
+ else:
459
+ an = atoms[n]
460
+ s = _pyramid_sign((an.x, an.y, 0), *order)
461
+ else:
462
+ s = _pyramid_sign(order[-1], *order[:3])
463
+ if s:
464
+ atoms[n]._stereo = s > 0
465
+ if clean_cache:
466
+ self.flush_cache(keep_components=True, keep_sssr=True)
467
+ else:
468
+ raise NotChiral
469
+
470
+ def calculate_cis_trans_from_2d(self: 'MoleculeContainer', *, clean_cache=True):
471
+ """
472
+ Calculate cis-trans stereo bonds from given 2d coordinates. Unusable for SMILES and INCHI.
473
+ """
474
+ atoms = self._atoms
475
+ flag = False
476
+ while self.chiral_cis_trans:
477
+ stereo = False
478
+ for nm in self.chiral_cis_trans:
479
+ n, m = nm
480
+ n1, m1, *_ = self.stereogenic_cis_trans[nm]
481
+ s = _cis_trans_sign(atoms[n1].xy, atoms[n].xy, atoms[m].xy, atoms[m1].xy)
482
+ if s:
483
+ stereo = True
484
+ i, j = self._stereo_cis_trans_centers[n]
485
+ self._bonds[i][j]._stereo = s > 0
486
+ if stereo:
487
+ flag = True
488
+ self.flush_stereo_cache()
489
+ else:
490
+ break
491
+ if flag and clean_cache:
492
+ self.flush_cache(keep_components=True, keep_sssr=True)
493
+
494
+ def add_atom_stereo(self: 'MoleculeContainer', n: int, env: Tuple[int, ...], mark: bool, *, clean_cache=True):
495
+ """
496
+ Add stereo data for specified neighbors bypass. Use it for tetrahedrons or allenes.
497
+
498
+ :param n: number of tetrahedron atom or central atom of allene.
499
+ :param env: numbers of atoms with specified bypass
500
+ :param mark: clockwise or anti bypass.
501
+
502
+ See <https://www.daylight.com/dayhtml/doc/theory/theory.smiles.html> and <http://opensmiles.org/opensmiles.html>
503
+ """
504
+ try:
505
+ atom = self._atoms[n]
506
+ except KeyError:
507
+ raise AtomNotFound
508
+ if atom.stereo is not None:
509
+ raise IsChiral
510
+ if not isinstance(mark, bool):
511
+ raise TypeError('stereo mark should be bool')
512
+
513
+ if n in self.chiral_tetrahedrons:
514
+ atom._stereo = self._translate_tetrahedron_sign(n, env, mark)
515
+ if clean_cache:
516
+ self.flush_cache(keep_components=True, keep_sssr=True)
517
+ elif n in self.chiral_allenes:
518
+ atom._stereo = self._translate_allene_sign(n, *env, mark)
519
+ if clean_cache:
520
+ self.flush_cache(keep_components=True, keep_sssr=True)
521
+ else: # only tetrahedrons supported
522
+ raise NotChiral
523
+
524
+ def add_cis_trans_stereo(self: 'MoleculeContainer', n: int, m: int, n1: int, n2: int, mark: bool, *,
525
+ clean_cache=True):
526
+ """
527
+ Add stereo data to cis-trans double bonds (not allenes).
528
+
529
+ n1/n=m/n2
530
+
531
+ :param n: number of starting atom of double bonds chain (alkenes of cumulenes)
532
+ :param m: number of ending atom of double bonds chain (alkenes of cumulenes)
533
+ :param n1: number of neighboring atom of starting atom
534
+ :param n2: number of neighboring atom of ending atom
535
+ :param mark: cis or trans
536
+
537
+ See <https://www.daylight.com/dayhtml/doc/theory/theory.smiles.html> and <http://opensmiles.org/opensmiles.html
538
+ """
539
+ atoms = self._atoms
540
+ if n not in atoms or m not in atoms or n1 not in atoms or n2 not in atoms:
541
+ raise AtomNotFound
542
+ if not isinstance(mark, bool):
543
+ raise TypeError('stereo mark should be bool')
544
+
545
+ if n not in self._stereo_cis_trans_counterpart or self._stereo_cis_trans_counterpart[n] != m:
546
+ raise NotChiral
547
+ i, j = self._stereo_cis_trans_centers[n]
548
+ if self._bonds[i][j].stereo is not None:
549
+ raise IsChiral
550
+
551
+ if (n, m) in self.chiral_cis_trans:
552
+ self._bonds[i][j]._stereo = self._translate_cis_trans_sign(n, m, n1, n2, mark)
553
+ if clean_cache:
554
+ self.flush_cache(keep_components=True, keep_sssr=True)
555
+ elif (m, n) in self.chiral_cis_trans:
556
+ self._bonds[i][j]._stereo = self._translate_cis_trans_sign(m, n, n2, n1, mark)
557
+ if clean_cache:
558
+ self.flush_cache(keep_components=True, keep_sssr=True)
559
+ else:
560
+ raise NotChiral
561
+
562
+ def flush_stereo_cache(self):
563
+ """
564
+ Flush chiral morgan and chiral centers cache.
565
+ """
566
+ self.__dict__.pop('_chiral_morgan', None)
567
+ self.__dict__.pop('_MoleculeStereo__chiral_centers', None)
568
+
569
+ def fix_stereo(self: 'MoleculeContainer'):
570
+ """
571
+ Reset stereo marks.
572
+ """
573
+ stereo_tetrahedrons = self.stereogenic_tetrahedrons
574
+ stereo_allenes = self.stereogenic_allenes
575
+ stereo_cis_trans = self._stereo_cis_trans_terminals
576
+ atoms_stereo = []
577
+ allenes_stereo = []
578
+ cis_trans_stereo = []
579
+ for n, a in self.atoms():
580
+ if a.stereo is None:
581
+ continue
582
+ elif n in stereo_tetrahedrons:
583
+ atoms_stereo.append((n, a, a.stereo))
584
+ elif n in stereo_allenes:
585
+ allenes_stereo.append((n, a, a.stereo))
586
+ a._stereo = None # flush stereo label
587
+
588
+ for n, m, b in self.bonds():
589
+ if b.stereo is None:
590
+ continue
591
+ elif ta := stereo_cis_trans.get(n):
592
+ cis_trans_stereo.append((ta, b, b.stereo))
593
+ b._stereo = None # flush stereo label
594
+ self.flush_stereo_cache()
595
+
596
+ old_stereo = len(atoms_stereo) + len(allenes_stereo) + len(cis_trans_stereo)
597
+ while old_stereo:
598
+ chiral_tetrahedrons = self.chiral_tetrahedrons
599
+ chiral_allenes = self.chiral_allenes
600
+ chiral_cis_trans = self.chiral_cis_trans
601
+
602
+ # filter out resolved
603
+ tmp = []
604
+ for n, a, s in atoms_stereo:
605
+ if n in chiral_tetrahedrons:
606
+ a._stereo = s # restore stereo
607
+ else:
608
+ tmp.append((n, a, s))
609
+ atoms_stereo = tmp
610
+
611
+ tmp = []
612
+ for n, a, s in allenes_stereo:
613
+ if n in chiral_allenes:
614
+ a._stereo = s # restore stereo
615
+ else:
616
+ tmp.append((n, a, s))
617
+ allenes_stereo = tmp
618
+
619
+ tmp = []
620
+ for ta, b, s in cis_trans_stereo:
621
+ if ta in chiral_cis_trans:
622
+ b._stereo = s
623
+ else:
624
+ tmp.append((ta, b, s))
625
+ cis_trans_stereo = tmp
626
+
627
+ fail_stereo = len(atoms_stereo) + len(allenes_stereo) + len(cis_trans_stereo)
628
+ if fail_stereo == old_stereo:
629
+ break
630
+ old_stereo = fail_stereo
631
+ self.flush_stereo_cache()
632
+
633
+ @cached_property
634
+ def _cis_trans_count(self) -> int:
635
+ return sum(b.stereo is not None for *_, b in self.bonds())
636
+
637
+ @cached_property
638
+ def _stereo_cis_trans_centers(self) -> Dict[int, Tuple[int, int]]:
639
+ """
640
+ Cis-Trans terminal atoms to cis-trans key mapping. Key is central double bond in a cumulene chain.
641
+ """
642
+ terminals = {}
643
+ for path in self.stereogenic_cumulenes:
644
+ if len(path) % 2:
645
+ continue
646
+ n, m = path[0], path[-1]
647
+ i = len(path) // 2
648
+ terminals[n] = terminals[m] = (path[i - 1], path[i])
649
+ return terminals
650
+
651
+ @cached_property
652
+ def _stereo_cis_trans_terminals(self) -> Dict[int, Tuple[int, int]]:
653
+ """
654
+ Cis-Trans terminal and central atoms to terminal pair mapping.
655
+ """
656
+ terminals = {}
657
+ for path in self.stereogenic_cumulenes:
658
+ if len(path) % 2:
659
+ continue
660
+ n, m = path[0], path[-1]
661
+ i = len(path) // 2
662
+ terminals[n] = terminals[m] = terminals[path[i]] = terminals[path[i - 1]] = (n, m)
663
+ return terminals
664
+
665
+ @cached_property
666
+ def _stereo_cis_trans_counterpart(self) -> Dict[int, int]:
667
+ """
668
+ Cis-Trans terminal atoms counterparts
669
+ """
670
+ counterpart = {}
671
+ for path in self.stereogenic_cumulenes:
672
+ if len(path) % 2:
673
+ continue
674
+ n, m = path[0], path[-1]
675
+ counterpart[n] = m
676
+ counterpart[m] = n
677
+ return counterpart
678
+
679
+ @cached_property
680
+ def _stereo_allenes_centers(self) -> Dict[int, int]:
681
+ """
682
+ Allene terminal atom to center mapping
683
+ """
684
+ terminals = {}
685
+ for c, (n, m) in self._stereo_allenes_terminals.items():
686
+ terminals[n] = terminals[m] = c
687
+ return terminals
688
+
689
+ @cached_property
690
+ def _stereo_allenes_terminals(self) -> Dict[int, Tuple[int, int]]:
691
+ """
692
+ Allene center atom to terminals mapping
693
+ """
694
+ return {path[len(path) // 2]: (path[0], path[-1]) for path in self.stereogenic_cumulenes if len(path) % 2}
695
+
696
+ def _translate_tetrahedron_sign(self: 'MoleculeContainer', n, env, s=None):
697
+ """
698
+ Get sign of chiral tetrahedron atom for specified neighbors order
699
+
700
+ :param n: stereo atom
701
+ :param env: neighbors order
702
+ :param s: if None, use existing sign else translate given to molecule
703
+ """
704
+ if s is None:
705
+ s = self._atoms[n].stereo
706
+ if s is None:
707
+ raise KeyError
708
+
709
+ order = self.stereogenic_tetrahedrons[n]
710
+ if len(order) == 3:
711
+ if len(env) == 4: # hydrogen atom passed to env
712
+ # hydrogen always last in order
713
+ try:
714
+ order = (*order, next(x for x in env if self._atoms[x] == H)) # see translate scheme
715
+ except StopIteration:
716
+ raise KeyError
717
+ elif len(env) != 3: # pyramid or tetrahedron expected
718
+ raise ValueError('invalid atoms list')
719
+ elif len(env) not in (3, 4): # pyramid or tetrahedron expected
720
+ raise ValueError('invalid atoms list')
721
+
722
+ translate = tuple(order.index(x) for x in env[:3])
723
+ if _tetrahedron_translate[translate]:
724
+ return not s
725
+ return s
726
+
727
+ def _translate_cis_trans_sign(self: 'MoleculeContainer', n, m, nn, nm, s=None):
728
+ """
729
+ Get sign for specified opposite neighbors
730
+
731
+ :param n: first double bonded atom
732
+ :param m: last double bonded atom
733
+ :param nn: neighbor of first atom
734
+ :param nm: neighbor of last atom
735
+ :param s: if None, use existing sign else translate given to molecule
736
+ """
737
+ try:
738
+ n0, n1, n2, n3 = self.stereogenic_cis_trans[(n, m)]
739
+ except KeyError:
740
+ n0, n1, n2, n3 = self.stereogenic_cis_trans[(m, n)]
741
+ n, m = m, n # in alkenes sign not order depended
742
+ nn, nm = nm, nn
743
+
744
+ if s is None:
745
+ i, j = self._stereo_cis_trans_centers[n]
746
+ s = self._bonds[i][j].stereo
747
+ if s is None:
748
+ raise KeyError
749
+
750
+ if nn == n0: # same start
751
+ t0 = 0
752
+ if nm == n1:
753
+ t1 = 1
754
+ elif nm == n3 or n3 is None and self._atoms[nm] == H:
755
+ t1 = 3
756
+ else:
757
+ raise KeyError
758
+ elif nn == n1:
759
+ t0 = 1
760
+ if nm == n0:
761
+ t1 = 0
762
+ elif nm == n2 or n2 is None and self._atoms[nm] == H:
763
+ t1 = 2
764
+ else:
765
+ raise KeyError
766
+ elif nn == n2 or n2 is None and self._atoms[nn] == H:
767
+ t0 = 2
768
+ if nm == n1:
769
+ t1 = 1
770
+ elif nm == n3 or n3 is None and self._atoms[nm] == H:
771
+ t1 = 3
772
+ else:
773
+ raise KeyError
774
+ elif nn == n3 or n3 is None and self._atoms[nn] == H:
775
+ t0 = 3
776
+ if nm == n0:
777
+ t1 = 0
778
+ elif nm == n2 or n2 is None and self._atoms[nm] == H:
779
+ t1 = 2
780
+ else:
781
+ raise KeyError
782
+ else:
783
+ raise KeyError
784
+
785
+ if _alkene_translate[(t0, t1)]:
786
+ return not s
787
+ return s
788
+
789
+ def _translate_allene_sign(self: 'MoleculeContainer', c, nn, nm, s=None):
790
+ """
791
+ get sign for specified opposite neighbors
792
+
793
+ :param c: central double bonded atom
794
+ :param nn: neighbor of first double bonded atom
795
+ :param nm: neighbor of last double bonded atom
796
+ :param s: if None, use existing sign else translate given to molecule
797
+ """
798
+ if s is None:
799
+ s = self._atoms[c].stereo
800
+ if s is None:
801
+ raise KeyError
802
+
803
+ n0, n1, n2, n3 = self.stereogenic_allenes[c]
804
+ if nn == n0: # same start
805
+ t0 = 0
806
+ if nm == n1:
807
+ t1 = 1
808
+ elif nm == n3 or n3 is None and self._atoms[nm] == H:
809
+ t1 = 3
810
+ else:
811
+ raise KeyError
812
+ elif nn == n1:
813
+ t0 = 1
814
+ if nm == n0:
815
+ t1 = 0
816
+ elif nm == n2 or n2 is None and self._atoms[nm] == H:
817
+ t1 = 2
818
+ else:
819
+ raise KeyError
820
+ elif nn == n2 or n2 is None and self._atoms[nn] == H:
821
+ t0 = 2
822
+ if nm == n1:
823
+ t1 = 1
824
+ elif nm == n3 or n3 is None and self._atoms[nm] == H:
825
+ t1 = 3
826
+ else:
827
+ raise KeyError
828
+ elif nn == n3 or n3 is None and self._atoms[nn] == H:
829
+ t0 = 3
830
+ if nm == n0:
831
+ t1 = 0
832
+ elif nm == n2 or n2 is None and self._atoms[nm] == H:
833
+ t1 = 2
834
+ else:
835
+ raise KeyError
836
+ else:
837
+ raise KeyError
838
+
839
+ if _alkene_translate[(t0, t1)]:
840
+ return not s
841
+ return s
842
+
843
+ @cached_property
844
+ def _wedge_map(self: Union['MoleculeContainer', 'MoleculeStereo']):
845
+ atoms = self._atoms
846
+
847
+ overlap = set()
848
+ space = []
849
+ solved = []
850
+ seen = set()
851
+ for n, env in self.stereogenic_allenes.items():
852
+ if atoms[n].stereo is None:
853
+ continue
854
+ term = self._stereo_allenes_terminals[n]
855
+ overlap.update(term) # don't allow incoming wedge to allenes terminals
856
+ orders = [(*env[:2], *term, n, True), (*env[1::-1], *term[::-1], n, True)]
857
+ if env[2]:
858
+ orders.append((env[2], env[1], *term, n, True))
859
+ if env[3]:
860
+ orders.append((env[3], env[0], *term[::-1], n, True))
861
+ space.append(orders)
862
+ for n, env in self.stereogenic_tetrahedrons.items():
863
+ if atoms[n].stereo is None:
864
+ continue
865
+ overlap.add(n) # don't allow incoming wedge to stereo tetrahedrons
866
+ order = list(env)
867
+ orders = [(*order, n, False)]
868
+ for _ in range(1, len(order)):
869
+ order = order.copy()
870
+ order.append(order.pop(0))
871
+ orders.append((*order, n, False))
872
+ space.append(orders)
873
+
874
+ while space:
875
+ ls = len(space)
876
+ unsolved = []
877
+ for orders in space:
878
+ good = []
879
+ if orders[0][-1]:
880
+ for x in orders:
881
+ x0 = x[0]
882
+ if x0 in seen or x0 not in overlap:
883
+ good.append(x)
884
+ seen.add(x[2])
885
+ if good:
886
+ solved.append(max(good, key=lambda x: (not atoms[x[0]].in_ring, atoms[x[0]].atomic_number)))
887
+ else:
888
+ unsolved.append(orders)
889
+ else:
890
+ for x in orders:
891
+ x0 = x[0]
892
+ if x0 in seen or x0 not in overlap:
893
+ good.append(x)
894
+ if good:
895
+ seen.add(x[-2])
896
+ solved.append(max(good, key=lambda x: (not atoms[x[0]].in_ring, atoms[x[0]].atomic_number)))
897
+ else:
898
+ unsolved.append(orders)
899
+ space = unsolved
900
+ if len(unsolved) == ls:
901
+ break
902
+
903
+ solved = [y for x in solved if (y := self.__wedge_sign(x))]
904
+ if not space:
905
+ return solved
906
+
907
+ for orders in product(*space):
908
+ used = set()
909
+ wedge = []
910
+ for order in orders:
911
+ if order[-1]: # allene
912
+ if (order[0], order[2]) in used:
913
+ break
914
+ used.add((order[2], order[0]))
915
+ wedge.append(self.__wedge_sign(order))
916
+ else: # TH
917
+ n = order[-2]
918
+ if (order[0], n) in used:
919
+ break
920
+ used.add((n, order[0]))
921
+ wedge.append(self.__wedge_sign(order))
922
+ else: # found
923
+ solved.extend(wedge)
924
+ return solved
925
+ logger.info('wedge stereo mapping failed')
926
+ return solved
927
+
928
+ def __wedge_sign(self: 'MoleculeContainer', order):
929
+ if order[-1]: # allene
930
+ s = self._translate_allene_sign(order[-2], order[0], order[1])
931
+ v = _allene_sign(1, self._atoms[order[2]].xy, self._atoms[order[3]].xy, self._atoms[order[1]].xy)
932
+ if not v:
933
+ logger.info(f'need 2d clean. allenes wedge stereo ambiguous for atom {order[-2]}')
934
+ if s:
935
+ return order[2], order[0], v
936
+ else:
937
+ return order[2], order[0], -v
938
+ else: # TH
939
+ n = order[-2]
940
+ s = self._translate_tetrahedron_sign(n, order[:-2])
941
+ # need recalculation if XY changed
942
+ ao0 = self._atoms[order[0]]
943
+ ao1 = self._atoms[order[1]]
944
+ ao2 = self._atoms[order[2]]
945
+ if len(order) == 5:
946
+ an = self._atoms[n]
947
+ v = _pyramid_sign((an.x, an.y, 0),
948
+ (ao0.x, ao0.y, 1),
949
+ (ao1.x, ao1.y, 0),
950
+ (ao2.x, ao2.y, 0))
951
+ else:
952
+ ao3 = self._atoms[order[3]]
953
+ v = _pyramid_sign((ao3.x, ao3.y, 0),
954
+ (ao0.x, ao0.y, 1),
955
+ (ao1.x, ao1.y, 0),
956
+ (ao2.x, ao2.y, 0))
957
+ if not v:
958
+ logger.info(f'need 2d clean. tetrahedron wedge stereo ambiguous for atom {n}')
959
+ if s:
960
+ return n, order[0], v
961
+ else:
962
+ return n, order[0], -v
963
+
964
+ @cached_property
965
+ def _chiral_morgan(self: Union['MoleculeContainer', 'MoleculeStereo']) -> Dict[int, int]:
966
+ stereo_atoms = {n for n, a in self.atoms() if a.stereo is not None}
967
+ stereo_bonds = {n for n, mb in self._bonds.items() if any(b.stereo is not None for m, b in mb.items())}
968
+ if not stereo_atoms and not stereo_bonds:
969
+ return self.atoms_order
970
+
971
+ morgan = self.atoms_order.copy()
972
+ atoms_stereo = stereo_atoms.intersection(self.tetrahedrons)
973
+ allenes_stereo = stereo_atoms - atoms_stereo
974
+
975
+ cis_trans_terminals = self._stereo_cis_trans_terminals
976
+ cis_trans_stereo = {cis_trans_terminals[n] for n in stereo_bonds}
977
+
978
+ while True:
979
+ # try iteratively differentiate stereo atoms.
980
+ morgan, atoms_stereo, cis_trans_stereo, allenes_stereo, atoms_groups, cis_trans_groups, allenes_groups = \
981
+ self.__differentiation(morgan, atoms_stereo, cis_trans_stereo, allenes_stereo)
982
+ if not atoms_groups and not cis_trans_groups and not allenes_groups:
983
+ break
984
+ # for some rings differentiation by morgan impossible. try randomly set new weights.
985
+ # sometimes this will lead to pseudo chiral centers and non-unique morgan.
986
+ for group in atoms_groups:
987
+ for n in group[:len(group) // 2]: # set new weight in half of group randomly.
988
+ morgan[n] = -morgan[n]
989
+ for group in cis_trans_groups:
990
+ for n, _ in group[:len(group) // 2]: # set new weight in half of group randomly.
991
+ morgan[n] = -morgan[n]
992
+ for group in allenes_groups:
993
+ for n in group[:len(group) // 2]: # set new weight in half of group randomly.
994
+ morgan[n] = -morgan[n]
995
+ morgan = _morgan(morgan, self.int_adjacency)
996
+ return morgan
997
+
998
+ @cached_property
999
+ def __chiral_centers(self: Union['MoleculeStereo', 'MoleculeContainer']):
1000
+ atoms_rings = self.atoms_rings
1001
+ tetrahedrons = self.stereogenic_tetrahedrons
1002
+ cis_trans = self.stereogenic_cis_trans
1003
+ allenes_centers = self._stereo_allenes_centers
1004
+ cis_trans_terminals = self._stereo_cis_trans_terminals
1005
+ cis_trans_centers = self._stereo_cis_trans_centers
1006
+ morgan = self._chiral_morgan
1007
+
1008
+ # find new chiral atoms and bonds.
1009
+ # tetrahedron is chiral if all its neighbors are unique.
1010
+ chiral_t = {n for n, env in tetrahedrons.items() if len({morgan[x] for x in env}) == len(env)}
1011
+ # tetrahedrons-linkers is chiral if in each rings neighbors are unique.
1012
+ chiral_t.update(n for n, (n1, n2, m1, m2) in self.rings_linker_tetrahedrons.items()
1013
+ if morgan[n1] != morgan[n2] and morgan[m1] != morgan[m2])
1014
+
1015
+ # required for axes detection.
1016
+ graph = {}
1017
+ stereogenic = set()
1018
+ pseudo = {}
1019
+
1020
+ # double bond is chiral if neighbors of each terminal atom is unique.
1021
+ # ring-linkers and rings-attached also takes into account.
1022
+ chiral_c = set()
1023
+ chiral_a = set()
1024
+ for path, (n1, m1, n2, m2) in self.stereogenic_cumulenes.items():
1025
+ if morgan[n1] != morgan.get(n2, 0) and morgan[m1] != morgan.get(m2, 0):
1026
+ n, m = path[0], path[-1]
1027
+ if len(path) % 2:
1028
+ chiral_a.add(path[len(path) // 2])
1029
+ else:
1030
+ chiral_c.add(n)
1031
+ stereogenic.add(n)
1032
+ stereogenic.add(m)
1033
+ # ring cumulenes always chiral. can be already added.
1034
+ for nm in self.ring_cumulenes_terminals:
1035
+ n, m = nm
1036
+ if any(len(x) < 8 for x in atoms_rings[n]): # skip small rings.
1037
+ if n in chiral_c: # remove already added small rings cumulenes.
1038
+ chiral_c.discard(n)
1039
+ if m in chiral_c:
1040
+ chiral_c.discard(m)
1041
+ elif n in allenes_centers and (c := allenes_centers[n]) in chiral_a:
1042
+ chiral_a.discard(c)
1043
+ continue
1044
+ elif nm in cis_trans:
1045
+ chiral_c.add(n)
1046
+ else:
1047
+ chiral_a.add(allenes_centers[n])
1048
+ pseudo[m] = n
1049
+ graph[n] = set()
1050
+ stereogenic.add(n)
1051
+
1052
+ # find chiral axes. build graph of stereogenic atoms in rings.
1053
+ # atoms connected then located in same ring or cumulene.
1054
+ for n, env in self.ring_tetrahedrons.items():
1055
+ if len(env) == 2: # one or zero non-ring neighbors stereogenic.
1056
+ n1, n2 = env
1057
+ if morgan[n1] == morgan[n2]: # only unique non-ring members required.
1058
+ continue
1059
+ graph[n] = set()
1060
+ stereogenic.add(n) # non-linker tetrahedrons in rings - stereogenic.
1061
+ for n, (n1, n2, m1, m2) in self.rings_linker_tetrahedrons.items():
1062
+ graph[n] = set()
1063
+ if morgan[n1] != morgan[n2] or morgan[m1] != morgan[m2]:
1064
+ stereogenic.add(n) # linkers with at least one unsymmetric ring.
1065
+ for n, m in self.rings_linker_cumulenes_terminals:
1066
+ graph[n] = {m}
1067
+ graph[m] = {n}
1068
+ # stereogenic atoms already found.
1069
+ for (n, m), env in self.ring_attached_cumulenes.items():
1070
+ if len(env) == 2:
1071
+ n1, n2 = env
1072
+ if morgan[n1] == morgan[n2]: # only unique non-ring members required.
1073
+ continue
1074
+ if n in atoms_rings:
1075
+ graph[n] = set() # non ring endpoints not required.
1076
+ stereogenic.add(n) # mark as stereogenic
1077
+ else:
1078
+ graph[m] = set()
1079
+ stereogenic.add(m)
1080
+
1081
+ if len(graph) > 1: # add bonds to graph. bonds connects atoms in same rings and terminal atoms of cumulenes.
1082
+ for n, ms in graph.items():
1083
+ for r in atoms_rings[n]:
1084
+ for m in r:
1085
+ if n == m:
1086
+ continue
1087
+ elif m in graph:
1088
+ ms.add(m)
1089
+ elif m in pseudo and (m := pseudo[m]) != n:
1090
+ ms.add(m)
1091
+ # remove not stereogenic terminals.
1092
+ while True:
1093
+ try:
1094
+ n = next(n for n, ms in graph.items() if not ms or len(ms) == 1 and n not in stereogenic)
1095
+ except StopIteration:
1096
+ break
1097
+ for m in graph.pop(n):
1098
+ graph[m].discard(n)
1099
+ # update chiral atoms.
1100
+ for n in graph:
1101
+ if n in tetrahedrons:
1102
+ chiral_t.add(n)
1103
+ elif n in allenes_centers:
1104
+ chiral_a.add(allenes_centers[n])
1105
+ else:
1106
+ chiral_c.add(n)
1107
+
1108
+ # skip already marked.
1109
+ stereo_atoms = {n for n, a in self.atoms() if a.stereo is not None}
1110
+ chiral_t.difference_update(stereo_atoms)
1111
+ chiral_a.difference_update(stereo_atoms)
1112
+ diff = set()
1113
+ for n in chiral_c:
1114
+ i, j = cis_trans_centers[n]
1115
+ if self._bonds[i][j].stereo is None:
1116
+ diff.add(cis_trans_terminals[n])
1117
+ return chiral_t, diff, chiral_a
1118
+
1119
+ def __differentiation(self: Union['MoleculeStereo', 'MoleculeContainer'], morgan,
1120
+ atoms_stereo, cis_trans_stereo, allenes_stereo):
1121
+ bonds = self.int_adjacency
1122
+
1123
+ tetrahedrons = self.stereogenic_tetrahedrons
1124
+ cis_trans = self.stereogenic_cis_trans
1125
+ allenes = self.stereogenic_allenes
1126
+
1127
+ translate_tetrahedron = self._translate_tetrahedron_sign
1128
+ translate_cis_trans = self._translate_cis_trans_sign
1129
+ translate_allene = self._translate_allene_sign
1130
+
1131
+ while True:
1132
+ morgan_update = {}
1133
+ atoms_groups = []
1134
+ cis_trans_groups = []
1135
+ allenes_groups = []
1136
+ # recalculate morgan weights with taking into account existing stereo marks.
1137
+ if atoms_stereo:
1138
+ grouped_stereo = defaultdict(list)
1139
+ for n in atoms_stereo:
1140
+ grouped_stereo[morgan[n]].append(n) # collect equal stereo atoms.
1141
+ for group in grouped_stereo.values():
1142
+ if not len(group) % 2: # only even number of equal stereo atoms give new stereo center.
1143
+ # process only truly stereogenic.
1144
+ if len(env := tetrahedrons[group[0]]) == len({morgan[x] for x in env}):
1145
+ s = [n for n in group if translate_tetrahedron(n, sorted(tetrahedrons[n], key=morgan.get))]
1146
+ if 0 < len(s) < len(group): # RS pair required.
1147
+ for m in s:
1148
+ morgan_update[m] = -morgan[m]
1149
+ for n in group: # prevent checks repeating.
1150
+ atoms_stereo.discard(n)
1151
+ else: # stereo group in rings. unambiguous environment order impossible.
1152
+ atoms_groups.append(group)
1153
+
1154
+ if cis_trans_stereo:
1155
+ grouped_stereo = defaultdict(list)
1156
+ for nm in cis_trans_stereo:
1157
+ n, m = nm
1158
+ if (mn := morgan[n]) <= (mm := morgan[m]):
1159
+ grouped_stereo[mn].append((n, nm))
1160
+ else:
1161
+ grouped_stereo[mm].append((m, nm))
1162
+ for group in grouped_stereo.values():
1163
+ if not len(group) % 2: # only even number of equal stereo bonds give new stereo center.
1164
+ n1, m1, n2, m2 = cis_trans[group[0][1]]
1165
+ if morgan[n1] != morgan.get(n2, 0) and morgan[m1] != morgan.get(m2, 0):
1166
+ s = []
1167
+ for x, nm in group:
1168
+ n, m = nm
1169
+ n1, m1, n2, m2 = cis_trans[nm]
1170
+ if n2 is None:
1171
+ a = n1
1172
+ else:
1173
+ a = min(n1, n2, key=morgan.get)
1174
+ if m2 is None:
1175
+ b = m1
1176
+ else:
1177
+ b = min(m1, m2, key=morgan.get)
1178
+ if translate_cis_trans(n, m, a, b):
1179
+ s.append(x)
1180
+ if 0 < len(s) < len(group): # RS pair required.
1181
+ for n in s:
1182
+ morgan_update[n] = -morgan[n]
1183
+ for _, nm in group:
1184
+ cis_trans_stereo.discard(nm)
1185
+ else:
1186
+ cis_trans_groups.append(group)
1187
+
1188
+ if allenes_stereo:
1189
+ grouped_stereo = defaultdict(list)
1190
+ for c in allenes_stereo:
1191
+ grouped_stereo[morgan[c]].append(c)
1192
+ for group in grouped_stereo.values():
1193
+ if not len(group) % 2: # only even number of equal stereo bonds give new stereo center.
1194
+ n1, m1, n2, m2 = allenes[group[0]]
1195
+ if morgan[n1] != morgan.get(n2, 0) and morgan[m1] != morgan.get(m2, 0):
1196
+ s = []
1197
+ for c in group:
1198
+ n1, m1, n2, m2 = allenes[c]
1199
+ if n2 is None:
1200
+ a = n1
1201
+ else:
1202
+ a = min(n1, n2, key=morgan.get)
1203
+ if m2 is None:
1204
+ b = m1
1205
+ else:
1206
+ b = min(m1, m2, key=morgan.get)
1207
+ if translate_allene(c, a, b):
1208
+ s.append(c)
1209
+ if 0 < len(s) < len(group): # RS pair required.
1210
+ for c in s:
1211
+ morgan_update[c] = -morgan[c]
1212
+ for c in group:
1213
+ allenes_stereo.discard(c)
1214
+ else:
1215
+ allenes_groups.append(group)
1216
+ if not morgan_update:
1217
+ break
1218
+ morgan = _morgan({**morgan, **morgan_update}, bonds)
1219
+ return morgan, atoms_stereo, cis_trans_stereo, allenes_stereo, atoms_groups, cis_trans_groups, allenes_groups
1220
+
1221
+
1222
+ __all__ = ['MoleculeStereo']