Coverage for ase/optimize/climbfixinternals.py: 98.63%
73 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1from typing import IO, Any
3from numpy.linalg import norm
5from ase import Atoms
6from ase.constraints import FixInternals
7from ase.optimize.bfgs import BFGS
8from ase.optimize.optimize import Optimizer
9from ase.utils import deprecate_positionals
12class BFGSClimbFixInternals(BFGS):
13 """Class for transition state search and optimization
15 Climbs the 1D reaction coordinate defined as constrained internal coordinate
16 via the :class:`~ase.constraints.FixInternals` class while minimizing all
17 remaining degrees of freedom.
19 Details: Two optimizers, 'A' and 'B', are applied orthogonal to each other.
20 Optimizer 'A' climbs the constrained coordinate while optimizer 'B'
21 optimizes the remaining degrees of freedom after each climbing step.
22 Optimizer 'A' uses the BFGS algorithm to climb along the projected force of
23 the selected constraint. Optimizer 'B' can be any ASE optimizer
24 (default: BFGS).
26 In combination with other constraints, the order of constraints matters.
27 Generally, the FixInternals constraint should come first in the list of
28 constraints.
29 This has been tested with the :class:`~ase.constraints.FixAtoms` constraint.
31 Inspired by concepts described by P. N. Plessow. [1]_
33 .. [1] Plessow, P. N., Efficient Transition State Optimization of Periodic
34 Structures through Automated Relaxed Potential Energy Surface Scans.
35 J. Chem. Theory Comput. 2018, 14 (2), 981–990.
36 https://doi.org/10.1021/acs.jctc.7b01070.
38 .. note::
39 Convergence is based on 'fmax' of the total forces which is the sum of
40 the projected forces and the forces of the remaining degrees of freedom.
41 This value is logged in the 'logfile'. Optimizer 'B' logs 'fmax' of the
42 remaining degrees of freedom without the projected forces. The projected
43 forces can be inspected using the :meth:`get_projected_forces` method:
45 for _ in dyn.irun():
46 projected_forces = dyn.get_projected_forces()
48 Example
49 -------
50 .. literalinclude:: ../../ase/test/optimize/test_climb_fix_internals.py
51 :end-before: # end example for documentation
52 """
54 @deprecate_positionals(2)
55 def __init__(
56 self,
57 atoms: Atoms,
58 restart: str | None = None,
59 logfile: IO | str = '-',
60 trajectory: str | None = None,
61 maxstep: float | None = None,
62 alpha: float | None = None,
63 climb_coordinate: list[FixInternals] | None = None,
64 optB: type[Optimizer] = BFGS,
65 optB_kwargs: dict[str, Any] | None = None,
66 optB_fmax: float = 0.05,
67 optB_fmax_scaling: float = 0.0,
68 **kwargs,
69 ):
70 """Allowed parameters are similar to the parent class
71 :class:`~ase.optimize.bfgs.BFGS` with the following additions:
73 Parameters
74 ----------
75 climb_coordinate: list
76 Specifies which subconstraint of the
77 :class:`~ase.constraints.FixInternals` constraint is to be climbed.
78 Provide the corresponding nested list of indices
79 (including coefficients in the case of Combo constraints).
80 See the example above.
82 optB: any ASE optimizer, optional
83 Optimizer 'B' for optimization of the remaining degrees of freedom
84 after each climbing step.
86 optB_kwargs: dict, optional
87 Specifies keyword arguments to be passed to optimizer 'B' at its
88 initialization. By default, optimizer 'B' writes a logfile and
89 trajectory (optB_{...}.log, optB_{...}.traj) where {...} is the
90 current value of the ``climb_coordinate``. Set ``logfile`` to '-'
91 for console output. Set ``trajectory`` to 'None' to suppress
92 writing of the trajectory file.
94 optB_fmax: float, optional
95 Specifies the convergence criterion 'fmax' of optimizer 'B'.
97 optB_fmax_scaling: float, optional
98 Scaling factor to dynamically tighten 'fmax' of optimizer 'B' to
99 the value of ``optB_fmax`` when close to convergence.
100 Can speed up the climbing process. The scaling formula is
102 'fmax' = ``optB_fmax`` + ``optB_fmax_scaling``
103 :math:`\\cdot` norm_of_projected_forces
105 The final optimization with optimizer 'B' is
106 performed with ``optB_fmax`` independent of ``optB_fmax_scaling``.
107 """
108 self.targetvalue = None # may be assigned during restart in self.read()
109 super().__init__(
110 atoms,
111 restart=restart,
112 logfile=logfile,
113 trajectory=trajectory,
114 maxstep=maxstep,
115 alpha=alpha,
116 **kwargs,
117 )
119 self.constr2climb = get_constr2climb(
120 self.optimizable.atoms, climb_coordinate
121 )
122 self.targetvalue = self.targetvalue or self.constr2climb.targetvalue
124 self.optB = optB
125 self.optB_kwargs = optB_kwargs or {}
126 self.optB_fmax = optB_fmax
127 self.scaling = optB_fmax_scaling
128 # log optimizer 'B' in logfiles named after current value of constraint
129 self.autolog = 'logfile' not in self.optB_kwargs
130 self.autotraj = 'trajectory' not in self.optB_kwargs
132 def Nx3(self, array):
133 return array.reshape(-1, 3)
135 def read(self):
136 (self.H, self.pos0, self.forces0, self.maxstep, self.targetvalue) = (
137 self.load()
138 )
140 def step(self):
141 self.relax_remaining_dof() # optimization with optimizer 'B'
143 pos, dpos = self.pretend2climb() # with optimizer 'A'
144 self.update_positions_and_targetvalue(pos, dpos) # obey other constr.
146 self.dump(
147 (self.H, self.pos0, self.forces0, self.maxstep, self.targetvalue)
148 )
150 def pretend2climb(self):
151 """Get directions for climbing and climb with optimizer 'A'."""
152 proj_forces = self.get_projected_forces()
153 pos = self.optimizable.get_x()
154 dpos, steplengths = self.prepare_step(pos, -proj_forces)
155 dpos = self.determine_step(dpos, steplengths)
156 return pos, dpos
158 def update_positions_and_targetvalue(self, pos, dpos):
159 """Adjust constrained targetvalue of constraint and update positions."""
160 self.constr2climb.adjust_positions(
161 self.Nx3(pos), self.Nx3(pos + dpos)
162 ) # update sigma
163 self.targetvalue += self.constr2climb.sigma # climb constraint
164 self.constr2climb.targetvalue = self.targetvalue # adjust positions
165 # XXX very magical ...
166 self.optimizable.set_x(self.optimizable.get_x()) # to targetvalue
168 def relax_remaining_dof(self):
169 """Optimize remaining degrees of freedom with optimizer 'B'."""
170 if self.autolog:
171 self.optB_kwargs['logfile'] = f'optB_{self.targetvalue}.log'
172 if self.autotraj:
173 self.optB_kwargs['trajectory'] = f'optB_{self.targetvalue}.traj'
174 fmax = self.get_scaled_fmax()
175 with self.optB(self.optimizable.atoms, **self.optB_kwargs) as opt:
176 opt.run(fmax) # optimize with scaled fmax
177 grad = self.optimizable.get_gradient()
178 if self.gradient_converged(grad) and fmax > self.optB_fmax:
179 # (final) optimization with desired fmax
180 opt.run(self.optB_fmax)
182 def get_scaled_fmax(self):
183 """Return the adaptive 'fmax' based on the estimated distance to the
184 transition state."""
185 return self.optB_fmax + self.scaling * norm(
186 self.constr2climb.projected_forces
187 )
189 def get_projected_forces(self):
190 """Return the projected forces along the constrained coordinate in
191 uphill direction (negative sign)."""
192 forces = self.constr2climb.projected_forces
193 # XXX simplify me once optimizable shape shenanigans have converged
194 forces = -forces.ravel()
195 return forces
197 def get_total_forces(self):
198 """Return forces obeying all constraints plus projected forces."""
199 forces = -self.optimizable.get_gradient()
200 return forces + self.get_projected_forces()
202 def gradient_converged(self, gradient):
203 """Did the optimization converge based on the total forces?"""
204 # XXX ignoring gradient
205 gradient = -self.get_total_forces().ravel()
206 return super().gradient_converged(gradient=gradient)
208 def log(self, gradient):
209 forces = self.get_total_forces()
210 super().log(gradient=-forces.ravel())
213def get_fixinternals(atoms):
214 """Get pointer to the FixInternals constraint on the atoms object."""
215 all_constr_types = list(map(type, atoms.constraints))
216 index = all_constr_types.index(FixInternals) # locate constraint
217 return atoms.constraints[index]
220def get_constr2climb(atoms, climb_coordinate):
221 """Get pointer to the subconstraint that is to be climbed.
222 Identification by its definition via indices (and coefficients)."""
223 constr = get_fixinternals(atoms)
224 return constr.get_subconstraint(atoms, climb_coordinate)