Coverage for ase/optimize/gpmin/prior.py: 73.53%
34 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
4class Prior:
5 """Base class for all priors for the bayesian optimizer.
7 The __init__ method and the prior method are implemented here.
8 Each child class should implement its own potential method, that will be
9 called by the prior method implemented here.
11 When used, the prior should be initialized outside the optimizer and the
12 Prior object should be passed as a function to the optimizer.
13 """
15 def __init__(self):
16 """Basic prior implementation."""
18 def prior(self, x):
19 """Actual prior function, common to all Priors"""
20 if len(x.shape) > 1:
21 n = x.shape[0]
22 return np.hstack([self.potential(x[i, :]) for i in range(n)])
23 else:
24 return self.potential(x)
27class ZeroPrior(Prior):
28 """ZeroPrior object, consisting on a constant prior with 0eV energy."""
30 def __init__(self):
31 Prior.__init__(self)
33 def potential(self, x):
34 return np.zeros(x.shape[0] + 1)
37class ConstantPrior(Prior):
38 """Constant prior, with energy = constant and zero forces
40 Parameters
41 ----------
43 constant: energy value for the constant.
45 Example:
47 >>> from ase import Atoms
48 >>> from ase.calculators.emt import EMT
49 >>> from ase.optimize.gpmin.gpmin import GPMin
50 >>> from ase.optimize.gpmin.prior import ConstantPrior
51 ...
52 >>> system = Atoms(
53 ... 'N2',
54 ... positions = [(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)],
55 ... calculator=EMT()
56 ... )
57 >>> dyn = GPMin(system, prior = ConstantPrior(10))
58 >>> dyn.run(fmax=0.05) # doctest:+ELLIPSIS, +NORMALIZE_WHITESPACE
59 Step Time Energy fmax
60 GPMin: 0 ... 0.440344 3.251800
61 GPMin: 1 ... 0.262968 0.122695
62 GPMin: 2 ... 0.262777 0.005044
63 ...
64 """
66 def __init__(self, constant):
67 self.constant = constant
68 Prior.__init__(self)
70 def potential(self, x):
71 d = x.shape[0]
72 output = np.zeros(d + 1)
73 output[0] = self.constant
74 return output
76 def set_constant(self, constant):
77 self.constant = constant
80class CalculatorPrior(Prior):
81 """CalculatorPrior object, allows the user to
82 use another calculator as prior function instead of the
83 default constant.
85 Parameters
86 ----------
88 atoms: the Atoms object
89 calculator: one of ASE's calculators
90 """
92 def __init__(self, atoms, calculator):
93 Prior.__init__(self)
94 self.atoms = atoms.copy()
95 self.atoms.calc = calculator
97 def potential(self, x):
98 self.atoms.set_positions(x.reshape(-1, 3))
99 V = self.atoms.get_potential_energy(force_consistent=True)
100 gradV = -self.atoms.get_forces().reshape(-1)
101 return np.append(np.array(V).reshape(-1), gradV)