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

1import numpy as np 

2 

3 

4class Prior(): 

5 """Base class for all priors for the bayesian optimizer. 

6 

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. 

10 

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 """ 

14 

15 def __init__(self): 

16 """Basic prior implementation.""" 

17 

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) 

25 

26 

27class ZeroPrior(Prior): 

28 """ZeroPrior object, consisting on a constant prior with 0eV energy.""" 

29 

30 def __init__(self): 

31 Prior.__init__(self) 

32 

33 def potential(self, x): 

34 return np.zeros(x.shape[0] + 1) 

35 

36 

37class ConstantPrior(Prior): 

38 """Constant prior, with energy = constant and zero forces 

39 

40 Parameters: 

41 

42 constant: energy value for the constant. 

43 

44 Example: 

45 

46 >>> from ase.optimize import GPMin 

47 >>> from ase.optimize.gpmin.prior import ConstantPrior 

48 >>> op = GPMin(atoms, Prior = ConstantPrior(10) 

49 """ 

50 

51 def __init__(self, constant): 

52 self.constant = constant 

53 Prior.__init__(self) 

54 

55 def potential(self, x): 

56 d = x.shape[0] 

57 output = np.zeros(d + 1) 

58 output[0] = self.constant 

59 return output 

60 

61 def set_constant(self, constant): 

62 self.constant = constant 

63 

64 

65class CalculatorPrior(Prior): 

66 """CalculatorPrior object, allows the user to 

67 use another calculator as prior function instead of the 

68 default constant. 

69 

70 Parameters: 

71 

72 atoms: the Atoms object 

73 calculator: one of ASE's calculators 

74 """ 

75 

76 def __init__(self, atoms, calculator): 

77 Prior.__init__(self) 

78 self.atoms = atoms.copy() 

79 self.atoms.calc = calculator 

80 

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)