seamm-optimizer 2026.11.24__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 (25) hide show
  1. seamm_optimizer-2026.11.24/CODE_OF_CONDUCT.md +77 -0
  2. seamm_optimizer-2026.11.24/LICENSE +28 -0
  3. seamm_optimizer-2026.11.24/MANIFEST.in +3 -0
  4. seamm_optimizer-2026.11.24/PKG-INFO +43 -0
  5. seamm_optimizer-2026.11.24/README.md +20 -0
  6. seamm_optimizer-2026.11.24/pyproject.toml +89 -0
  7. seamm_optimizer-2026.11.24/seamm_optimizer/__init__.py +16 -0
  8. seamm_optimizer-2026.11.24/seamm_optimizer/_version.py +1 -0
  9. seamm_optimizer-2026.11.24/seamm_optimizer/coordinates.py +181 -0
  10. seamm_optimizer-2026.11.24/seamm_optimizer/geometry.py +170 -0
  11. seamm_optimizer-2026.11.24/seamm_optimizer/model_hessian.py +110 -0
  12. seamm_optimizer-2026.11.24/seamm_optimizer/optimizer.py +380 -0
  13. seamm_optimizer-2026.11.24/seamm_optimizer/steps.py +107 -0
  14. seamm_optimizer-2026.11.24/seamm_optimizer.egg-info/PKG-INFO +43 -0
  15. seamm_optimizer-2026.11.24/seamm_optimizer.egg-info/SOURCES.txt +24 -0
  16. seamm_optimizer-2026.11.24/seamm_optimizer.egg-info/dependency_links.txt +1 -0
  17. seamm_optimizer-2026.11.24/seamm_optimizer.egg-info/not-zip-safe +1 -0
  18. seamm_optimizer-2026.11.24/seamm_optimizer.egg-info/requires.txt +9 -0
  19. seamm_optimizer-2026.11.24/seamm_optimizer.egg-info/top_level.txt +2 -0
  20. seamm_optimizer-2026.11.24/setup.cfg +17 -0
  21. seamm_optimizer-2026.11.24/tests/__init__.py +0 -0
  22. seamm_optimizer-2026.11.24/tests/mmff.py +86 -0
  23. seamm_optimizer-2026.11.24/tests/test_cheap_hessian.py +92 -0
  24. seamm_optimizer-2026.11.24/tests/test_coordinates.py +101 -0
  25. seamm_optimizer-2026.11.24/tests/test_optimizer.py +170 -0
@@ -0,0 +1,77 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age,
8
+ body size, disability, ethnicity, gender identity and expression, level of
9
+ experience, nationality, personal appearance, race, religion, or sexual
10
+ identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment include:
15
+
16
+ * Using welcoming and inclusive language
17
+ * Being respectful of differing viewpoints and experiences
18
+ * Gracefully accepting constructive criticism
19
+ * Focusing on what is best for the community
20
+ * Showing empathy towards other community members
21
+
22
+ Examples of unacceptable behavior by participants include:
23
+
24
+ * The use of sexualized language or imagery and unwelcome sexual attention or advances
25
+ * Trolling, insulting/derogatory comments, and personal or political attacks
26
+ * Public or private harassment
27
+ * Publishing others' private information, such as a physical or electronic address, without explicit permission
28
+ * Other conduct which could reasonably be considered inappropriate in a professional setting
29
+
30
+ ## Our Responsibilities
31
+
32
+ Project maintainers are responsible for clarifying the standards of acceptable
33
+ behavior and are expected to take appropriate and fair corrective action in
34
+ response to any instances of unacceptable behavior.
35
+
36
+ Project maintainers have the right and responsibility to remove, edit, or
37
+ reject comments, commits, code, wiki edits, issues, and other contributions
38
+ that are not aligned to this Code of Conduct, or to ban temporarily or
39
+ permanently any contributor for other behaviors that they deem inappropriate,
40
+ threatening, offensive, or harmful.
41
+
42
+ Moreover, project maintainers will strive to offer feedback and advice to
43
+ ensure quality and consistency of contributions to the code. Contributions
44
+ from outside the group of project maintainers are strongly welcomed but the
45
+ final decision as to whether commits are merged into the codebase rests with
46
+ the team of project maintainers.
47
+
48
+ ## Scope
49
+
50
+ This Code of Conduct applies both within project spaces and in public spaces
51
+ when an individual is representing the project or its community. Examples of
52
+ representing a project or community include using an official project e-mail
53
+ address, posting via an official social media account, or acting as an
54
+ appointed representative at an online or offline event. Representation of a
55
+ project may be further defined and clarified by project maintainers.
56
+
57
+ ## Enforcement
58
+
59
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
60
+ reported by contacting the project team at 'psaxe@molssi.org'. The project team will
61
+ review and investigate all complaints, and will respond in a way that it deems
62
+ appropriate to the circumstances. The project team is obligated to maintain
63
+ confidentiality with regard to the reporter of an incident. Further details of
64
+ specific enforcement policies may be posted separately.
65
+
66
+ Project maintainers who do not follow or enforce the Code of Conduct in good
67
+ faith may face temporary or permanent repercussions as determined by other
68
+ members of the project's leadership.
69
+
70
+ ## Attribution
71
+
72
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
73
+ version 1.4, available at
74
+ [http://contributor-covenant.org/version/1/4][version]
75
+
76
+ [homepage]: http://contributor-covenant.org
77
+ [version]: http://contributor-covenant.org/version/1/4/
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, MolSSI SEAMM
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,3 @@
1
+ include CODE_OF_CONDUCT.md
2
+
3
+ global-exclude *.py[cod] __pycache__ *.so
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: seamm_optimizer
3
+ Version: 2026.11.24
4
+ Summary: Robust geometry optimization for SEAMM: model and cheap-level Hessians, Delta-surrogates, minimum checks
5
+ Author-email: Paul Saxe <psaxe@molssi.org>
6
+ License: BSD-3-Clause
7
+ Project-URL: Source, https://github.com/molssi-seamm/seamm_optimizer/
8
+ Project-URL: Documentation, https://molssi-seamm.github.io/
9
+ Classifier: License :: OSI Approved :: BSD License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: geometric
15
+ Requires-Dist: numpy
16
+ Requires-Dist: scipy
17
+ Provides-Extra: test
18
+ Requires-Dist: pytest>=6.1.2; extra == "test"
19
+ Requires-Dist: pytest-cov; extra == "test"
20
+ Requires-Dist: rdkit; extra == "test"
21
+ Requires-Dist: ase; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ # seamm_optimizer
25
+
26
+ Robust, economical geometry optimization for SEAMM: quasi-Newton minimization with an
27
+ RFO / trust-region step, Lindh's model Hessian or a computed (cheap-level) one, BFGS
28
+ updates, and a check that the end point is a minimum, with an escape from saddle points.
29
+
30
+ Design: `OPTIMIZER_DESIGN_PROPOSAL_20261124.md` (Paul's §10 decisions, 2026-11-24).
31
+ This is phase 1 (Cartesian coordinates). Next: internal coordinates (geomeTRIC's
32
+ primitives with a checked back-transformation), cheap-level Hessians and the
33
+ Δ-gradient / Δ-Hessian surrogates.
34
+
35
+ ```python
36
+ from seamm_optimizer import Optimizer
37
+
38
+ result = Optimizer(engine, symbols, xyz, hessian_engine=hessian).run()
39
+ # engine(xyz) -> (energy eV, gradient N x 3 eV/Å); hessian(xyz) -> 3N x 3N eV/Å^2
40
+ ```
41
+
42
+ `benchmark/mmff_proxy.py` compares it with ASE's BFGS on MMFF94 surfaces from the
43
+ benchmark's starting structures, at no cost.
@@ -0,0 +1,20 @@
1
+ # seamm_optimizer
2
+
3
+ Robust, economical geometry optimization for SEAMM: quasi-Newton minimization with an
4
+ RFO / trust-region step, Lindh's model Hessian or a computed (cheap-level) one, BFGS
5
+ updates, and a check that the end point is a minimum, with an escape from saddle points.
6
+
7
+ Design: `OPTIMIZER_DESIGN_PROPOSAL_20261124.md` (Paul's §10 decisions, 2026-11-24).
8
+ This is phase 1 (Cartesian coordinates). Next: internal coordinates (geomeTRIC's
9
+ primitives with a checked back-transformation), cheap-level Hessians and the
10
+ Δ-gradient / Δ-Hessian surrogates.
11
+
12
+ ```python
13
+ from seamm_optimizer import Optimizer
14
+
15
+ result = Optimizer(engine, symbols, xyz, hessian_engine=hessian).run()
16
+ # engine(xyz) -> (energy eV, gradient N x 3 eV/Å); hessian(xyz) -> 3N x 3N eV/Å^2
17
+ ```
18
+
19
+ `benchmark/mmff_proxy.py` compares it with ASE's BFGS on MMFF94 surfaces from the
20
+ benchmark's starting structures, at no cost.
@@ -0,0 +1,89 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "versioningit~=2.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ # Self-descriptive entries which should always be present
6
+ # https://packaging.python.org/en/latest/specifications/declaring-project-metadata/
7
+ [project]
8
+ name = "seamm_optimizer"
9
+ description = "Robust geometry optimization for SEAMM: model and cheap-level Hessians, Delta-surrogates, minimum checks"
10
+ dynamic = ["version"]
11
+ readme = "README.md"
12
+ authors = [
13
+ { name = "Paul Saxe", email = "psaxe@molssi.org" }
14
+ ]
15
+ license = { text = "BSD-3-Clause" }
16
+ # See https://pypi.org/classifiers/
17
+ classifiers = [
18
+ "License :: OSI Approved :: BSD License",
19
+ "Programming Language :: Python :: 3",
20
+ ]
21
+ requires-python = ">=3.9"
22
+ # Pure bookkeeping -- no quantum-chemistry, no SEAMM-core, no molsystem
23
+ # dependency by design (see the architecture doc). No runtime dependencies.
24
+ dependencies = [
25
+ "geometric",
26
+ "numpy",
27
+ "scipy",
28
+ ]
29
+
30
+ [project.urls]
31
+ "Source" = "https://github.com/molssi-seamm/seamm_optimizer/"
32
+ "Documentation" = "https://molssi-seamm.github.io/"
33
+
34
+ [project.optional-dependencies]
35
+ test = [
36
+ "pytest>=6.1.2",
37
+ "pytest-cov",
38
+ "rdkit",
39
+ "ase",
40
+ ]
41
+
42
+ [tool.setuptools]
43
+ # This subkey is a beta stage development and keys may change in the future, see https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html for more details
44
+ #
45
+ # As of version 0.971, mypy does not support type checking of installed zipped
46
+ # packages (because it does not actually import the Python packages).
47
+ # We declare the package not-zip-safe so that our type hints are also available
48
+ # when checking client code that uses our (installed) package.
49
+ # Ref:
50
+ # https://mypy.readthedocs.io/en/stable/installed_packages.html?highlight=zip#using-installed-packages-with-mypy-pep-561
51
+ zip-safe = false
52
+ # Let setuptools discover the package in the current directory,
53
+ # but be explicit about non-Python files.
54
+ # See also:
55
+ # https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html#setuptools-specific-configuration
56
+ # Note that behavior is currently evolving with respect to how to interpret the
57
+ # "data" and "tests" subdirectories. As of setuptools 63, both are automatically
58
+ # included if namespaces is true (default), even if the package is named explicitly
59
+ # (instead of using 'find'). With 'find', the 'tests' subpackage is discovered
60
+ # recursively because of its __init__.py file, but the data subdirectory is excluded
61
+ # with include-package-data = false and namespaces = false.
62
+ include-package-data = false
63
+ [tool.setuptools.packages.find]
64
+ namespaces = false
65
+ where = ["."]
66
+
67
+ # Ref https://setuptools.pypa.io/en/latest/userguide/datafiles.html#package-data
68
+ [tool.setuptools.package-data]
69
+ seamm_optimizer = [
70
+ "py.typed"
71
+ ]
72
+
73
+ [tool.versioningit]
74
+ default-version = "1+unknown"
75
+
76
+ [tool.versioningit.format]
77
+ distance = "{base_version}+{distance}.{vcs}{rev}"
78
+ dirty = "{base_version}+{distance}.{vcs}{rev}.dirty"
79
+ distance-dirty = "{base_version}+{distance}.{vcs}{rev}.dirty"
80
+
81
+ [tool.versioningit.vcs]
82
+ # The method key:
83
+ method = "git" # <- The method name
84
+ # Parameters to pass to the method:
85
+ match = ["*"]
86
+ default-tag = "1.0.0"
87
+
88
+ [tool.versioningit.write]
89
+ file = "seamm_optimizer/_version.py"
@@ -0,0 +1,16 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """seamm_optimizer: robust geometry optimization for SEAMM.
4
+
5
+ Phase 1 (proposal OPTIMIZER_DESIGN_PROPOSAL_20261124): quasi-Newton minimization in
6
+ Cartesians with an RFO / trust-region step, Lindh's model Hessian or a computed one,
7
+ BFGS updates, and a minimum check with an escape from saddle points.
8
+ """
9
+
10
+ from .geometry import frequencies, projector, rigid_modes # noqa: F401
11
+ from .model_hessian import lindh_hessian # noqa: F401
12
+ from .optimizer import Optimizer, Result # noqa: F401
13
+ from .steps import bfgs_update, rfo_step # noqa: F401
14
+
15
+ # Handle versioneer
16
+ from ._version import __version__ # noqa: F401
@@ -0,0 +1 @@
1
+ __version__ = "2026.11.24"
@@ -0,0 +1,181 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """Coordinate systems for the optimizer: Cartesians, and internal coordinates built
4
+ with geomeTRIC's code (TRIC, delocalized internals, redundant primitives), per the
5
+ design (proposal §4, Paul's §10 decision 1).
6
+
7
+ Every system works in atomic units internally (bohr, hartree) and offers:
8
+
9
+ - ``q(xyz)``: the coordinates of a Cartesian structure (Å in, a vector out);
10
+ - ``gradient(xyz, gx)``: the gradient in these coordinates (gx in eV/Å);
11
+ - ``hessian(xyz, gx, hx)``: a Cartesian Hessian (eV/Å^2) in these coordinates;
12
+ - ``to_cartesian(xyz, dq)``: the Cartesian structure for a step dq, and whether the
13
+ back-transformation reproduced dq (the check of §4: a failure lets the optimizer
14
+ shrink the step or fall back to a Cartesian step);
15
+ - ``difference(xyz1, xyz0)``: q(xyz1) - q(xyz0), with angles wrapped;
16
+ - ``rigid(xyz)``: an orthonormal basis of the coordinate changes of an overall
17
+ translation or rotation, removed from every step.
18
+ """
19
+
20
+ import numpy as np
21
+
22
+ from .geometry import rigid_modes
23
+ from .model_hessian import BOHR, HARTREE
24
+
25
+ #: the back-transformation is accepted when |dq_achieved - dq| <= this x |dq| (+1e-6)
26
+ BACK_TRANSFORM_TOLERANCE = 0.1
27
+
28
+
29
+ def _to_au_gradient(gx):
30
+ return np.asarray(gx, float).ravel() * BOHR / HARTREE
31
+
32
+
33
+ def _to_au_hessian(hx):
34
+ return np.asarray(hx, float) * BOHR**2 / HARTREE
35
+
36
+
37
+ class Cartesian:
38
+ """Cartesian coordinates (bohr)."""
39
+
40
+ name = "Cartesian"
41
+
42
+ def __init__(self, symbols, xyz):
43
+ self.symbols = list(symbols)
44
+
45
+ def q(self, xyz):
46
+ return np.asarray(xyz, float).ravel() / BOHR
47
+
48
+ def gradient(self, xyz, gx):
49
+ return _to_au_gradient(gx)
50
+
51
+ def hessian(self, xyz, gx, hx):
52
+ return _to_au_hessian(hx)
53
+
54
+ def to_cartesian(self, xyz, dq):
55
+ return np.asarray(xyz, float) + dq.reshape(-1, 3) * BOHR, True
56
+
57
+ def difference(self, xyz1, xyz0):
58
+ return (np.asarray(xyz1, float) - np.asarray(xyz0, float)).ravel() / BOHR
59
+
60
+ def rigid(self, xyz):
61
+ return rigid_modes(np.asarray(xyz, float))
62
+
63
+ def to_cartesian_hessian(self, xyz, hq):
64
+ """A q-space Hessian (atomic units) as a Cartesian one (eV/Å^2)."""
65
+ return np.asarray(hq) * HARTREE / BOHR**2
66
+
67
+
68
+ class Internal:
69
+ """geomeTRIC's internal coordinates.
70
+
71
+ kind: "TRIC" (translation-rotation internal coordinates: each fragment's
72
+ translations and rotations are coordinates, so clusters need no bonds between
73
+ fragments), "DLC" (delocalized internals, fragments connected), "HDLC" (TRIC plus
74
+ Cartesians) or "primitive" (TRIC's redundant primitives)."""
75
+
76
+ def __init__(self, symbols, xyz, kind="TRIC"):
77
+ from geometric.internal import (
78
+ DelocalizedInternalCoordinates,
79
+ PrimitiveInternalCoordinates,
80
+ )
81
+ from geometric.molecule import Molecule
82
+
83
+ self.symbols = list(symbols)
84
+ self.kind = kind
85
+ self.name = kind
86
+ molecule = Molecule()
87
+ molecule.elem = list(symbols)
88
+ molecule.xyzs = [np.asarray(xyz, float)]
89
+ molecule.build_topology()
90
+ if kind == "TRIC":
91
+ self.ic = DelocalizedInternalCoordinates(
92
+ molecule, build=True, connect=False, addcart=False
93
+ )
94
+ elif kind == "DLC":
95
+ self.ic = DelocalizedInternalCoordinates(
96
+ molecule, build=True, connect=True, addcart=False
97
+ )
98
+ elif kind == "HDLC":
99
+ self.ic = DelocalizedInternalCoordinates(
100
+ molecule, build=True, connect=False, addcart=True
101
+ )
102
+ elif kind == "primitive":
103
+ self.ic = PrimitiveInternalCoordinates(
104
+ molecule, connect=False, addcart=False
105
+ )
106
+ else:
107
+ raise ValueError(f"Unknown internal coordinates {kind!r}")
108
+
109
+ @staticmethod
110
+ def _bohr(xyz):
111
+ return np.asarray(xyz, float).ravel() / BOHR
112
+
113
+ def q(self, xyz):
114
+ return np.asarray(self.ic.calculate(self._bohr(xyz)), float)
115
+
116
+ def gradient(self, xyz, gx):
117
+ return np.asarray(self.ic.calcGrad(self._bohr(xyz), _to_au_gradient(gx)), float)
118
+
119
+ def hessian(self, xyz, gx, hx):
120
+ """A Cartesian Hessian in these coordinates, without the gradient (K) term.
121
+
122
+ The K term is right for an exact Hessian but, applied to a model Hessian away
123
+ from a minimum, it made the model worse: on MMFF from perturbed starts it
124
+ took 64 gradients for PEG4 against 17 without it (Design, 2026-11-24)."""
125
+ zero = np.zeros(3 * len(self.symbols))
126
+ hq = self.ic.calcHess(self._bohr(xyz), zero, _to_au_hessian(hx))
127
+ return 0.5 * (hq + hq.T)
128
+
129
+ def guess_hessian(self, xyz, only=None):
130
+ """geomeTRIC's own guess (a diagonal Schlegel-type model in the primitives);
131
+ with `only` (primitive class names, e.g. ("LinearAngle", "OutOfPlane")), just
132
+ those primitives' terms."""
133
+ if only is None:
134
+ hq = np.asarray(self.ic.guess_hessian(self._bohr(xyz)), float)
135
+ return 0.5 * (hq + hq.T)
136
+ prims = self.ic.Prims if hasattr(self.ic, "Prims") else self.ic
137
+ hprim = np.asarray(prims.guess_hessian(self._bohr(xyz)), float)
138
+ keep = np.array([type(ic).__name__ in only for ic in prims.Internals], float)
139
+ hprim = hprim * keep[:, None] * keep[None, :]
140
+ if hasattr(self.ic, "Vecs"):
141
+ V = np.asarray(self.ic.Vecs)
142
+ hprim = V.T @ hprim @ V
143
+ return 0.5 * (hprim + hprim.T)
144
+
145
+ def B(self, xyz):
146
+ return np.asarray(self.ic.wilsonB(self._bohr(xyz)), float)
147
+
148
+ def difference(self, xyz1, xyz0):
149
+ return np.asarray(self.ic.calcDiff(self._bohr(xyz1), self._bohr(xyz0)), float)
150
+
151
+ def to_cartesian(self, xyz, dq):
152
+ new = self.ic.newCartesian(
153
+ self._bohr(xyz), np.asarray(dq, float), verbose=False
154
+ )
155
+ xyz_new = np.asarray(new, float).reshape(-1, 3) * BOHR
156
+ achieved = self.difference(xyz_new, xyz)
157
+ error = np.linalg.norm(achieved - dq)
158
+ ok = not getattr(self.ic, "bork", False) and error <= (
159
+ BACK_TRANSFORM_TOLERANCE * np.linalg.norm(dq) + 1.0e-6
160
+ )
161
+ return xyz_new, ok
162
+
163
+ def rigid(self, xyz):
164
+ """The q-space directions of an overall translation or rotation."""
165
+ Q = rigid_modes(np.asarray(xyz, float)) # Cartesian, orthonormal
166
+ R = self.B(xyz) @ (Q * BOHR) # dq for unit rigid displacements (bohr)
167
+ u, s, _ = np.linalg.svd(R, full_matrices=False)
168
+ keep = s > 1.0e-8 * max(1.0, s.max())
169
+ return u[:, keep]
170
+
171
+ def to_cartesian_hessian(self, xyz, hq):
172
+ """B^T Hq B (no gradient term) as a Cartesian Hessian in eV/Å^2."""
173
+ B = self.B(xyz)
174
+ return (B.T @ np.asarray(hq) @ B) * HARTREE / BOHR**2
175
+
176
+
177
+ def make(kind, symbols, xyz):
178
+ """A coordinate system: "cartesian", "TRIC", "DLC", "HDLC" or "primitive"."""
179
+ if str(kind).lower() in ("cartesian", "cart"):
180
+ return Cartesian(symbols, xyz)
181
+ return Internal(symbols, xyz, kind=kind)
@@ -0,0 +1,170 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """Geometry utilities: internal coordinates and their Wilson B vectors, the
4
+ projector that removes overall translation and rotation, and harmonic frequencies.
5
+
6
+ Cartesian coordinates are N x 3 arrays in Å; B vectors are flattened 3N arrays.
7
+ """
8
+
9
+ import math
10
+
11
+ import numpy as np
12
+
13
+ #: Atomic masses (amu) of the elements, by symbol, for frequencies
14
+ _MASSES = {
15
+ "H": 1.00784,
16
+ "He": 4.002602,
17
+ "Li": 6.94,
18
+ "Be": 9.0121831,
19
+ "B": 10.81,
20
+ "C": 12.011,
21
+ "N": 14.007,
22
+ "O": 15.999,
23
+ "F": 18.998403163,
24
+ "Ne": 20.1797,
25
+ "Na": 22.98976928,
26
+ "Mg": 24.305,
27
+ "Al": 26.9815385,
28
+ "Si": 28.085,
29
+ "P": 30.973761998,
30
+ "S": 32.06,
31
+ "Cl": 35.45,
32
+ "Ar": 39.948,
33
+ "K": 39.0983,
34
+ "Ca": 40.078,
35
+ "Br": 79.904,
36
+ "I": 126.90447,
37
+ "Se": 78.971,
38
+ "As": 74.921595,
39
+ "Ge": 72.630,
40
+ "Sn": 118.710,
41
+ "Ga": 69.723,
42
+ "In": 114.818,
43
+ "Te": 127.60,
44
+ "Fe": 55.845,
45
+ "Co": 58.933194,
46
+ "Ni": 58.6934,
47
+ "Cu": 63.546,
48
+ "Zn": 65.38,
49
+ "Cr": 51.9961,
50
+ "Mn": 54.938044,
51
+ "Ti": 47.867,
52
+ "V": 50.9415,
53
+ "Sc": 44.955908,
54
+ }
55
+
56
+ #: 1 eV/Å^2/amu in (cm^-1)^2: nu = sqrt(k/m) / (2 pi c)
57
+ _EV_A2_AMU_TO_CM2 = (
58
+ 1.602176634e-19 / 1e-20 / 1.66053906660e-27 / (2 * math.pi * 2.99792458e10) ** 2
59
+ )
60
+
61
+
62
+ def masses(symbols):
63
+ """The masses (amu) of the atoms."""
64
+ try:
65
+ return np.array([_MASSES[s] for s in symbols])
66
+ except KeyError as e:
67
+ raise ValueError(f"No mass for element {e}") from None
68
+
69
+
70
+ def distance(xyz, i, j):
71
+ return float(np.linalg.norm(xyz[i] - xyz[j]))
72
+
73
+
74
+ def b_stretch(xyz, i, j):
75
+ """(r, B vector) of the distance i-j."""
76
+ n = len(xyz)
77
+ d = xyz[i] - xyz[j]
78
+ r = float(np.linalg.norm(d))
79
+ u = d / r
80
+ b = np.zeros((n, 3))
81
+ b[i], b[j] = u, -u
82
+ return r, b.ravel()
83
+
84
+
85
+ def b_bend(xyz, i, j, k):
86
+ """(angle i-j-k in radians, B vector), j the apex; None near 0 or 180 degrees."""
87
+ n = len(xyz)
88
+ u, v = xyz[i] - xyz[j], xyz[k] - xyz[j]
89
+ ru, rv = np.linalg.norm(u), np.linalg.norm(v)
90
+ u, v = u / ru, v / rv
91
+ c = float(np.clip(np.dot(u, v), -1.0, 1.0))
92
+ s = math.sqrt(max(0.0, 1.0 - c * c))
93
+ if s < 1.0e-3:
94
+ return None
95
+ phi = math.acos(c)
96
+ bi = (c * u - v) / (ru * s)
97
+ bk = (c * v - u) / (rv * s)
98
+ b = np.zeros((n, 3))
99
+ b[i], b[k], b[j] = bi, bk, -bi - bk
100
+ return phi, b.ravel()
101
+
102
+
103
+ def b_torsion(xyz, i, j, k, m):
104
+ """(dihedral i-j-k-m in radians, B vector); None if a bend in it is near linear."""
105
+ n = len(xyz)
106
+ b1, b2, b3 = xyz[j] - xyz[i], xyz[k] - xyz[j], xyz[m] - xyz[k]
107
+ c1, c2 = np.cross(b1, b2), np.cross(b2, b3)
108
+ n1, n2 = float(np.dot(c1, c1)), float(np.dot(c2, c2))
109
+ r2 = float(np.linalg.norm(b2))
110
+ if r2 < 1.0e-6 or n1 < 1.0e-8 * r2 * r2 or n2 < 1.0e-8 * r2 * r2:
111
+ return None
112
+ # Blondel & Karplus (1996) gradient of the dihedral
113
+ tau = math.atan2(r2 * float(np.dot(b1, c2)), float(np.dot(c1, c2)))
114
+ gi = -r2 / n1 * c1
115
+ gm = r2 / n2 * c2
116
+ # with r_ij = x_i - x_j = -b1, r_kj = b2, r_kl = x_k - x_m = -b3
117
+ p1 = np.dot(b1, b2) / (r2 * r2)
118
+ p3 = np.dot(b3, b2) / (r2 * r2)
119
+ gj = (-p1 - 1.0) * gi + p3 * gm
120
+ gk = (-p3 - 1.0) * gm + p1 * gi
121
+ b = np.zeros((n, 3))
122
+ b[i], b[j], b[k], b[m] = gi, gj, gk, gm
123
+ return tau, b.ravel()
124
+
125
+
126
+ def rigid_modes(xyz, weights=None):
127
+ """An orthonormal basis (3N x k) of the overall translations and rotations
128
+ (k = 6, or 5 for a linear molecule, 3 for an atom), optionally mass-weighted."""
129
+ n = len(xyz)
130
+ w = np.ones(n) if weights is None else np.asarray(weights, float)
131
+ sw = np.sqrt(w)
132
+ center = (w[:, None] * xyz).sum(0) / w.sum()
133
+ r = xyz - center
134
+ vectors = []
135
+ for axis in np.eye(3):
136
+ vectors.append((np.tile(axis, (n, 1)) * sw[:, None]).ravel())
137
+ for axis in np.eye(3):
138
+ vectors.append((np.cross(axis, r) * sw[:, None]).ravel())
139
+ V = np.array(vectors).T
140
+ u, s, _ = np.linalg.svd(V, full_matrices=False)
141
+ keep = s > 1.0e-6 * s.max()
142
+ return u[:, keep]
143
+
144
+
145
+ def projector(xyz):
146
+ """The projector (3N x 3N) onto the internal motions: translations and
147
+ rotations removed."""
148
+ Q = rigid_modes(xyz)
149
+ return np.eye(3 * len(xyz)) - Q @ Q.T
150
+
151
+
152
+ def frequencies(symbols, xyz, hessian):
153
+ """Harmonic frequencies (cm^-1, imaginary as negative) and the Cartesian normal
154
+ modes (3N x f), translations and rotations projected out. `hessian` in eV/Å^2."""
155
+ m = masses(symbols)
156
+ m3 = np.repeat(m, 3)
157
+ inv = 1.0 / np.sqrt(m3)
158
+ Hm = hessian * inv[:, None] * inv[None, :]
159
+ Q = rigid_modes(xyz, weights=m)
160
+ P = np.eye(len(m3)) - Q @ Q.T
161
+ Hm = P @ Hm @ P
162
+ w, v = np.linalg.eigh(0.5 * (Hm + Hm.T))
163
+ # drop the rigid-body modes: the eigenvectors with the largest overlap with Q
164
+ overlap = np.linalg.norm(Q.T @ v, axis=0)
165
+ order = np.argsort(-overlap)
166
+ internal = np.sort(order[Q.shape[1] :])
167
+ w, v = w[internal], v[:, internal]
168
+ nu = np.sign(w) * np.sqrt(np.abs(w) * _EV_A2_AMU_TO_CM2)
169
+ modes = v * inv[:, None]
170
+ return nu, modes