Coverage for /builds/kinetik161/ase/ase/optimize/gpmin/prior.py: 73.53%
34 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-12-10 11:04 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-12-10 11:04 +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:
42 constant: energy value for the constant.
44 Example:
46 >>> from ase.optimize import GPMin
47 >>> from ase.optimize.gpmin.prior import ConstantPrior
48 >>> op = GPMin(atoms, Prior = ConstantPrior(10)
49 """
51 def __init__(self, constant):
52 self.constant = constant
53 Prior.__init__(self)
55 def potential(self, x):
56 d = x.shape[0]
57 output = np.zeros(d + 1)
58 output[0] = self.constant
59 return output
61 def set_constant(self, constant):
62 self.constant = constant
65class CalculatorPrior(Prior):
66 """CalculatorPrior object, allows the user to
67 use another calculator as prior function instead of the
68 default constant.
70 Parameters:
72 atoms: the Atoms object
73 calculator: one of ASE's calculators
74 """
76 def __init__(self, atoms, calculator):
77 Prior.__init__(self)
78 self.atoms = atoms.copy()
79 self.atoms.calc = calculator
81 def potential(self, x):
82 self.atoms.set_positions(x.reshape(-1, 3))
83 V = self.atoms.get_potential_energy(force_consistent=True)
84 gradV = -self.atoms.get_forces().reshape(-1)
85 return np.append(np.array(V).reshape(-1), gradV)