Coverage for ase/optimize/gpmin/gp.py: 53.85%

65 statements  

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

1import numpy as np 

2from scipy.linalg import cho_factor, cho_solve, solve_triangular 

3from scipy.optimize import minimize 

4 

5from ase.optimize.gpmin.kernel import SquaredExponential 

6from ase.optimize.gpmin.prior import ZeroPrior 

7 

8 

9class GaussianProcess: 

10 """Gaussian Process Regression 

11 It is recommended to be used with other Priors and Kernels from 

12 ase.optimize.gpmin 

13 

14 Parameters 

15 ---------- 

16 

17 prior: Prior class, as in ase.optimize.gpmin.prior 

18 Defaults to ZeroPrior 

19 

20 kernel: Kernel function for the regression, as in 

21 ase.optimize.gpmin.kernel 

22 Defaults to the Squared Exponential kernel with derivatives 

23 """ 

24 

25 def __init__(self, prior=None, kernel=None): 

26 if kernel is None: 

27 self.kernel = SquaredExponential() 

28 else: 

29 self.kernel = kernel 

30 

31 if prior is None: 

32 self.prior = ZeroPrior() 

33 else: 

34 self.prior = prior 

35 

36 def set_hyperparams(self, params): 

37 """Set hyperparameters of the regression. 

38 This is a list containing the parameters of the 

39 kernel and the regularization (noise) 

40 of the method as the last entry. 

41 """ 

42 self.hyperparams = params 

43 self.kernel.set_params(params[:-1]) 

44 self.noise = params[-1] 

45 

46 def train(self, X, Y, noise=None): 

47 """Produces a PES model from data. 

48 

49 Given a set of observations, X, Y, compute the K matrix 

50 of the Kernel given the data (and its cholesky factorization) 

51 This method should be executed whenever more data is added. 

52 

53 Parameters 

54 ---------- 

55 

56 X: observations (i.e. positions). numpy array with shape: nsamples x D 

57 Y: targets (i.e. energy and forces). numpy array with 

58 shape (nsamples, D+1) 

59 noise: Noise parameter in the case it needs to be restated. 

60 """ 

61 if noise is not None: 

62 self.noise = noise # Set noise attribute to a different value 

63 

64 self.X = X.copy() # Store the data in an attribute 

65 n = self.X.shape[0] 

66 D = self.X.shape[1] 

67 regularization = np.array( 

68 n * ([self.noise * self.kernel.l] + D * [self.noise]) 

69 ) 

70 

71 K = self.kernel.kernel_matrix(X) # Compute the kernel matrix 

72 K[range(K.shape[0]), range(K.shape[0])] += regularization**2 

73 

74 self.m = self.prior.prior(X) 

75 self.a = Y.flatten() - self.m 

76 self.L, self.lower = cho_factor(K, lower=True, check_finite=True) 

77 cho_solve( 

78 (self.L, self.lower), self.a, overwrite_b=True, check_finite=True 

79 ) 

80 

81 def predict(self, x, get_variance=False): 

82 """Given a trained Gaussian Process, it predicts the value and the 

83 uncertainty at point x. It returns f and V: 

84 f : prediction: [y, grady] 

85 V : Covariance matrix. Its diagonal is the variance of each component 

86 of f. 

87 

88 Parameters 

89 ---------- 

90 

91 x (1D np.array): The position at which the prediction is computed 

92 get_variance (bool): if False, only the prediction f is returned 

93 if True, the prediction f and the variance V are 

94 returned: Note V is O(D*nsample2) 

95 """ 

96 n = self.X.shape[0] 

97 k = self.kernel.kernel_vector(x, self.X, n) 

98 f = self.prior.prior(x) + np.dot(k, self.a) 

99 if get_variance: 

100 v = solve_triangular( 

101 self.L, k.T.copy(), lower=True, check_finite=False 

102 ) 

103 variance = self.kernel.kernel(x, x) 

104 # covariance = np.matmul(v.T, v) 

105 covariance = np.tensordot(v, v, axes=(0, 0)) 

106 V = variance - covariance 

107 return f, V 

108 return f 

109 

110 def neg_log_likelihood(self, params, *args): 

111 """Negative logarithm of the marginal likelihood and its derivative. 

112 It has been built in the form that suits the best its optimization, 

113 with the scipy minimize module, to find the optimal hyperparameters. 

114 

115 Parameters 

116 ---------- 

117 

118 l: The scale for which we compute the marginal likelihood 

119 *args: Should be a tuple containing the inputs and targets 

120 in the training set- 

121 """ 

122 X, Y = args 

123 # Come back to this 

124 self.kernel.set_params(np.array([params[0], params[1], self.noise])) 

125 self.train(X, Y) 

126 y = Y.flatten() 

127 

128 # Compute log likelihood 

129 logP = ( 

130 -0.5 * np.dot(y - self.m, self.a) 

131 - np.sum(np.log(np.diag(self.L))) 

132 - X.shape[0] * 0.5 * np.log(2 * np.pi) 

133 ) 

134 

135 # Gradient of the loglikelihood 

136 grad = self.kernel.gradient(X) 

137 

138 # vectorizing the derivative of the log likelihood 

139 D_P_input = np.array( 

140 [np.dot(np.outer(self.a, self.a), g) for g in grad] 

141 ) 

142 D_complexity = np.array( 

143 [cho_solve((self.L, self.lower), g) for g in grad] 

144 ) 

145 

146 DlogP = 0.5 * np.trace(D_P_input - D_complexity, axis1=1, axis2=2) 

147 return -logP, -DlogP 

148 

149 def fit_hyperparameters(self, X, Y, tol=1e-2, eps=None): 

150 """Given a set of observations, X, Y; optimize the scale 

151 of the Gaussian Process maximizing the marginal log-likelihood. 

152 This method calls TRAIN there is no need to call the TRAIN method 

153 again. The method also sets the parameters of the Kernel to their 

154 optimal value at the end of execution 

155 

156 Parameters 

157 ---------- 

158 

159 X: observations(i.e. positions). numpy array with shape: nsamples x D 

160 Y: targets (i.e. energy and forces). 

161 numpy array with shape (nsamples, D+1) 

162 tol: tolerance on the maximum component of the gradient of the 

163 log-likelihood. 

164 (See scipy's L-BFGS-B documentation: 

165 https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) 

166 eps: include bounds to the hyperparameters as a +- a percentage 

167 if eps is None there are no bounds in the optimization 

168 

169 Returns 

170 ------- 

171 

172 result (dict) : 

173 result = {'hyperparameters': (numpy.array) New hyperparameters, 

174 'converged': (bool) True if it converged, 

175 False otherwise 

176 } 

177 """ 

178 params = np.copy(self.hyperparams)[:2] 

179 arguments = (X, Y) 

180 if eps is not None: 

181 bounds = [((1 - eps) * p, (1 + eps) * p) for p in params] 

182 else: 

183 bounds = None 

184 

185 result = minimize( 

186 self.neg_log_likelihood, 

187 params, 

188 args=arguments, 

189 method='L-BFGS-B', 

190 jac=True, 

191 bounds=bounds, 

192 options={'gtol': tol, 'ftol': 0.01 * tol}, 

193 ) 

194 

195 if not result.success: 

196 converged = False 

197 else: 

198 converged = True 

199 self.hyperparams = np.array( 

200 [result.x.copy()[0], result.x.copy()[1], self.noise] 

201 ) 

202 self.set_hyperparams(self.hyperparams) 

203 return {'hyperparameters': self.hyperparams, 'converged': converged}