protomol 0.0.1__tar.gz

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 (40) hide show
  1. protomol-0.0.1/LICENSE +21 -0
  2. protomol-0.0.1/PKG-INFO +85 -0
  3. protomol-0.0.1/README.md +67 -0
  4. protomol-0.0.1/pyproject.toml +110 -0
  5. protomol-0.0.1/pyproject.toml.orig +103 -0
  6. protomol-0.0.1/src/protomol/__init__.py +84 -0
  7. protomol-0.0.1/src/protomol/_backend.py +208 -0
  8. protomol-0.0.1/src/protomol/_ccv.py +416 -0
  9. protomol-0.0.1/src/protomol/_display.py +107 -0
  10. protomol-0.0.1/src/protomol/_json.py +43 -0
  11. protomol-0.0.1/src/protomol/_reaction.py +274 -0
  12. protomol-0.0.1/src/protomol/_smiles.py +249 -0
  13. protomol-0.0.1/src/protomol/_stereo.py +468 -0
  14. protomol-0.0.1/src/protomol/_types.py +600 -0
  15. protomol-0.0.1/src/protomol/_vendor/__init__.py +7 -0
  16. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/LICENSE +21 -0
  17. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/__init__.py +23 -0
  18. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/algorithms/__init__.py +0 -0
  19. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/algorithms/_bond_orders.py +648 -0
  20. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/algorithms/canon.py +469 -0
  21. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/algorithms/circular.py +725 -0
  22. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/algorithms/isomorphism.py +731 -0
  23. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/algorithms/symmetry.py +295 -0
  24. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/coords.py +434 -0
  25. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/experimental/__init__.py +20 -0
  26. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/experimental/_isomers.py +180 -0
  27. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/experimental/_json.py +204 -0
  28. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/graph2rdmol.py +542 -0
  29. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/graphs/__init__.py +19 -0
  30. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/graphs/crg.py +370 -0
  31. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/graphs/mg.py +743 -0
  32. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/graphs/scrg.py +574 -0
  33. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/graphs/smg.py +456 -0
  34. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/ipython.py +267 -0
  35. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/periodic_table.py +81 -0
  36. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/py.typed +0 -0
  37. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/rdmol2graph.py +547 -0
  38. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/stereodescriptors.py +674 -0
  39. protomol-0.0.1/src/protomol/_vendor/stereomolgraph/xyz2graph.py +288 -0
  40. protomol-0.0.1/src/protomol/examples.py +56 -0
protomol-0.0.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Andreas V. Copan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.4
2
+ Name: protomol
3
+ Version: 0.0.1
4
+ Author: Andreas V. Copan
5
+ Author-email: Andreas V. Copan <avcopan@uga.edu>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Dist: more-itertools>=8
9
+ Requires-Dist: networkx>=3.5
10
+ Requires-Dist: numpy>=2.2
11
+ Requires-Dist: pydantic>=2.10
12
+ Requires-Dist: rdkit>=2024.9.1
13
+ Requires-Dist: typing-extensions>=4.12
14
+ Requires-Python: >=3.13
15
+ Project-URL: Repository, https://github.com/avcopan/protomol
16
+ Project-URL: Documentation, https://avcopan.github.io/protomol/
17
+ Description-Content-Type: text/markdown
18
+
19
+ # protomol
20
+
21
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
22
+ [![Pixi Badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/prefix-dev/pixi/main/assets/badge/v0.json)](https://pixi.sh)
23
+ [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)
24
+ [![Typing: ty](https://img.shields.io/badge/typing-ty-EFC621.svg)](https://github.com/astral-sh/ty)
25
+ [![Copier](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/copier-org/copier/master/img/badge/badge-grayscale-border.json)](https://github.com/copier-org/copier)
26
+
27
+ A draft of the graph API for [AutoStorage](https://github.com/avcopan/autostorage) and
28
+ AutoEngine: graph types for molecules and reactions with local stereodescriptors.
29
+
30
+ It has four immutable graph types (`MolGraph`, `StereoMolGraph`, `ReactionGraph`,
31
+ `StereoReactionGraph`), which are frozen pydantic models; their local stereodescriptors
32
+ (`Tetrahedral`, `PlanarBond`, `AtropBond`, …, and `StereoChange` for a reaction);
33
+ `from_smiles`; a deterministic JSON form; the transition-state graphs of a reaction
34
+ (`ts_graphs`); drawings in Jupyter; and three test graphs in `protomol.examples`.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install protomol
40
+ ```
41
+
42
+ or, in a pixi workspace, `pixi add --pypi protomol`. It is also on the `avcopan/automech`
43
+ channel of prefix.dev.
44
+
45
+ ## Usage
46
+
47
+ ```python
48
+ import protomol as pm
49
+
50
+ # Every H is explicit, and atom i of the graph is atom i of the SMILES
51
+ gra = pm.from_smiles("CC(O)CC")
52
+ gra.symbols[:4] # ('C', 'C', 'O', 'C')
53
+
54
+ # In Jupyter: C1 is marked "?", since the SMILES doesn't give its configuration
55
+ pm.display(gra)
56
+
57
+ # One compact, deterministic JSON string per graph
58
+ text = pm.to_json(gra)
59
+ assert pm.from_json(text) == gra
60
+
61
+ # The transition-state graphs of a reaction, in the reactants' atom order
62
+ (ts,) = pm.ts_graphs(pm.from_smiles("CC.[OH]"), pm.from_smiles("C[CH2].O"))
63
+ ts.breaking, ts.forming # ((0, 3),), ((2, 3),)
64
+ ```
65
+
66
+ `protomol.examples` has three test graphs, each with its golden JSON in `tests/data/examples/`:
67
+
68
+ | function | graph |
69
+ |---|---|
70
+ | `species()` | (E)-pent-3-en-2-ol, one enantiomer (`C[C@@H](O)/C=C/C`) |
71
+ | `abstraction_ts()` | C2H6 + OH → C2H5 + H2O, H abstraction |
72
+ | `stereoisomerization_ts()` | (Z) → (E) but-2-en-1-yl radical, rotation about C2=C3 |
73
+
74
+ The pages in `user_guide/` show protomol as AutoEngine and AutoStorage use it, one page
75
+ per interface. Their `>>>` examples run as doctests; the planned examples show the API
76
+ still to come.
77
+
78
+ ## Contributing
79
+
80
+ Pull requests are welcome. For major changes, please open an issue first
81
+ to discuss what you would like to change.
82
+
83
+ ## Credits
84
+
85
+ This package was created with [copier](https://copier.readthedocs.io/) and the [avcopan/copier-pixi-python](https://github.com/avcopan/copier-pixi-python) project template.
@@ -0,0 +1,67 @@
1
+ # protomol
2
+
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
4
+ [![Pixi Badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/prefix-dev/pixi/main/assets/badge/v0.json)](https://pixi.sh)
5
+ [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)
6
+ [![Typing: ty](https://img.shields.io/badge/typing-ty-EFC621.svg)](https://github.com/astral-sh/ty)
7
+ [![Copier](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/copier-org/copier/master/img/badge/badge-grayscale-border.json)](https://github.com/copier-org/copier)
8
+
9
+ A draft of the graph API for [AutoStorage](https://github.com/avcopan/autostorage) and
10
+ AutoEngine: graph types for molecules and reactions with local stereodescriptors.
11
+
12
+ It has four immutable graph types (`MolGraph`, `StereoMolGraph`, `ReactionGraph`,
13
+ `StereoReactionGraph`), which are frozen pydantic models; their local stereodescriptors
14
+ (`Tetrahedral`, `PlanarBond`, `AtropBond`, …, and `StereoChange` for a reaction);
15
+ `from_smiles`; a deterministic JSON form; the transition-state graphs of a reaction
16
+ (`ts_graphs`); drawings in Jupyter; and three test graphs in `protomol.examples`.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install protomol
22
+ ```
23
+
24
+ or, in a pixi workspace, `pixi add --pypi protomol`. It is also on the `avcopan/automech`
25
+ channel of prefix.dev.
26
+
27
+ ## Usage
28
+
29
+ ```python
30
+ import protomol as pm
31
+
32
+ # Every H is explicit, and atom i of the graph is atom i of the SMILES
33
+ gra = pm.from_smiles("CC(O)CC")
34
+ gra.symbols[:4] # ('C', 'C', 'O', 'C')
35
+
36
+ # In Jupyter: C1 is marked "?", since the SMILES doesn't give its configuration
37
+ pm.display(gra)
38
+
39
+ # One compact, deterministic JSON string per graph
40
+ text = pm.to_json(gra)
41
+ assert pm.from_json(text) == gra
42
+
43
+ # The transition-state graphs of a reaction, in the reactants' atom order
44
+ (ts,) = pm.ts_graphs(pm.from_smiles("CC.[OH]"), pm.from_smiles("C[CH2].O"))
45
+ ts.breaking, ts.forming # ((0, 3),), ((2, 3),)
46
+ ```
47
+
48
+ `protomol.examples` has three test graphs, each with its golden JSON in `tests/data/examples/`:
49
+
50
+ | function | graph |
51
+ |---|---|
52
+ | `species()` | (E)-pent-3-en-2-ol, one enantiomer (`C[C@@H](O)/C=C/C`) |
53
+ | `abstraction_ts()` | C2H6 + OH → C2H5 + H2O, H abstraction |
54
+ | `stereoisomerization_ts()` | (Z) → (E) but-2-en-1-yl radical, rotation about C2=C3 |
55
+
56
+ The pages in `user_guide/` show protomol as AutoEngine and AutoStorage use it, one page
57
+ per interface. Their `>>>` examples run as doctests; the planned examples show the API
58
+ still to come.
59
+
60
+ ## Contributing
61
+
62
+ Pull requests are welcome. For major changes, please open an issue first
63
+ to discuss what you would like to change.
64
+
65
+ ## Credits
66
+
67
+ This package was created with [copier](https://copier.readthedocs.io/) and the [avcopan/copier-pixi-python](https://github.com/avcopan/copier-pixi-python) project template.
@@ -0,0 +1,110 @@
1
+ [project]
2
+ name = "protomol"
3
+ version = "0.0.1"
4
+ readme = "README.md"
5
+ license = "MIT"
6
+ license-files = ["LICENSE"]
7
+ dependencies = [
8
+ "more-itertools>=8",
9
+ "networkx>=3.5",
10
+ "numpy>=2.2",
11
+ "pydantic>=2.10",
12
+ "rdkit>=2024.9.1",
13
+ "typing-extensions>=4.12",
14
+ ]
15
+ requires-python = ">= 3.13"
16
+
17
+ [[project.authors]]
18
+ name = "Andreas V. Copan"
19
+ email = "avcopan@uga.edu"
20
+
21
+ [project.urls]
22
+ Repository = "https://github.com/avcopan/protomol"
23
+ Documentation = "https://avcopan.github.io/protomol/"
24
+
25
+ [build-system]
26
+ build-backend = "uv_build"
27
+ requires = ["uv_build"]
28
+
29
+ [tool.ruff]
30
+ extend-exclude = [
31
+ ".agents",
32
+ ".claude",
33
+ "extern",
34
+ "src/protomol/_vendor",
35
+ ]
36
+ force-exclude = true
37
+
38
+ [tool.ruff.lint]
39
+ select = ["ALL"]
40
+ ignore = [
41
+ "COM812",
42
+ "TID252",
43
+ "D203",
44
+ "D213",
45
+ "CPY001",
46
+ ]
47
+
48
+ [tool.ruff.lint.per-file-ignores]
49
+ "tests/**.py" = [
50
+ "S101",
51
+ "PLR2004",
52
+ ]
53
+ "scripts/**.py" = [
54
+ "T201",
55
+ "INP001",
56
+ ]
57
+
58
+ [tool.ruff.lint.pydocstyle]
59
+ convention = "google"
60
+
61
+ [tool.ty.environment]
62
+ python = ".pixi/envs/test/bin/python"
63
+
64
+ [tool.ty.src]
65
+ include = [
66
+ "src",
67
+ "tests",
68
+ "scripts",
69
+ ]
70
+ exclude = ["src/protomol/_vendor"]
71
+
72
+ [tool.importlinter]
73
+ root_package = "protomol"
74
+
75
+ [[tool.importlinter.contracts]]
76
+ name = "Module Layering"
77
+ type = "layers"
78
+ layers = [
79
+ "protomol._smiles | protomol._display",
80
+ "protomol._backend | protomol._json",
81
+ "protomol._types",
82
+ "protomol._stereo",
83
+ ]
84
+ ignore_imports = ["protomol._types -> protomol._display"]
85
+
86
+ [tool.pytest.ini_options]
87
+ testpaths = [
88
+ "tests",
89
+ "src",
90
+ "user_guide",
91
+ ]
92
+ addopts = [
93
+ "--doctest-modules",
94
+ "--doctest-glob=*.qmd",
95
+ "--ignore=src/protomol/_vendor",
96
+ "--cov=protomol",
97
+ "--cov-report=term-missing",
98
+ "--cov-report=html",
99
+ ]
100
+ doctest_optionflags = "NORMALIZE_WHITESPACE"
101
+
102
+ [tool.coverage.run]
103
+ branch = true
104
+ source = ["protomol"]
105
+ omit = ["*/protomol/_vendor/*"]
106
+
107
+ [tool.coverage.report]
108
+ show_missing = true
109
+ skip_covered = true
110
+ fail_under = 80
@@ -0,0 +1,103 @@
1
+ [project]
2
+ name = "protomol"
3
+ version = "0.0.1"
4
+ readme = "README.md" # the PyPI page
5
+ license = "MIT"
6
+ license-files = ["LICENSE"]
7
+ authors = [{name = "Andreas V. Copan", email = "avcopan@uga.edu"}]
8
+ dependencies = [
9
+ "more-itertools>=8",
10
+ "networkx>=3.5",
11
+ "numpy>=2.2",
12
+ "pydantic>=2.10", # Field(default_factory=...) taking the validated data
13
+ "rdkit>=2024.9.1",
14
+ "typing-extensions>=4.12",
15
+ ]
16
+ requires-python = ">= 3.13"
17
+
18
+ [project.urls]
19
+ Repository = "https://github.com/avcopan/protomol"
20
+ Documentation = "https://avcopan.github.io/protomol/"
21
+
22
+ [build-system]
23
+ build-backend = "uv_build"
24
+ requires = ["uv_build"]
25
+
26
+ # Ruff configurations
27
+ [tool.ruff]
28
+ extend-exclude = [
29
+ ".agents", # vendored agent skills
30
+ ".claude",
31
+ "extern", # upstream source (git-subrepo), linted by its own rules
32
+ "src/protomol/_vendor", # generated by `pixi run vendor`
33
+ ]
34
+ force-exclude = true # also when an editor or hook passes an excluded file by name
35
+
36
+ [tool.ruff.lint]
37
+ select = ["ALL"]
38
+ ignore = [
39
+ "COM812", # missing trailing comma (handled by format)
40
+ "TID252", # relative import
41
+ "D203", # conflict: incorrect blank line before class (uses D211 instead)
42
+ "D213", # conflict: multi-line summary second line (uses D212 instead)
43
+ "CPY001", # copyright notice
44
+ ]
45
+
46
+ [tool.ruff.lint.per-file-ignores]
47
+ "tests/**.py" = ["S101", "PLR2004"] # assert, magic values
48
+ "scripts/**.py" = ["T201", "INP001"] # print, not a package
49
+
50
+ [tool.ruff.lint.pydocstyle]
51
+ convention = "google"
52
+
53
+ # Ty configurations
54
+ [tool.ty.environment]
55
+ python = ".pixi/envs/test/bin/python"
56
+
57
+ [tool.ty.src]
58
+ include = [
59
+ "src",
60
+ "tests",
61
+ "scripts",
62
+ ]
63
+ exclude = ["src/protomol/_vendor"] # generated by `pixi run vendor`
64
+
65
+ # Import-linter configurations
66
+ [tool.importlinter]
67
+ root_package = "protomol"
68
+
69
+ [[tool.importlinter.contracts]]
70
+ name = "Module Layering"
71
+ type = "layers"
72
+ layers = [
73
+ "protomol._smiles | protomol._display",
74
+ "protomol._backend | protomol._json",
75
+ "protomol._types",
76
+ "protomol._stereo",
77
+ ]
78
+ # `_repr_svg_` on the graph types draws with `_display`, imported inside the method
79
+ ignore_imports = ["protomol._types -> protomol._display"]
80
+
81
+ # Pytest configurations
82
+ [tool.pytest.ini_options]
83
+ testpaths = ["tests", "src", "user_guide"]
84
+ addopts = [
85
+ "--doctest-modules",
86
+ "--doctest-glob=*.qmd", # the use-case pages (user_guide/)
87
+ "--ignore=src/protomol/_vendor", # generated by `pixi run vendor`
88
+ "--cov=protomol",
89
+ "--cov-report=term-missing",
90
+ "--cov-report=html",
91
+ ]
92
+ doctest_optionflags = "NORMALIZE_WHITESPACE"
93
+
94
+ # Pytest-cov configurations
95
+ [tool.coverage.run]
96
+ branch = true
97
+ source = ["protomol"]
98
+ omit = ["*/protomol/_vendor/*"] # generated by `pixi run vendor`
99
+
100
+ [tool.coverage.report]
101
+ show_missing = true
102
+ skip_covered = true
103
+ fail_under = 80
@@ -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
+ ]
@@ -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
+ )