Coverage for ase/optimize/gpmin/gpmin.py: 70.97%
124 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 warnings
3import numpy as np
4from scipy.optimize import minimize
6from ase.io.jsonio import write_json
7from ase.optimize.gpmin.gp import GaussianProcess
8from ase.optimize.gpmin.kernel import SquaredExponential
9from ase.optimize.gpmin.prior import ConstantPrior
10from ase.optimize.optimize import Optimizer
11from ase.parallel import world
12from ase.utils import deprecate_positionals
15class GPMin(Optimizer, GaussianProcess):
16 @deprecate_positionals(2)
17 def __init__(
18 self,
19 atoms,
20 restart=None,
21 logfile='-',
22 trajectory=None,
23 prior=None,
24 kernel=None,
25 noise=None,
26 weight=None,
27 scale=None,
28 batch_size=None,
29 bounds=None,
30 update_prior_strategy='maximum',
31 update_hyperparams=False,
32 **kwargs,
33 ):
34 """Optimize atomic positions using GPMin algorithm, which uses both
35 potential energies and forces information to build a PES via Gaussian
36 Process (GP) regression and then minimizes it.
38 Default behaviour:
39 --------------------
40 The default values of the scale, noise, weight, batch_size and bounds
41 parameters depend on the value of update_hyperparams. In order to get
42 the default value of any of them, they should be set up to None.
43 Default values are:
45 update_hyperparams = True
46 scale : 0.3
47 noise : 0.004
48 weight: 2.
49 bounds: 0.1
50 batch_size: 1
52 update_hyperparams = False
53 scale : 0.4
54 noise : 0.005
55 weight: 1.
56 bounds: irrelevant
57 batch_size: irrelevant
59 Parameters
60 ----------
62 atoms: :class:`~ase.Atoms`
63 The Atoms object to relax.
65 restart: str
66 JSON file used to store the training set. If set, file with
67 such a name will be searched and the data in the file incorporated
68 to the new training set, if the file exists.
70 logfile: file object or str
71 If *logfile* is a string, a file with that name will be opened.
72 Use '-' for stdout
74 trajectory: str
75 File used to store trajectory of atomic movement.
77 prior: Prior object or None
78 Prior for the GP regression of the PES surface
79 See ase.optimize.gpmin.prior
80 If *prior* is None, then it is set as the
81 ConstantPrior with the constant being updated
82 using the update_prior_strategy specified as a parameter
84 kernel: Kernel object or None
85 Kernel for the GP regression of the PES surface
86 See ase.optimize.gpmin.kernel
87 If *kernel* is None the SquaredExponential kernel is used.
88 Note: It needs to be a kernel with derivatives!!!!!
90 noise: float
91 Regularization parameter for the Gaussian Process Regression.
93 weight: float
94 Prefactor of the Squared Exponential kernel.
95 If *update_hyperparams* is False, changing this parameter
96 has no effect on the dynamics of the algorithm.
98 update_prior_strategy: str
99 Strategy to update the constant from the ConstantPrior
100 when more data is collected. It does only work when
101 Prior = None
103 options:
104 'maximum': update the prior to the maximum sampled energy
105 'init' : fix the prior to the initial energy
106 'average': use the average of sampled energies as prior
108 scale: float
109 scale of the Squared Exponential Kernel
111 update_hyperparams: bool
112 Update the scale of the Squared exponential kernel
113 every batch_size-th iteration by maximizing the
114 marginal likelihood.
116 batch_size: int
117 Number of new points in the sample before updating
118 the hyperparameters.
119 Only relevant if the optimizer is executed in update_hyperparams
120 mode: (update_hyperparams = True)
122 bounds: float, 0<bounds<1
123 Set bounds to the optimization of the hyperparameters.
124 Let t be a hyperparameter. Then it is optimized under the
125 constraint (1-bound)*t_0 <= t <= (1+bound)*t_0
126 where t_0 is the value of the hyperparameter in the previous
127 step.
128 If bounds is False, no constraints are set in the optimization of
129 the hyperparameters.
131 kwargs : dict, optional
132 Extra arguments passed to
133 :class:`~ase.optimize.optimize.Optimizer`.
135 .. warning:: The memory of the optimizer scales as O(n²N²) where
136 N is the number of atoms and n the number of steps.
137 If the number of atoms is sufficiently high, this
138 may cause a memory issue.
139 This class prints a warning if the user tries to
140 run GPMin with more than 100 atoms in the unit cell.
142 Examples
143 --------
145 >>> from ase import Atoms
146 >>> from ase.calculators.emt import EMT
147 >>> from ase.optimize.gpmin.gpmin import GPMin
148 ...
149 >>> system = Atoms(
150 ... 'N2',
151 ... positions = [(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)],
152 ... calculator=EMT()
153 ... )
154 >>> dyn = GPMin(system)
155 >>> dyn.run(fmax=0.05) # doctest:+ELLIPSIS, +NORMALIZE_WHITESPACE
156 Step Time Energy fmax
157 GPMin: 0 ... 0.440344 3.251800
158 GPMin: 1 ... 0.357046 2.961912
159 GPMin: 2 ... 0.262953 0.116630
160 GPMin: 3 ... 0.262777 0.004907
161 ...
162 """
163 # Warn the user if the number of atoms is very large
164 if len(atoms) > 100:
165 warning = (
166 'Possible Memory Issue. There are more than '
167 '100 atoms in the unit cell. The memory '
168 'of the process will increase with the number '
169 'of steps, potentially causing a memory issue. '
170 'Consider using a different optimizer.'
171 )
173 warnings.warn(warning)
175 # Give it default hyperparameters
176 if update_hyperparams: # Updated GPMin
177 if scale is None:
178 scale = 0.3
179 if noise is None:
180 noise = 0.004
181 if weight is None:
182 weight = 2.0
183 if bounds is None:
184 self.eps = 0.1
185 elif bounds is False:
186 self.eps = None
187 else:
188 self.eps = bounds
189 if batch_size is None:
190 self.nbatch = 1
191 else:
192 self.nbatch = batch_size
193 else: # GPMin without updates
194 if scale is None:
195 scale = 0.4
196 if noise is None:
197 noise = 0.001
198 if weight is None:
199 weight = 1.0
200 if bounds is not None:
201 warning = (
202 'The parameter bounds is of no use '
203 'if update_hyperparams is False. '
204 'The value provided by the user '
205 'is being ignored.'
206 )
207 warnings.warn(warning, UserWarning)
208 if batch_size is not None:
209 warning = (
210 'The parameter batch_size is of no use '
211 'if update_hyperparams is False. '
212 'The value provided by the user '
213 'is being ignored.'
214 )
215 warnings.warn(warning, UserWarning)
217 # Set the variables to something anyways
218 self.eps = False
219 self.nbatch = None
221 self.strategy = update_prior_strategy
222 self.update_hp = update_hyperparams
223 self.function_calls = 1
224 self.force_calls = 0
225 self.x_list = [] # Training set features
226 self.y_list = [] # Training set targets
228 Optimizer.__init__(
229 self,
230 atoms,
231 restart=restart,
232 logfile=logfile,
233 trajectory=trajectory,
234 **kwargs,
235 )
236 if prior is None:
237 self.update_prior = True
238 prior = ConstantPrior(constant=None)
239 else:
240 self.update_prior = False
242 if kernel is None:
243 kernel = SquaredExponential()
244 GaussianProcess.__init__(self, prior, kernel)
245 self.set_hyperparams(np.array([weight, scale, noise]))
247 def acquisition(self, r):
248 e = self.predict(r)
249 return e[0], e[1:]
251 def update(self, r, e, f):
252 """Update the PES
254 Update the training set, the prior and the hyperparameters.
255 Finally, train the model
256 """
257 # update the training set
258 self.x_list.append(r)
259 y = np.append(np.array(e).reshape(-1), -f)
260 self.y_list.append(y)
262 # Set/update the constant for the prior
263 if self.update_prior:
264 if self.strategy == 'average':
265 av_e = np.mean(np.array(self.y_list)[:, 0])
266 self.prior.set_constant(av_e)
267 elif self.strategy == 'maximum':
268 max_e = np.max(np.array(self.y_list)[:, 0])
269 self.prior.set_constant(max_e)
270 elif self.strategy == 'init':
271 self.prior.set_constant(e)
272 self.update_prior = False
274 # update hyperparams
275 if (
276 self.update_hp
277 and self.function_calls % self.nbatch == 0
278 and self.function_calls != 0
279 ):
280 self.fit_to_batch()
282 # build the model
283 self.train(np.array(self.x_list), np.array(self.y_list))
285 def relax_model(self, r0):
286 result = minimize(self.acquisition, r0, method='L-BFGS-B', jac=True)
287 if result.success:
288 return result.x
289 else:
290 self.dump()
291 raise RuntimeError(
292 'The minimization of the acquisition function has not converged'
293 )
295 def fit_to_batch(self):
296 """Fit hyperparameters keeping the ratio noise/weight fixed"""
297 ratio = self.noise / self.kernel.weight
298 self.fit_hyperparameters(
299 np.array(self.x_list), np.array(self.y_list), eps=self.eps
300 )
301 self.noise = ratio * self.kernel.weight
303 def step(self, f=None):
304 gradient = self._get_gradient(f)
305 optimizable = self.optimizable
306 f = -gradient.reshape(-1, 3)
308 r0 = optimizable.get_x()
309 e0 = optimizable.get_value()
310 self.update(r0, e0, f)
312 r1 = self.relax_model(r0)
313 optimizable.set_x(r1)
314 e1 = optimizable.get_value()
315 f1 = -optimizable.get_gradient()
316 self.function_calls += 1
317 self.force_calls += 1
318 count = 0
319 while e1 >= e0:
320 self.update(r1, e1, f1)
321 r1 = self.relax_model(r0)
323 optimizable.set_x(r1)
324 e1 = optimizable.get_value()
325 f1 = -optimizable.get_gradient()
326 self.function_calls += 1
327 self.force_calls += 1
328 if self.gradient_converged(f1):
329 break
331 count += 1
332 if count == 30:
333 raise RuntimeError('A descent model could not be built')
334 self.dump()
336 def dump(self):
337 """Save the training set"""
338 if world.rank == 0 and self.restart is not None:
339 with open(self.restart, 'w') as fd:
340 write_json(fd, (self.x_list, self.y_list))
342 def read(self):
343 self.x_list, self.y_list = self.load()