Coverage for ase/_4/optimize/bfgs.py: 100.00%

47 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import numpy as np 

2 

3from .method import OptimizerMethod 

4 

5 

6def fd_hessian(target, eps=1e-5, tol=1e-8): 

7 xval_orig = target.get_x() 

8 

9 ndofs = len(xval_orig) 

10 hessian = np.empty((ndofs, ndofs)) 

11 

12 xval = xval_orig.copy() 

13 

14 for i in range(ndofs): 

15 xval[i] = xval_orig[i] + eps 

16 target.set_x(xval) 

17 gradplus = target.get_gradient().gradient 

18 xval[i] = xval_orig[i] - eps 

19 target.set_x(xval) 

20 gradminus = target.get_gradient().gradient 

21 xval[i] = xval_orig[i] 

22 

23 dgrad_dx = (gradplus - gradminus) / (2 * eps) 

24 hessian[i, :] = dgrad_dx 

25 

26 target.set_x(xval_orig) 

27 

28 symm_error = abs(hessian.T - hessian).max(initial=0.0) 

29 assert symm_error < tol, symm_error 

30 symm_hessian = 0.5 * (hessian.T + hessian) 

31 return symm_hessian 

32 

33 

34class BFGSMethod(OptimizerMethod): 

35 iotype = 'bfgs' 

36 methodname = 'BFGS' 

37 

38 def __init__(self, hessian: np.ndarray): 

39 self.hessian = hessian 

40 

41 def compute_step(self, gradient: np.ndarray) -> np.ndarray: 

42 omega, vectors = np.linalg.eigh(self.hessian) 

43 # Not sure what we should do about negative eigenvalues, 

44 # taking the absolute value is arbitrary and probably not good. 

45 return -vectors @ (gradient @ vectors / np.fabs(omega)) 

46 

47 def update( 

48 self, 

49 pos: np.ndarray, 

50 gradient: np.ndarray, 

51 pos0: np.ndarray, 

52 gradient0: np.ndarray, 

53 ) -> None: 

54 dpos = pos - pos0 

55 

56 if np.abs(dpos).max() < 1e-7: 

57 # Same configuration again (maybe a restart). 

58 # 

59 # This happens when the class is used by the old code, 

60 # but it shouldn't generally trigger in ase._4. 

61 return 

62 

63 dgradient = gradient - gradient0 

64 a = dpos @ dgradient 

65 dg = self.hessian @ dpos 

66 b = dpos @ dg 

67 self.hessian += ( 

68 np.outer(dgradient, dgradient) / a - np.outer(dg, dg) / b 

69 ) 

70 

71 def datafy(self) -> list[float]: 

72 return self.hessian.ravel().tolist() 

73 

74 @classmethod 

75 def undatafy(cls, hessian: list[float]): 

76 from math import isqrt 

77 

78 n = isqrt(len(hessian)) 

79 hessian_array = np.array(hessian).reshape(n, n) 

80 return cls(hessian_array)