Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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 def __init__(self): 

15 """Basic prior implementation.""" 

16 pass 

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 def __init__(self): 

30 Prior.__init__(self) 

31 

32 def potential(self, x): 

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

34 

35 

36class ConstantPrior(Prior): 

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

38 

39 Parameters: 

40 

41 constant: energy value for the constant. 

42 

43 Example: 

44 

45 >>> from ase.optimize import GPMin 

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

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

48 """ 

49 def __init__(self, constant): 

50 self.constant = constant 

51 Prior.__init__(self) 

52 

53 def potential(self, x): 

54 d = x.shape[0] 

55 output = np.zeros(d+1) 

56 output[0] = self.constant 

57 return output 

58 

59 def set_constant(self, constant): 

60 self.constant = constant 

61 

62 

63class CalculatorPrior(Prior): 

64 """CalculatorPrior object, allows the user to 

65 use another calculator as prior function instead of the 

66 default constant. 

67 

68 Parameters: 

69 

70 atoms: the Atoms object 

71 calculator: one of ASE's calculators 

72 """ 

73 def __init__(self, atoms, calculator): 

74 Prior.__init__(self) 

75 self.atoms = atoms.copy() 

76 self.atoms.calc = calculator 

77 

78 def potential(self, x): 

79 self.atoms.set_positions(x.reshape(-1, 3)) 

80 V = self.atoms.get_potential_energy(force_consistent=True) 

81 gradV = -self.atoms.get_forces().reshape(-1) 

82 return np.append(np.array(V).reshape(-1), gradV)