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

1from __future__ import annotations 

2 

3from abc import ABC, abstractmethod 

4from dataclasses import dataclass 

5 

6import numpy as np 

7from scipy.sparse import coo_array 

8 

9from ase import Atoms 

10from ase.optimize.optimize import OptimizableAtoms as OptimizableAtoms3 

11 

12 

13@dataclass 

14class ForceGradient: 

15 gradient: np.ndarray 

16 forces: np.ndarray 

17 fnorm: float 

18 converged: bool 

19 

20 def loginfo(self) -> dict[str, float]: 

21 return {'fmax': self.fnorm} 

22 

23 

24class Optimizable4(ABC): 

25 @abstractmethod 

26 def get_value(self) -> float: ... 

27 

28 @abstractmethod 

29 def get_gradient(self) -> ForceGradient: ... 

30 

31 @abstractmethod 

32 def get_x(self) -> np.ndarray: ... 

33 

34 @abstractmethod 

35 def set_x(self, x: np.ndarray) -> None: ... 

36 

37 @abstractmethod 

38 def initial_hessian(self, *args, **kwargs) -> np.ndarray: ... 

39 

40 @abstractmethod 

41 def initial_inverse_hessian(self, *args, **kwargs) -> coo_array: ... 

42 

43 @abstractmethod 

44 def gradient_norm(self, gradient: np.ndarray) -> float: ... 

45 

46 

47class OptimizableAtoms(Optimizable4): 

48 def __init__(self, atoms: Atoms, fmax: float): 

49 self.optimizable: OptimizableAtoms3 = atoms.__ase_optimizable__() 

50 self.fmax = fmax 

51 

52 def get_value(self) -> float: 

53 return self.optimizable.get_value() 

54 

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 ) 

66 

67 def get_x(self) -> np.ndarray: 

68 return self.optimizable.get_x() 

69 

70 def set_x(self, x: np.ndarray) -> None: 

71 self.optimizable.set_x(x) 

72 

73 def initial_hessian(self, alpha: float = 70.0) -> np.ndarray: 

74 return initial_position_hessian(self.optimizable.ndofs(), alpha) 

75 

76 def initial_inverse_hessian(self, alpha: float = 70.0) -> coo_array: 

77 return initial_inverse_position_hessian(self.optimizable.ndofs(), alpha) 

78 

79 def gradient_norm(self, gradient: np.ndarray) -> float: 

80 return self.optimizable.gradient_norm(gradient) 

81 

82 

83def get_maxforce(forces: np.ndarray) -> float: 

84 return np.linalg.norm(forces, axis=1).max() 

85 

86 

87def initial_position_hessian(ndofs: int, alpha: float = 70.0) -> np.ndarray: 

88 return np.diag(np.full(ndofs, 70.0)) 

89 

90 

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))