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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

from ase import Atoms 

from mchammer.calculators.target_vector_calculator import TargetVectorCalculator 

from .canonical_ensemble import CanonicalEnsemble 

from .canonical_annealing import _cooling_exponential 

import numpy as np 

from typing import List 

import random 

from icet.io.logging import logger 

logger = logger.getChild('target_cluster_vector_annealing') 

 

 

class TargetClusterVectorAnnealing(): 

""" 

Instances of this class allow one to carry out simulated annealing 

towards a target cluster vector. Because it is impossible 

to know *a priori* which supercell shape accomodates the best 

match, this ensemble allows the annealing to be done for multiple 

:class:`ase.Atoms` objects at the same time. 

 

Parameters 

---------- 

structure 

atomic configurations to be used in the Monte Carlo simulation; 

also defines the initial occupation vectors 

calculators 

calculators corresponding to each :class:`Atoms <ase.Atoms>` 

object 

T_start 

artificial temperature at which annealing is started 

T_stop : float 

artificial temperature at which annealing is stopped 

random_seed : int 

seed for random number generator used in the Monte Carlo 

simulation 

""" 

 

def __init__(self, structure: List[Atoms], 

calculators: List[TargetVectorCalculator], 

T_start: float = 5.0, T_stop: float = 0.001, 

random_seed: int = None) -> None: 

 

if isinstance(structure, Atoms): 

raise ValueError( 

'A list of ASE Atoms (supercells) must be provided') 

if len(structure) != len(calculators): 

raise ValueError('There must be as many supercells as there ' 

'are calculators ({} != {})'.format(len(structure), 

len(calculators))) 

 

logger.info('Initializing target cluster vector annealing ' 

'with {} supercells'.format(len(structure))) 

 

# random number generator 

if random_seed is None: 

self._random_seed = random.randint(0, 1e16) 

else: 

self._random_seed = random_seed 

random.seed(a=self._random_seed) 

 

# Initialize an ensemble for each supercell 

sub_ensembles = [] 

for ens_id, (supercell, calculator) in enumerate(zip(structure, calculators)): 

sub_ensembles.append(CanonicalEnsemble(structure=supercell, 

calculator=calculator, 

random_seed=random.randint( 

0, 1e16), 

user_tag='ensemble_{}'.format( 

ens_id), 

temperature=T_start, 

data_container=None)) 

self._sub_ensembles = sub_ensembles 

self._current_score = self._sub_ensembles[0].calculator.calculate_total( 

self._sub_ensembles[0].configuration.occupations) 

self._best_score = self._current_score 

self._best_structure = structure[0] 

self._temperature = T_start 

self._T_start = T_start 

self._T_stop = T_stop 

self._total_trials = 0 

self._accepted_trials = 0 

self._n_steps = 42 

 

def generate_structure(self, number_of_trial_steps: int = None) -> Atoms: 

""" 

Run a structure annealing simulation. 

 

Parameters 

---------- 

number_of_trial_steps 

Total number of trial steps to perform. If None, 

run (on average) 3000 steps per supercell 

""" 

93 ↛ 94line 93 didn't jump to line 94, because the condition on line 93 was never true if number_of_trial_steps is None: 

self._n_steps = 3000 * len(self._sub_ensembles) 

else: 

self._n_steps = number_of_trial_steps 

 

self._temperature = self._T_start 

self._total_trials = 0 

self._accepted_trials = 0 

while self.total_trials < self.n_steps: 

if self._total_trials % 1000 == 0: 

logger.info('MC step {}/{} ({} accepted trials, ' 

'temperature {:.3f}), ' 

'best score: {:.3f}'.format(self.total_trials, 

self.n_steps, 

self.accepted_trials, 

self.temperature, 

self.best_score)) 

self._do_trial_step() 

return self.best_structure 

 

def _do_trial_step(self): 

""" Carries out one Monte Carlo trial step. """ 

self._temperature = _cooling_exponential( 

self.total_trials, self.T_start, self.T_stop, self.n_steps) 

self._total_trials += 1 

 

# Choose a supercell 

ensemble = random.choice(self._sub_ensembles) 

 

# Choose two sites and swap 

sublattice_index = ensemble.get_random_sublattice_index( 

ensemble._swap_sublattice_probabilities) 

sites, species = ensemble.configuration.get_swapped_state( 

sublattice_index) 

 

# Update occupations so that the cluster vector (and its score) 

# can be calculated 

ensemble.configuration.update_occupations(sites, species) 

new_score = ensemble.calculator.calculate_total( 

ensemble.configuration.occupations) 

 

if self._acceptance_condition(new_score - self.current_score): 

self._current_score = new_score 

self._accepted_trials += 1 

 

# Since we are looking for the best structures we want to 

# keep track of the best one we have found as yet (the 

# current one may have a worse score) 

if self._current_score < self._best_score: 

self._best_structure = ensemble.structure 

self._best_score = self._current_score 

else: 

ensemble.configuration.update_occupations( 

sites, list(reversed(species))) 

 

def _acceptance_condition(self, potential_diff: float) -> bool: 

""" 

Evaluates Metropolis acceptance criterion. 

 

Parameters 

---------- 

potential_diff 

change in the thermodynamic potential associated 

with the trial step 

""" 

if potential_diff < 0: 

return True 

160 ↛ 161line 160 didn't jump to line 161, because the condition on line 160 was never true elif abs(self.temperature) < 1e-6: # temperature is numerically zero 

return False 

else: 

p = np.exp(-potential_diff / self.temperature) 

return p > random.random() 

 

@property 

def temperature(self) -> float: 

""" Current temperature """ 

return self._temperature 

 

@property 

def T_start(self) -> float: 

""" Starting temperature """ 

return self._T_start 

 

@property 

def T_stop(self) -> float: 

""" Stop temperature """ 

return self._T_stop 

 

@property 

def n_steps(self) -> int: 

""" Number of steps to carry out """ 

return self._n_steps 

 

@property 

def total_trials(self) -> int: 

""" Number of steps carried out so far """ 

return self._total_trials 

 

@property 

def accepted_trials(self) -> int: 

""" Number of accepted trials carried out so far """ 

return self._accepted_trials 

 

@property 

def current_score(self) -> float: 

""" Current target vector score """ 

return self._current_score 

 

@property 

def best_score(self) -> float: 

""" Best target vector score found so far """ 

return self._best_score 

 

@property 

def best_structure(self) -> float: 

""" Structure most closely matching target vector so far """ 

return self._best_structure