gofee.py 13.3 KB
Newer Older
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
1
2
import numpy as np

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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
from surrogate.gpr import GPR
from population import population

from ase import Atoms
from ase.io import read, write, Trajectory
from ase.calculators.singlepoint import SinglePointCalculator

from bfgslinesearch_zlim import BFGSLineSearch_zlim
from ase.ga.relax_attaches import VariansBreak
from parallel_utils import split, parallel_function_eval
from mpi4py import MPI
world = MPI.COMM_WORLD

import traceback
import sys

def relax(structure, calc, Fmax=0.05, steps=200, niter_max=1, dmax_cov=None):
    a = structure.copy()
    # Set calculator
    a.set_calculator(calc)
    pos_init = a.get_positions()

    # loop a number of times to capture if minimization stops with high force
    # due to the VariansBreak calls
    niter = 0

    # Catch if linesearch fails
    try:
        while (a.get_forces()**2).sum(axis = 1).max()**0.5 > Fmax and niter < niter_max:
            dyn = BFGSLineSearch_zlim(a,
                                      pos_init=pos_init,
                                      dmax_cov=dmax_cov,
                                      logfile=None)
            vb = VariansBreak(a, dyn, min_stdev = 0.001, N = 15)
            dyn.attach(vb)
            dyn.run(fmax = Fmax, steps = steps)
            niter += 1
            #print('Nsteps rank {}:'.format(rank), dyn.get_number_of_steps(), flush=True)
    except Exception as err:
        print('Error in ML-relaxation:', err, flush=True)
        traceback.print_exc()
        traceback.print_exc(file=sys.stderr)

    return a

def relax_old(structure, calc, Fmax=0.05, steps=200, dmax_cov=None):
    a = structure.copy()
    # Set calculator 
    a.set_calculator(calc)
    pos_init = a.get_positions()

    # Catch if linesearch fails
    try:
        dyn = BFGSLineSearch_zlim(a,
                                  logfile=None,
                                  pos_init=pos_init,
                                  dmax_cov=dmax_cov)
        dyn.run(fmax = Fmax, steps = steps)
    except Exception as err:
        print('Error in surrogate-relaxation:', err, flush=True)
        traceback.print_exc()
        traceback.print_exc(file=sys.stderr)
    return a


class GOFEE():
    def __init__(self, structures=None,
                 calc=None,
                 gpr=None,
                 startgenerator=None,
                 candidate_generator=None,
                 trajectory=None,
                 kappa=2,
                 Neval=200,
                 dmax_cov=3.5,
                 Ncandidates=30,
                 population_size=5,
                 dualpoint=True,
                 min_certainty=0.7):
        """GOFEE global structure search method.
        
        structures: 
        """
        if structures is not None:
            if isinstance(structures, Atoms):
                self.structures = [structures]
            elif isinstance(structures, list):
                assert isinstance(structures[0], Atoms)
                self.structures = structures
            elif isinstance(structures, str):
                self.structures = read(structures, index=':')
            else:
                assert structures is None
                assert startgenerator is not None
        
        if calc is not None:
            self.calc = calc
        else:
            assert structures is not None
            calc = structures[0].get_calculator()
            assert calc is not None and not isinstance(calc, SinglePointCalculator)
            print('Using calculator from supplied structure(s)')
            self.calc = calc

        if gpr is not None:
            self.gpr = gpr
        else:
            self.gpr = GPR()

        if startgenerator is not None:
            self.startgenerator = startgenerator
        else:
            assert structures is not None
            self.startgenerator = None

        if candidate_generator is not None:
            self.candidate_generator = candidate_generator
        else:
            assert False

        # Initialize population
        self.population = population(population_size=population_size, gpr=self.gpr, similarity2equal=0.9999)

        # Define parallel communication
        self.comm = world.Dup()  # Important to avoid mpi-problems from call to ase.parallel in BFGS
        self.master = self.comm.rank == 0
            
        if isinstance(trajectory, str):
            self.trajectory = Trajectory(filename=trajectory, mode='a', master=self.master)
        elif isinstance(trajectory, Trajectory):
            self.trajectory = trajectory
        else:
            assert trajectory is None

        self.kappa = kappa
        self.Neval = Neval
        self.dmax_cov = dmax_cov
        self.Ncandidates = Ncandidates
        self.dualpoint = dualpoint
        self.min_certainty = min_certainty

    def initialize_search(self):
        self.get_initial_structures()

    def get_initial_structures(self):
        self.counter = 0
        # Initial structures
            
        if self.structures is None:
            assert False
        else:
            for a in self.structures:
                Ei = a.get_potential_energy()
                Fi = a.get_forces()
                self.gpr.memory.save_data([a])
                self.trajectory.write(a, energy=Ei, forces=Fi)
                #self.population.add_structure(a, Ei, Fi)
                self.population.add_structure(a)
                
    def run(self):
        self.initialize_search()

        while self.counter < self.Neval:
            self.print_master('counter:', self.counter)
            self.train_surrogate()
            self.update_population()
            relaxed_candidates = self.get_surrogate_relaxed_candidates()

            kappa = self.kappa
            anew = self.select_with_acquisition(relaxed_candidates, kappa)
            self.print_master('aq done')
            anew = self.evaluate(anew)
            self.print_master('sp done')
            if self.dualpoint:
                adp = self.get_dualpoint(anew)
                adp = self.evaluate(adp)
            self.print_master('dp done')
            self.gpr.memory.save_data([anew, adp])
            self.counter += 1 + int(self.dualpoint)

            # Add structure to population
            E = anew.get_potential_energy()
            if self.dualpoint:
                Edp = adp.get_potential_energy()
                if Edp <= E:
                    self.population.add_structure(adp)
                else:
                    self.population.add_structure(anew)
            else:
                self.population.add_structure(anew)
            
            if self.master:
                print('anew pred:', anew.info['key_value_pairs']['Epred'], anew.info['key_value_pairs']['Epred_std'])
                print('E_true:', anew.get_potential_energy(), adp.get_potential_energy())
                print('pop:', [a.get_potential_energy() for a in self.population.pop])
            
            """
            kappa = self.kappa
            for _ in range(5):
                try:
                    anew = self.select_with_acquisition(relaxed_candidates, kappa)
                    self.print_master('aq done')
                    anew = self.evaluate(anew)
                    self.print_master('sp done')
                    if self.dualpoint:
                        adp = self.get_dualpoint(anew)
                        adp = self.evaluate(adp)
                    self.print_master('dp done')
                except:
                    kappa /=2
                    if self.master:
                        traceback.print_exc(file=sys.stderr)
                    continue
                self.counter += 1 + int(self.dualpoint)
            """

    def get_dualpoint(self, a, lmax=0.10, Fmax_flat=5):
        """Returns dual-point structure, i.e. the original structure
        perturbed slightly along the forces.
        
        lmax: The atom with the largest force will be displaced by
        this distance
        
        Fmax_flat: maximum atomic displacement. is increased linearely
        with force until Fmax = Fmax_flat, after which it remains
        constant as lmax.
        """
        F = a.get_forces()
        a_dp = a.copy()

        # Calculate and set new positions
        Fmax = np.sqrt((F**2).sum(axis=1).max())
        pos_displace = lmax * F*min(1/Fmax_flat, 1/Fmax)
        pos_dp = a.positions + pos_displace
        a_dp.set_positions(pos_dp)
        return a_dp

    def print_master(self, *args):
        self.comm.barrier()
        if self.master:
            print(*args, flush=True)

    def generate_candidate(self):
        Ntrials = 5
        for i_trial in range(Ntrials):
            parents = self.population.get_structure_pair()
            a_mutated, _ = self.candidate_generator.get_new_individual(parents)
            # break trial loop if successful
            if a_mutated is not None:
                break
            # If no success in max number of trials
        if a_mutated is None:
            a_mutated = parents[0].copy()
        return a_mutated

    def get_surrogate_relaxed_candidates(self):
        Njobs = self.Ncandidates
        task_split = split(Njobs, self.comm.size)
        def func1():
            return [self.generate_candidate() for i in task_split[self.comm.rank]]
        candidates = parallel_function_eval(self.comm, func1)
        
        def func2():
            return [self.surrogate_relaxation(candidates[i], Fmax=0.1, steps=200, kappa=self.kappa)
                    for i in task_split[self.comm.rank]]
        relaxed_candidates = parallel_function_eval(self.comm, func2)
        relaxed_candidates = self.certainty_filter(relaxed_candidates)

        #if (self.NsearchIter % self.Nuse_pop_as_candidates) == 0:
        if self.counter % 6 == 0:
            relaxed_candidates = self.population.pop_MLrelaxed + relaxed_candidates
        
        if self.master:
            Epred = np.array([a.info['key_value_pairs']['Epred'] for a in relaxed_candidates])
            Epred_std = np.array([a.info['key_value_pairs']['Epred_std'] for a in relaxed_candidates])
            fitness = Epred - self.kappa*Epred_std
            print(np.c_[Epred, Epred_std, fitness])
        return relaxed_candidates
        
    def certainty_filter(self, structures):
        certainty = np.array([a.info['key_value_pairs']['Epred_std']
                              for a in structures]) / np.sqrt(self.gpr.K0)
        min_certainty = self.min_certainty
        for _ in range(5):
            filt = certainty < min_certainty
            if np.sum(filt.astype(int)) > 0:
                structures = [structures[i] for i in range(len(filt)) if filt[i]]
                break
            else:
                min_certainty = min_certainty + (1-min_certainty)/2
        return structures

    def update_population(self):
        Njobs = len(self.population.pop)
        task_split = split(Njobs, self.comm.size)
        func = lambda: [self.surrogate_relaxation(self.population.pop[i],
                                                  Fmax=0.001, steps=200, kappa=None)
                        for i in task_split[self.comm.rank]]
        self.population.pop_MLrelaxed = parallel_function_eval(self.comm, func)
        if self.master:
            print('ML-relaxed pop forces:\n',
                  [(a.get_forces()**2).sum(axis=1).max()**0.5 for a in self.population.pop_MLrelaxed])
            """
            print('pop forces before and after:\n', np.c_[np.array([(a.get_forces()**2).sum(axis=1).max()**0.5
                                                                  for a in self.population.pop]),
                                                        np.array([(a.get_forces()**2).sum(axis=1).max()**0.5
                                                                  for a in self.population.pop_MLrelaxed])])
            """

    def train_surrogate(self):
        # Train
        if self.counter < 100 or (self.counter % 20) == 0:
            self.gpr.optimize_hyperparameters(comm=self.comm)
        else:
            self.gpr.train()
        if self.master:
            print('kernel:', list(np.exp(self.gpr.kernel.theta)))
            print('lml:', self.gpr.lml)

    def surrogate_relaxation(self, a, Fmax=0.1, steps=200, kappa=None):
        calc = self.gpr.get_calculator(kappa)
        a_relaxed = relax(a, calc, dmax_cov=self.dmax_cov, Fmax=Fmax, steps=steps)

        # Evaluate uncertainty
        E, Estd = self.gpr.predict_energy(a_relaxed, eval_std=True)
        a_relaxed.info['key_value_pairs']['Epred'] = E
        a_relaxed.info['key_value_pairs']['Epred_std'] = Estd
        a_relaxed.info['key_value_pairs']['pre_relaxed'] = a.copy()

        return a_relaxed

    def select_with_acquisition(self, structures, kappa):
        Epred = np.array([a.info['key_value_pairs']['Epred']
                          for a in structures])
        Epred_std = np.array([a.info['key_value_pairs']['Epred_std']
                              for a in structures])
        acquisition = Epred - kappa*Epred_std
        index_select = np.argmin(acquisition)
        return structures[index_select]

    def evaluate(self, a):
        a.set_calculator(self.calc)
        E = a.get_potential_energy()
        F = a.get_forces()
        
        results = {'energy': E, 'forces': F}
        calc_sp = SinglePointCalculator(a, **results)
        a.set_calculator(calc_sp)

        self.write(a)

        return a

    def write(self, a):
        if self.trajectory is not None:
            self.trajectory.write(a)

    def save_state(self):
        pass

    def restart(self):
        pass