def interp_by_neb(initial, final, n_images, interp='idpp', calculator=None, constraint=None, fmax=0.5, steps=10, **kwargs): """Interpolate between the initial and final points by NEB method. :param initial: The initial image. :param final: The final image. :param int n_images: The number of image between the initial and final images. :param string interp: The interpolation method. :param Callable calculator: The callable to generate calculators for the images. It can be set to None if no real optimization is intended. :param constraint: The constraint for the images. :param fmax: The maximal force to stop the optimization. :param steps: The number of optimization steps allowed. :param kwargs: All other keyword arguments are forwarded to the initializer of the ASE NEB class. :return: The list of images between the points. """ # To circumvent the error from interpolation when we have no middle images. if n_images == 0: return [initial, final] images = [initial] for _ in range(n_images): image = initial.copy() images.append(image) if calculator is not None: image.set_calculator(calculator()) if constraint is not None: image.set_constraint(constraint) continue images.append(final) neb = NEB(images, **kwargs) neb.interpolate(method=interp) if calculator is not None: dyn = MDMin(neb) dyn.run(fmax=fmax, steps=steps) return neb.images
def test_unitcellfilter_hcp(asap3, testdir): cu = bulk('Cu', 'hcp', a=3.6 / 2.0**0.5) cu.cell[1, 0] -= 0.05 cu *= (6, 6, 3) cu.calc = asap3.EMT() print(cu.get_forces()) print(cu.get_stress()) f = UnitCellFilter(cu) opt = MDMin(f, dt=0.01) with Trajectory('Cu-hcp.traj', 'w', cu) as t: opt.attach(t) opt.run(0.2)
xc=xc, kpts=kpts, parallel={'band': 1}, txt='neb{}.txt'.format(j), communicator=ranks) image.set_calculator(calc_ase) images_ase.append(image) images_ase.append(final_ase) neb_ase = NEB(images_ase, parallel=True, climb=True) neb_ase.interpolate(method='idpp') qn_ase = MDMin(neb_ase, logfile='neb_ase.log', trajectory='neb_ase.traj') itime = time.default_timer() qn_ase.run(fmax=0.05) logging.warning('ase = %s', time.default_timer() - itime) # 2.B. NEB using CatLearn neb_catlearn = MLNEB(start=slab_initial, end=slab_final, ase_calc=calc, n_images=n_images + 2, interpolation='idpp', restart=False) itime = time.default_timer() neb_catlearn.run(fmax=0.05, trajectory='ML-NEB.traj')
# Make a mask of zeros and ones that select fixed atoms (the # two bottom layers): mask = initial.positions[:, 2] - min(initial.positions[:, 2]) < 1.5 * h constraint = FixAtoms(mask=mask) print(mask) for image in images: # Let all images use an EMT calculator: image.set_calculator(EMT()) image.set_constraint(constraint) # Relax the initial and final states: QuasiNewton(initial).run(fmax=0.05) QuasiNewton(final).run(fmax=0.05) # Create a Nudged Elastic Band: neb = NEB(images) # Make a starting guess for the minimum energy path (a straight line # from the initial to the final state): neb.interpolate() # Relax the NEB path: minimizer = MDMin(neb) minimizer.run(fmax=0.05) # Write the path to a trajectory: view(images) # 126 meV write('jump1.traj', images)
print 'Starting NEB run with %d images' % len(neb.images) if not os.path.exists('%s-initial.xyz' % basename): neb.write('%s-initial.xyz' % basename) if opt.eval: # actually evaluate end forces as well neb.get_forces(all=True) neb.write('%s-eval.xyz' % basename) elif not opt.dry_run: # Optimize: if opt.optimizer == 'FIRE': from ase.optimize.fire import FIRE optimizer = FIRE(neb) elif opt.optimizer == 'MDMin': from ase.optimize import MDMin optimizer = MDMin(neb) else: p.error('Unknown optimizer %s' % opt.optimizer) if opt.write_traj is not None: def write_traj(): global neb n = 0 while os.path.exists('%s-band-%d.xyz' % (basename, n)): n += 1 neb.write('%s-band-%d.xyz' % (basename, n)) optimizer.attach(write_traj, interval=opt.write_traj) optimizer.run(fmax=opt.fmax)
def run(self, fmax=0.05, steps=200, kernel='SQE', max_step=0.25, acq='min_energy', full_output=False, noise=0.005): """Executing run will start the optimization process. Parameters ---------- fmax : float Convergence criteria (in eV/Angstrom). steps : int Max. number of optimization steps. kernel: string Type of covariance function to be used. Implemented are: SQE (fixed hyperparamters), SQE_opt and ARD_SQE. max_step: float Early stopping criteria. Maximum uncertainty before stopping the optimization in the predicted landscape. acq : string The acquisition function that decides the next point to evaluate. Implemented are: 'lcb', 'ucb', 'min_energy'. full_output: boolean Whether to print on screen the full output (True) or not (False). noise: Regularization parameter of the GP. Returns ------- Optimized atom structure. """ self.fmax = fmax self.acq = acq success_hyper = False while not converged(self): # 1. Train Machine Learning model. train = np.copy(self.list_train) targets = np.copy(self.list_targets) gradients = np.copy(self.list_gradients) self.u_prior = np.max(targets) scaled_targets = targets - self.u_prior sigma_f = 1e-3 + np.std(scaled_targets)**2 if kernel == 'SQE_fixed': opt_hyper = False kdict = [{ 'type': 'gaussian', 'width': 0.4, 'dimension': 'single', 'bounds': ((0.4, 0.4), ), 'scaling': 1.0, 'scaling_bounds': ((1.0, 1.0), ) }, { 'type': 'noise_multi', 'hyperparameters': [noise * 0.4**2, noise], 'bounds': ( (noise * 0.4**2, noise * 0.4**2), (noise, noise), ) }] if kernel == 'SQE': opt_hyper = True kdict = [{ 'type': 'gaussian', 'width': 0.4, 'dimension': 'single', 'bounds': ((0.01, 1.0), ), 'scaling': sigma_f, 'scaling_bounds': ((sigma_f, sigma_f), ) }, { 'type': 'noise_multi', 'hyperparameters': [noise, noise * 0.4**2], 'bounds': ( (noise / 5., noise * 10.), (noise / 5. * 0.4**2, noise * 10.), ) }] if kernel == 'ARD_SQE': opt_hyper = True kdict = [{ 'type': 'gaussian', 'width': 0.4, 'dimension': 'features', 'bounds': ((0.01, 1.0), ) * len(self.index_mask), 'scaling': sigma_f, 'scaling_bounds': ((sigma_f, sigma_f), ) }, { 'type': 'noise_multi', 'hyperparameters': [noise / 2., noise / 10.], 'bounds': ( (noise / 5., noise), (noise / 10., noise / 4.), ) }] if len(self.list_targets) == 1: opt_hyper = False kdict = [{ 'type': 'gaussian', 'width': 0.20, 'dimension': 'single', 'bounds': ((0.20, 0.20), ), 'scaling': sigma_f, 'scaling_bounds': ((sigma_f, sigma_f), ) }, { 'type': 'noise_multi', 'hyperparameters': [noise * 0.4**2, noise], 'bounds': ( (noise * 0.4**2, noise * 0.4**2), (noise, noise), ) }] if success_hyper is not False: kdict = success_hyper if self.index_mask is not None: train = apply_mask(list_to_mask=train, mask_index=self.index_mask)[1] gradients = apply_mask(list_to_mask=gradients, mask_index=self.index_mask)[1] parprint('Training a GP process...') parprint('Number of training points:', len(scaled_targets)) train = train.tolist() gradients = gradients.tolist() self.gp = fit(train, scaled_targets, gradients, kdict) if opt_hyper is True: if len(self.list_targets) > 5: self.gp.optimize_hyperparameters() if self.gp.theta_opt.success is True: if full_output is True: parprint( 'Hyperparam. optimization was successful.') parprint('Updating kernel list...') success_hyper = self.gp.kernel_list if self.gp.theta_opt.success is not True: if full_output is True: parprint('Hyperparam. optimization unsuccessful.') if success_hyper is False: if full_output is True: parprint('Not enough data...') if success_hyper is not False: if full_output is True: parprint('Using the last optimized ' 'hyperparamters.') if full_output is True: parprint('Kernel list:', self.gp.kernel_list) # 2. Optimize Machine Learning model. self.list_interesting_points = [] self.list_interesting_energies = [] self.list_interesting_uncertainties = [] guess = self.ase_ini guess_pos = np.array(self.list_train[-1]) guess.positions = guess_pos.reshape(-1, 3) guess.set_calculator( ASECalc(gp=self.gp, index_constraints=self.index_mask, scaling_targets=self.u_prior)) # Optimization in the predicted landscape: ml_opt = MDMin(guess, trajectory=None, logfile=None, dt=0.020) if full_output is True: parprint('Starting optimization on the predicted landscape...') ml_converged = False n_steps_performed = 0 while ml_converged is False: ml_opt.run(fmax=fmax * 0.90, steps=1) pos_ml = np.array(guess.positions).flatten() self.list_interesting_points.append(pos_ml) pos_ml = apply_mask([pos_ml], mask_index=self.index_mask)[1] pred_ml = self.gp.predict(test_fp=pos_ml, uncertainty=True) energy_ml = pred_ml['prediction'][0][0] unc_ml = pred_ml['uncertainty_with_reg'][0] self.list_interesting_energies.append(energy_ml) self.list_interesting_uncertainties.append(unc_ml) n_steps_performed += 1 if n_steps_performed > 1000: if full_output is True: parprint('Not converged yet...') ml_converged = True if unc_ml >= max_step: if full_output is True: parprint('Maximum uncertainty reach. Early stop.') ml_converged = True if ml_opt.converged(): if full_output is True: parprint('ML optimized.') ml_converged = True # Acquisition functions: acq_pred = np.array(self.list_interesting_energies) acq_unc = np.array(self.list_interesting_uncertainties) if self.acq == 'ucb': acq_values = UCB(predictions=acq_pred, uncertainty=acq_unc, objective='min', kappa=-1.0) if self.acq == 'lcb': e_minus_unc = np.array(self.list_interesting_energies) - \ np.array(self.list_interesting_uncertainties) acq_values = -e_minus_unc if self.acq == 'min_energy': acq_values = -np.array(self.list_interesting_energies) max_score = np.argmax(acq_values) self.interesting_point = self.list_interesting_points[max_score] # 3. Evaluate and append interesting point. if full_output is True: parprint('Performing evaluation in the real landscape...') eval_atom = self.ase_ini pos_atom = self.interesting_point eval_atom.positions = np.array(pos_atom).reshape((-1, 3)) eval_atom.set_calculator(self.ase_calc) energy_atom = eval_atom.get_potential_energy( force_consistent=self.fc) forces_atom = -eval_atom.get_forces().reshape(-1) # 4. Convergence and output. self.list_train.append(pos_atom) self.list_targets.append(energy_atom) self.list_gradients.append(forces_atom) self.list_fmax = get_fmax(np.array([self.list_gradients[-1]])) self.max_abs_forces = np.max(np.abs(self.list_fmax)) self.list_max_abs_forces.append(self.max_abs_forces) self.iter += 1 print_info(self) # Save evaluated image. self.list_atoms += [eval_atom] TrajectoryWriter(atoms=self.ase_ini, filename=self.filename, mode='a').write() # Maximum number of iterations reached. if self.iter >= steps: parprint( 'Not converged. Maximum number of iterations reached.') break
images = [Atoms(initial)] images += [Atoms(initial.copy()) for i in range(n_images)] images += [Atoms(final)] neb = NEB(images, k=0.1) neb.interpolate() for img in images: img.set_calculator(model.calculator) ase.io.write(sys.stdout, img, 'extxyz') # perturb intermediate images for img in images[1:-1]: img.rattle(0.05) # optimizer = FIRE(neb) optimizer = MDMin(neb, dt=0.05) optimizer.run(fmax=fmax) neb_traj = open('model-' + model.name + '-vacancy-path.neb.xyz', 'w') ase.io.write(neb_traj, neb.images, format='extxyz') neb_traj.close() Es = [] for img in images: Es.append(img.get_potential_energy() - e_bulk_per_atom * len(img)) ase.io.write(sys.stdout, img, 'extxyz') # dictionary of computed properties - this is output of this test, to # be compared with other models properties = {'vacancy_path': Es}
def main(): """Adopted from ase/test/stress.py""" # setup a Fist Lennard-Jones Potential inp = """&FORCE_EVAL &MM &FORCEFIELD &SPLINE EMAX_ACCURACY 500.0 EMAX_SPLINE 1000.0 EPS_SPLINE 1.0E-9 &END &NONBONDED &LENNARD-JONES atoms Ar Ar EPSILON [eV] 1.0 SIGMA [angstrom] 1.0 RCUT [angstrom] 10.0 &END LENNARD-JONES &END NONBONDED &CHARGE ATOM Ar CHARGE 0.0 &END CHARGE &END FORCEFIELD &POISSON &EWALD EWALD_TYPE none &END EWALD &END POISSON &END MM &END FORCE_EVAL""" calc = CP2K(label="test_stress", inp=inp, force_eval_method="Fist") # Theoretical infinite-cutoff LJ FCC unit cell parameters vol0 = 4 * 0.91615977036 # theoretical minimum a0 = vol0**(1 / 3) a = bulk('Ar', 'fcc', a=a0) cell0 = a.get_cell() a.calc = calc a.set_cell(np.dot(a.cell, [[1.02, 0, 0.03], [0, 0.99, -0.02], [0.1, -0.01, 1.03]]), scale_atoms=True) a *= (1, 2, 3) cell0 *= np.array([1, 2, 3])[:, np.newaxis] a.rattle() # Verify analytical stress tensor against numerical value s_analytical = a.get_stress() s_numerical = a.calc.calculate_numerical_stress(a, 1e-5) s_p_err = 100 * (s_numerical - s_analytical) / s_numerical print("Analytical stress:\n", s_analytical) print("Numerical stress:\n", s_numerical) print("Percent error in stress:\n", s_p_err) assert np.all(abs(s_p_err) < 1e-5) # Minimize unit cell opt = MDMin(UnitCellFilter(a), dt=0.01) opt.run(fmax=1e-3) # Verify minimized unit cell using Niggli tensors g_minimized = np.dot(a.cell, a.cell.T) g_theory = np.dot(cell0, cell0.T) g_p_err = 100 * (g_minimized - g_theory) / g_theory print("Minimized Niggli tensor:\n", g_minimized) print("Theoretical Niggli tensor:\n", g_theory) print("Percent error in Niggli tensor:\n", g_p_err) assert np.all(abs(g_p_err) < 1) print('passed test "stress"')
em = a.calc.get_potential_energy(a, force_consistent=True) s = (ep - em) / 2 / deps / vol print(v, s, abs(s - sigma_vv[v, v])) assert abs(s - sigma_vv[v, v]) < 1e-7 for v1 in range(3): v2 = (v1 + 1) % 3 x = np.eye(3) x[v1, v2] = deps x[v2, v1] = deps a.set_cell(np.dot(cell, x), scale_atoms=True) ep = a.calc.get_potential_energy(a, force_consistent=True) x[v1, v2] = -deps x[v2, v1] = -deps a.set_cell(np.dot(cell, x), scale_atoms=True) em = a.calc.get_potential_energy(a, force_consistent=True) s = (ep - em) / deps / 4 / vol print(v1, v2, s, abs(s - sigma_vv[v1, v2])) assert abs(s - sigma_vv[v1, v2]) < 1e-7 opt = MDMin(UnitCellFilter(a), dt=0.01) opt.run(fmax=0.5) print(a.cell) for i in range(3): for j in range(3): x = np.dot(a.cell[i], a.cell[j]) y = (i + 1) * (j + 1) * a0**2 / 2 if i != j: y /= 2 print(i, j, x, (x - y) / x) assert abs((x - y) / x) < 0.01
scale_atoms=True) a *= (1, 2, 3) cell0 *= np.array([1, 2, 3])[:, np.newaxis] a.rattle() # Verify analytical stress tensor against numerical value s_analytical = a.get_stress() s_numerical = a.calc.calculate_numerical_stress(a, 1e-5) s_p_err = 100 * (s_numerical - s_analytical) / s_numerical print("Analytical stress:\n", s_analytical) print("Numerical stress:\n", s_numerical) print("Percent error in stress:\n", s_p_err) assert np.all(abs(s_p_err) < 1e-5) # Minimize unit cell opt = MDMin(UnitCellFilter(a), dt=0.01) opt.run(fmax=1e-3) # Verify minimized unit cell using Niggli tensors g_minimized = np.dot(a.cell, a.cell.T) g_theory = np.dot(cell0, cell0.T) g_p_err = 100 * (g_minimized - g_theory) / g_theory print("Minimized Niggli tensor:\n", g_minimized) print("Theoretical Niggli tensor:\n", g_theory) print("Percent error in Niggli tensor:\n", g_p_err) assert np.all(abs(g_p_err) < 1)
def main(): """Adopted from ase/test/stress.py""" if "ASE_CP2K_COMMAND" not in os.environ: raise NotAvailable('$ASE_CP2K_COMMAND not defined') # setup a Fist Lennard-Jones Potential inp = """&FORCE_EVAL &MM &FORCEFIELD &SPLINE EMAX_ACCURACY 500.0 EMAX_SPLINE 1000.0 EPS_SPLINE 1.0E-9 &END &NONBONDED &LENNARD-JONES atoms Ar Ar EPSILON [eV] 1.0 SIGMA [angstrom] 1.0 RCUT [angstrom] 10.0 &END LENNARD-JONES &END NONBONDED &CHARGE ATOM Ar CHARGE 0.0 &END CHARGE &END FORCEFIELD &POISSON &EWALD EWALD_TYPE none &END EWALD &END POISSON &END MM &END FORCE_EVAL""" calc = CP2K(label="test_stress", inp=inp, force_eval_method="Fist") vol0 = 4 * 0.91615977036 # theoretical minimum a0 = vol0**(1 / 3) a = bulk('Ar', 'fcc', a=a0) a.calc = calc a.set_cell(np.dot(a.cell, [[1.02, 0, 0.03], [0, 0.99, -0.02], [0.1, -0.01, 1.03]]), scale_atoms=True) a *= (1, 2, 3) a.rattle() sigma_vv = a.get_stress(voigt=False) # print(sigma_vv) # print(a.get_potential_energy() / len(a)) vol = a.get_volume() # compare stress tensor with numeric derivative deps = 1e-5 cell = a.cell.copy() for v in range(3): x = np.eye(3) x[v, v] += deps a.set_cell(np.dot(cell, x), scale_atoms=True) ep = a.calc.get_potential_energy(a, force_consistent=True) x[v, v] -= 2 * deps a.set_cell(np.dot(cell, x), scale_atoms=True) em = a.calc.get_potential_energy(a, force_consistent=True) s = (ep - em) / 2 / deps / vol # print(v, s, abs(s - sigma_vv[v, v])) assert abs(s - sigma_vv[v, v]) < 1e-7 for v1 in range(3): v2 = (v1 + 1) % 3 x = np.eye(3) x[v1, v2] = deps x[v2, v1] = deps a.set_cell(np.dot(cell, x), scale_atoms=True) ep = a.calc.get_potential_energy(a, force_consistent=True) x[v1, v2] = -deps x[v2, v1] = -deps a.set_cell(np.dot(cell, x), scale_atoms=True) em = a.calc.get_potential_energy(a, force_consistent=True) s = (ep - em) / deps / 4 / vol # print(v1, v2, s, abs(s - sigma_vv[v1, v2])) assert abs(s - sigma_vv[v1, v2]) < 1e-7 # run a cell optimization, see if it finds back original crystal structure opt = MDMin(UnitCellFilter(a), dt=0.01, logfile=None) opt.run(fmax=0.5) # print(a.cell) for i in range(3): for j in range(3): x = np.dot(a.cell[i], a.cell[j]) y = (i + 1) * (j + 1) * a0**2 / 2 if i != j: y /= 2 # print(i, j, x, (x - y) / x) assert abs((x - y) / x) < 0.01 print('passed test "stress"')
def main(): """Adopted from ase/test/stress.py""" if "ASE_CP2K_COMMAND" not in os.environ: raise NotAvailable('$ASE_CP2K_COMMAND not defined') # setup a Fist Lennard-Jones Potential inp = """&FORCE_EVAL &MM &FORCEFIELD &SPLINE EMAX_ACCURACY 500.0 EMAX_SPLINE 1000.0 EPS_SPLINE 1.0E-9 &END &NONBONDED &LENNARD-JONES atoms Ar Ar EPSILON [eV] 1.0 SIGMA [angstrom] 1.0 RCUT [angstrom] 10.0 &END LENNARD-JONES &END NONBONDED &CHARGE ATOM Ar CHARGE 0.0 &END CHARGE &END FORCEFIELD &POISSON &EWALD EWALD_TYPE none &END EWALD &END POISSON &END MM &END FORCE_EVAL""" calc = CP2K(label="test_stress", inp=inp, force_eval_method="Fist") # Theoretical infinite-cutoff LJ FCC unit cell parameters vol0 = 4 * 0.91615977036 # theoretical minimum a0 = vol0 ** (1 / 3) a = bulk('Ar', 'fcc', a=a0) cell0 = a.get_cell() a.calc = calc a.set_cell(np.dot(a.cell, [[1.02, 0, 0.03], [0, 0.99, -0.02], [0.1, -0.01, 1.03]]), scale_atoms=True) a *= (1, 2, 3) cell0 *= np.array([1, 2, 3])[:, np.newaxis] a.rattle() # Verify analytical stress tensor against numerical value s_analytical = a.get_stress() s_numerical = a.calc.calculate_numerical_stress(a, 1e-5) s_p_err = 100 * (s_numerical - s_analytical) / s_numerical print("Analytical stress:\n", s_analytical) print("Numerical stress:\n", s_numerical) print("Percent error in stress:\n", s_p_err) assert np.all(abs(s_p_err) < 1e-5) # Minimize unit cell opt = MDMin(UnitCellFilter(a), dt=0.01) opt.run(fmax=1e-3) # Verify minimized unit cell using Niggli tensors g_minimized = np.dot(a.cell, a.cell.T) g_theory = np.dot(cell0, cell0.T) g_p_err = 100 * (g_minimized - g_theory) / g_theory print("Minimized Niggli tensor:\n", g_minimized) print("Theoretical Niggli tensor:\n", g_theory) print("Percent error in Niggli tensor:\n", g_p_err) assert np.all(abs(g_p_err) < 1) print('passed test "stress"')
# Make a mask of zeros and ones that select fixed atoms (the # two bottom layers): mask = initial.positions[:, 2] - min(initial.positions[:, 2]) < 1.5 * h constraint = FixAtoms(mask=mask) print(mask) for image in images: # Let all images use an EMT calculator: image.set_calculator(EMT()) image.set_constraint(constraint) # Relax the initial and final states: QuasiNewton(initial).run(fmax=0.05) QuasiNewton(final).run(fmax=0.05) # Create a Nudged Elastic Band: neb = NEB(images) # Make a starting guess for the minimum energy path (a straight line # from the initial to the final state): neb.interpolate() # Relax the NEB path: minimizer = MDMin(neb) minimizer.run(fmax=0.05) # Write the path to a trajectory: view(images) # 564 meV write('jump2.traj', images)
from ase.structure import molecule from ase.structure import nanotube from ase.optimize import BFGS, MDMin from asap3 import BrennerPotential from asap3.testtools import ReportTest import numpy as np atoms = nanotube(5, 5, length=10) atoms.set_calculator(BrennerPotential()) uc = atoms.get_cell() l0 = uc[2,2] e = -1e100 for eps in np.linspace(0, 0.5, 201): uc[2,2] = l0 * (1 + eps) atoms.set_cell(uc, scale_atoms=True) dyn = MDMin(atoms, logfile=None, dt=0.05) dyn.run(fmax=0.01, steps=100) epot = atoms.get_potential_energy() if epot > e: e = epot print "%.3f %f" % (eps, epot) print "Maximal energy:", e ReportTest("Maximal energy", e, -969.0, 5.0) if abs(e - -620.98) < 1.0: print "Bug 42 is back!"
xc = 'BEEF-vdW' ################################################# vacuum = 8 # Angstrom a = 2.53959*2 # Angstrom input_structure = "str.cif" fmaxx = 0.03 maxstep = 0.05 atoms = read(input_structure) atoms.set_calculator(GPAW(xc=xc, kpts = kpoints, gpts=gpoints, txt='bfgs.txt')) cellpar = atoms.cell.cellpar() scaled_pos = atoms.get_scaled_positions() # Constraints- fix atoms in the first first unit cell from origin and the last two unit cells from origin indices = [] for i in range(len(atoms)): if atoms[i].symbol == 'C': indices.append(i) elif scaled_pos[i][0] <= (3*a/2 + vacuum)/cellpar[0]: indices.append(i) elif scaled_pos[i][0] >= 1 - (vacuum + 5*a/2)/cellpar[0]: indices.append(i) atoms.set_constraint(FixAtoms(indices)) dyn=MDMin(atoms=atoms, trajectory='traj.traj', logfile = 'qn.log') dyn.run(fmax=fmaxx)
def main(): """Adopted from ase/test/stress.py""" if "ASE_CP2K_COMMAND" not in os.environ: raise NotAvailable('$ASE_CP2K_COMMAND not defined') # setup a Fist Lennard-Jones Potential inp = """&FORCE_EVAL &MM &FORCEFIELD &SPLINE EMAX_ACCURACY 500.0 EMAX_SPLINE 1000.0 EPS_SPLINE 1.0E-9 &END &NONBONDED &LENNARD-JONES atoms Ar Ar EPSILON [eV] 1.0 SIGMA [angstrom] 1.0 RCUT [angstrom] 10.0 &END LENNARD-JONES &END NONBONDED &CHARGE ATOM Ar CHARGE 0.0 &END CHARGE &END FORCEFIELD &POISSON &EWALD EWALD_TYPE none &END EWALD &END POISSON &END MM &END FORCE_EVAL""" calc = CP2K(label="test_stress", inp=inp, force_eval_method="Fist") vol0 = 4 * 0.91615977036 # theoretical minimum a0 = vol0 ** (1 / 3) a = bulk('Ar', 'fcc', a=a0) a.calc = calc a.set_cell(np.dot(a.cell, [[1.02, 0, 0.03], [0, 0.99, -0.02], [0.1, -0.01, 1.03]]), scale_atoms=True) a *= (1, 2, 3) a.rattle() sigma_vv = a.get_stress(voigt=False) # print(sigma_vv) # print(a.get_potential_energy() / len(a)) vol = a.get_volume() # compare stress tensor with numeric derivative deps = 1e-5 cell = a.cell.copy() for v in range(3): x = np.eye(3) x[v, v] += deps a.set_cell(np.dot(cell, x), scale_atoms=True) ep = a.calc.get_potential_energy(a, force_consistent=True) x[v, v] -= 2 * deps a.set_cell(np.dot(cell, x), scale_atoms=True) em = a.calc.get_potential_energy(a, force_consistent=True) s = (ep - em) / 2 / deps / vol # print(v, s, abs(s - sigma_vv[v, v])) assert abs(s - sigma_vv[v, v]) < 1e-7 for v1 in range(3): v2 = (v1 + 1) % 3 x = np.eye(3) x[v1, v2] = deps x[v2, v1] = deps a.set_cell(np.dot(cell, x), scale_atoms=True) ep = a.calc.get_potential_energy(a, force_consistent=True) x[v1, v2] = -deps x[v2, v1] = -deps a.set_cell(np.dot(cell, x), scale_atoms=True) em = a.calc.get_potential_energy(a, force_consistent=True) s = (ep - em) / deps / 4 / vol # print(v1, v2, s, abs(s - sigma_vv[v1, v2])) assert abs(s - sigma_vv[v1, v2]) < 1e-7 # run a cell optimization, see if it finds back original crystal structure opt = MDMin(UnitCellFilter(a), dt=0.01, logfile=None) opt.run(fmax=0.1) # print(a.cell) for i in range(3): for j in range(3): x = np.dot(a.cell[i], a.cell[j]) y = (i + 1) * (j + 1) * a0 ** 2 / 2 if i != j: y /= 2 # print(i, j, x, (x - y) / x) assert abs((x - y) / x) < 0.01 print('passed test "stress"')
initial_ase = read('initial_opt.traj') final_ase = read('final_opt.traj') constraint = FixAtoms(mask=[atom.tag > 1 for atom in initial_ase]) images_ase = [initial_ase] for i in range(1, n_images - 1): image = initial_ase.copy() image.set_calculator(copy.deepcopy(ase_calculator)) images_ase.append(image) images_ase.append(final_ase) neb_ase = NEB(images_ase, climb=True, method='aseneb') neb_ase.interpolate(method='idpp') qn_ase = MDMin(neb_ase, trajectory='neb_ase.traj') qn_ase.run(fmax=0.05) # 2.B. NEB using CatLearn #################################################### neb_catlearn = MLNEB(start='initial_opt.traj', end='final_opt.traj', ase_calc=copy.deepcopy(ase_calculator), n_images=n_images, interpolation='idpp', restart=False) neb_catlearn.run(fmax=0.05, trajectory='ML-NEB.traj') # 3. Summary of the results #################################################
print_version(1) size = 5 atoms = FaceCenteredCubic(size=(size,size,size), symbol="Cu", pbc=True) defsize = atoms.get_volume() atoms.set_cell(atoms.get_cell() * 1.1, scale_atoms=True) atoms.set_calculator(EMT()) def printvol(a): print "Volume:", a.get_volume(), " energy:",\ atoms.get_potential_energy() + atoms.get_kinetic_energy(),\ " stress:", atoms.get_stress()[:3] f = StrainFilter(atoms, [1, 1, 1, 0, 0, 0]) opt = MDMin(f, logfile="/dev/null", dt=0.01/(atoms.get_cell()[0,0])) printvol(atoms) opt.attach(printvol, 10, atoms) opt.run(0.01) printvol(atoms) print "Original vol:", defsize print stress = atoms.get_stress() for i in range(6): ReportTest("Stress component %d (T=0)" % (i,), stress[0], 0.0, 1e-5) atoms = FaceCenteredCubic(size=(size,size,size), symbol="Cu", pbc=True) atoms.set_calculator(EMT()) dyn = Langevin(atoms, 10*units.fs, 500*units.kB, 0.02) dyn.attach(printvol, 100, atoms) dyn.run(500)
pstress = patom.get_cell() * 0.0 fixstrain = np.ones((3, 3)) ref_atom = refatom.copy() ref_coord = refatom.get_cell() pstress[2][2] = 1.34523705e+01 # PK1 can be replaced by PK2 or Cauchy pbox = stressbox(patom, express=pstress, fixstrain=fixstrain, ref_atom=ref_atom, stress_type='PK1') dyn = MDMin(pbox) #dyn=FIRE(pbox) #dyn=BFGS(pbox) f_max = 1E-6 dyn.run(fmax=f_max, steps=10000) print('pk1 stress=', pbox.get_stress_pk1() / units.GPa) print('pk2 stress=', pbox.get_stress_pk2() / units.GPa) print('cauchy stress=', pbox.get_stress(voigt=False) / units.GPa) print('deformation gradient=', pbox.get_defgrad()) write("output.lmpdata", patom, format='lammps-data', atom_style='atomic')
temp.translate([x * a, y * a, z * a]) for i in range(4): print((x, y, z, i)) initial.append(temp[i]) tempPos = initial[0].position del initial[0] final = initial.copy() final[1].position = tempPos #QuasiNewton(initial).run(fmax=0.05) #QuasiNewton(final).run(fmax=0.05) images = [initial] images += [initial.copy() for i in range(3)] images += [final] neb = NEB(images) neb.interpolate() for image in images[1:4]: image.set_calculator(calc) print("its go time") optimizer = MDMin(neb, trajectory='neb.traj') optimizer.run(fmax=0.04) time = datetime.now().time() print(time)