Coverage for ase/_4/optimize/optimizable.py: 100.00%
46 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 __future__ import annotations
3from abc import ABC, abstractmethod
4from dataclasses import dataclass
6import numpy as np
7from scipy.sparse import coo_array
9from ase import Atoms
10from ase.optimize.optimize import OptimizableAtoms as OptimizableAtoms3
13@dataclass
14class ForceGradient:
15 gradient: np.ndarray
16 forces: np.ndarray
17 fnorm: float
18 converged: bool
20 def loginfo(self) -> dict[str, float]:
21 return {'fmax': self.fnorm}
24class Optimizable4(ABC):
25 @abstractmethod
26 def get_value(self) -> float: ...
28 @abstractmethod
29 def get_gradient(self) -> ForceGradient: ...
31 @abstractmethod
32 def get_x(self) -> np.ndarray: ...
34 @abstractmethod
35 def set_x(self, x: np.ndarray) -> None: ...
37 @abstractmethod
38 def initial_hessian(self, *args, **kwargs) -> np.ndarray: ...
40 @abstractmethod
41 def initial_inverse_hessian(self, *args, **kwargs) -> coo_array: ...
43 @abstractmethod
44 def gradient_norm(self, gradient: np.ndarray) -> float: ...
47class OptimizableAtoms(Optimizable4):
48 def __init__(self, atoms: Atoms, fmax: float):
49 self.optimizable: OptimizableAtoms3 = atoms.__ase_optimizable__()
50 self.fmax = fmax
52 def get_value(self) -> float:
53 return self.optimizable.get_value()
55 def get_gradient(self) -> ForceGradient:
56 forces = self.optimizable.atoms.get_forces()
57 gradient = -forces.ravel()
58 fnorm = get_maxforce(forces)
59 converged = fnorm < self.fmax
60 return ForceGradient(
61 gradient=gradient,
62 forces=forces,
63 fnorm=fnorm,
64 converged=converged,
65 )
67 def get_x(self) -> np.ndarray:
68 return self.optimizable.get_x()
70 def set_x(self, x: np.ndarray) -> None:
71 self.optimizable.set_x(x)
73 def initial_hessian(self, alpha: float = 70.0) -> np.ndarray:
74 return initial_position_hessian(self.optimizable.ndofs(), alpha)
76 def initial_inverse_hessian(self, alpha: float = 70.0) -> coo_array:
77 return initial_inverse_position_hessian(self.optimizable.ndofs(), alpha)
79 def gradient_norm(self, gradient: np.ndarray) -> float:
80 return self.optimizable.gradient_norm(gradient)
83def get_maxforce(forces: np.ndarray) -> float:
84 return np.linalg.norm(forces, axis=1).max()
87def initial_position_hessian(ndofs: int, alpha: float = 70.0) -> np.ndarray:
88 return np.diag(np.full(ndofs, 70.0))
91def initial_inverse_position_hessian(
92 ndofs: int,
93 alpha: float = 70.0,
94) -> coo_array:
95 diags = np.full(ndofs, 1.0 / alpha)
96 rows = cols = np.arange(ndofs)
97 return coo_array((diags, (rows, cols)), shape=(ndofs, ndofs))