Coverage for ase/_4/optimize/lbfgs.py: 94.74%
57 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
1import numpy as np
2from scipy.sparse import coo_array
4from .method import OptimizerMethod
7class LBFGSMethod(OptimizerMethod):
8 iotype = 'lbfgs'
9 methodname = 'LBFGS'
11 def __init__(
12 self,
13 *,
14 memory: int = 100,
15 initial_inverse_hessian: coo_array,
16 ):
17 self.memory = memory
18 self.H0 = initial_inverse_hessian
19 self.iteration = 0
20 self.s: list[np.ndarray] = []
21 self.y: list[np.ndarray] = []
22 # Store also rho, to avoid calculating the dot product again and again.
23 self.rho: list[float] = []
25 def compute_step(self, gradient: np.ndarray) -> np.ndarray:
26 loopmax = np.min([self.memory, self.iteration])
27 a = np.empty(loopmax, dtype=np.float64)
29 q = gradient.copy()
30 # ## The algorithm itself:
31 for i in range(loopmax - 1, -1, -1):
32 a[i] = self.rho[i] * np.dot(self.s[i], q)
33 q -= a[i] * self.y[i]
34 z = self.H0 @ q
36 for i in range(loopmax):
37 b = self.rho[i] * np.dot(self.y[i], z)
38 z += self.s[i] * (a[i] - b)
40 self.iteration += 1
42 return -z
44 def update(
45 self,
46 pos: np.ndarray,
47 gradient: np.ndarray,
48 pos0: np.ndarray,
49 gradient0: np.ndarray,
50 ) -> None:
51 s0 = pos - pos0
52 self.s.append(s0)
54 y0 = gradient - gradient0
55 self.y.append(y0)
57 rho0 = 1.0 / np.dot(y0, s0)
58 self.rho.append(rho0)
60 if self.iteration > self.memory:
61 self.s.pop(0)
62 self.y.pop(0)
63 self.rho.pop(0)
65 def datafy(self) -> dict:
66 arr = self.H0
67 rows = arr.row.tolist()
68 cols = arr.col.tolist()
69 vals = arr.data.tolist()
70 d = {'data': list(zip(rows, cols, vals)), 'shape': arr.shape}
71 return {
72 'memory': self.memory,
73 'initial_inverse_hessian': d,
74 'shape': arr.shape,
75 's': [_.tolist() for _ in self.s],
76 'y': [_.tolist() for _ in self.y],
77 'rho': np.array(self.rho).tolist(),
78 'iteration': self.iteration,
79 }
81 @classmethod
82 def undatafy(cls, method_data: dict):
83 memory = method_data['memory']
84 data = method_data['initial_inverse_hessian']['data']
85 shape = method_data['initial_inverse_hessian']['shape']
86 rows, cols, data = zip(*[(i, j, v) for i, j, v in data])
87 arr = coo_array((data, (rows, cols)), shape=shape)
88 self = cls(memory=memory, initial_inverse_hessian=arr)
89 self.y = [np.array(_) for _ in method_data['y']]
90 self.s = [np.array(_) for _ in method_data['s']]
91 self.rho = method_data['rho']
92 self.iteration = method_data['iteration']
93 return self