def test(): # Generate atomic system to create test data. atoms = fcc110('Cu', (2, 2, 2), vacuum=7.) adsorbate = Atoms([Atom('H', atoms[7].position + (0., 0., 2.)), Atom('H', atoms[7].position + (0., 0., 5.))]) atoms.extend(adsorbate) atoms.set_constraint(FixAtoms(indices=[0, 2])) calc = EMT() # cheap calculator atoms.set_calculator(calc) # Run some molecular dynamics to generate data. trajectory = io.Trajectory('data.traj', 'w', atoms=atoms) MaxwellBoltzmannDistribution(atoms, temp=300. * units.kB) dynamics = VelocityVerlet(atoms, dt=1. * units.fs) dynamics.attach(trajectory) for step in range(50): dynamics.run(5) trajectory.close() # Train the calculator. train_images, test_images = randomize_images('data.traj') calc = Amp(descriptor=Behler(), regression=NeuralNetwork()) calc.train(train_images, energy_goal=0.001, force_goal=None) # Plot and test the predictions. import matplotlib matplotlib.use('Agg') from matplotlib import pyplot fig, ax = pyplot.subplots() for image in train_images: actual_energy = image.get_potential_energy() predicted_energy = calc.get_potential_energy(image) ax.plot(actual_energy, predicted_energy, 'b.') for image in test_images: actual_energy = image.get_potential_energy() predicted_energy = calc.get_potential_energy(image) ax.plot(actual_energy, predicted_energy, 'r.') ax.set_xlabel('Actual energy, eV') ax.set_ylabel('Amp energy, eV') fig.savefig('parityplot.png')
1. Optimization of the initial and final end-points of the reaction path. 2.A. NEB optimization using CI-NEB as implemented in ASE. 2.B. NEB optimization using our machine-learning surrogate model. 3. Comparison between the ASE NEB and our ML-NEB algorithm. """ # 1. Structural relaxation. # 1.1. Structures: # 2x2-Al(001) surface with 3 layers and an # Au atom adsorbed in a hollow site: slab = fcc100('Al', size=(2, 2, 3)) add_adsorbate(slab, 'Au', 1.7, 'hollow') slab.center(axis=2, vacuum=4.0) slab.set_calculator(EMT()) # Fix second and third layers: mask = [atom.tag > 1 for atom in slab] slab.set_constraint(FixAtoms(mask=mask)) # 1.2. Optimize initial and final end-points. # Initial end-point: qn = BFGS(slab, trajectory='initial.traj') qn.run(fmax=0.01) # Final end-point: slab[-1].x += slab.get_cell()[0, 0] / 2 qn = BFGS(slab, trajectory='final.traj') qn.run(fmax=0.01)
# Construct a list of images: images = [initial] for i in range(5): images.append(initial.copy()) images.append(final) # 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 = BFGS(neb)
from ase.all import * from ase.calculators.emt import EMT from ase.optimize import BFGS from winak.globaloptimization.betterhopping import BetterHopping import numpy as np adsorbate = '../testsystems/NH3_on_Ag100.traj' molecule = read(adsorbate) #NOTE: Define your own calculator here! molecule.set_calculator(EMT()) f = FixAtoms(mask=[atom.symbol == 'Ag' for atom in molecule]) bh = BetterHopping(atoms=molecule, temperature=100 * kB, dr=1.0, optimizer=BFGS, fmax=2, logfile='tt.log', maxmoves=50, movemode=1, numdelocmodes=3, adsorbmask=(8, 12), cell_scale=(0.5, 0.5, 0.1)) bh.run(20)
import os from ase import Atoms from ase.calculators.emt import EMT from ase.optimize import QuasiNewton from ase.vibrations import Vibrations from ase.thermochemistry import IdealGasThermo n2 = Atoms('N2', positions=[(0, 0, 0), (0, 0, 1.1)], calculator=EMT()) QuasiNewton(n2).run(fmax=0.01) vib = Vibrations(n2) vib.run() freqs = vib.get_frequencies() print(freqs) vib.summary() print(vib.get_mode(-1)) vib.write_mode(n=None, nimages=20) vib_energies = vib.get_energies() for image in vib.iterimages(): assert len(image) == 2 thermo = IdealGasThermo(vib_energies=vib_energies, geometry='linear', atoms=n2, symmetrynumber=2, spin=0) thermo.get_gibbs_energy(temperature=298.15, pressure=2 * 101325.) assert vib.clean(empty_files=True) == 0 assert vib.clean() == 13 assert len(list(vib.iterimages())) == 13
def get_calculator_emt(): return EMT()
from ase import units from ase.calculators.emt import EMT size = 5 import ase.io from ase.io.trajectory import Trajectory atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], symbol='Pd', size=(size, size, size), pbc=True) traj = ase.io.Trajectory('traj_1.traj','w') atoms.set_calculator(EMT()) MaxwellBoltzmannDistribution(atoms, 300 * units.kB) traj.write(atoms) dyn = VelocityVerlet(atoms, dt=1 * units.fs) for step in range(10): pot = atoms.get_potential_energy() kin = atoms.get_kinetic_energy() with open('traj_1.txt','w') as f: f.write("{}: Total Energy={}, POT={}, KIN={}\n".format(step, pot+kin, pot, kin)) dyn.run(5) ase.io.write('traj_1.xyz',ase.io.read('traj_1.traj'), append=True) traj.write(atoms)
from ase.neb import SingleCalculatorNEB from ase.calculators.emt import EMT Optimizer = BFGS # Distance between Cu atoms on a (111) surface: a = 3.6 d = a / sqrt(2) fcc111 = Atoms(symbols='Cu', cell=[(d, 0, 0), (d / 2, d * sqrt(3) / 2, 0), (d / 2, d * sqrt(3) / 6, -a / sqrt(3))], pbc=True) initial = fcc111 * (2, 2, 4) initial.set_cell([2 * d, d * sqrt(3), 1]) initial.set_pbc((1, 1, 0)) initial.set_calculator(EMT()) Z = initial.get_positions()[:, 2] indices = [i for i, z in enumerate(Z) if z < Z.mean()] constraint = FixAtoms(indices=indices) initial.set_constraint(constraint) print('Relax initial image') dyn = Optimizer(initial) dyn.run(fmax=0.05) Z = initial.get_positions()[:, 2] print(Z[0] - Z[1]) print(Z[1] - Z[2]) print(Z[2] - Z[3]) b = 1.2 h = 1.5
def get_calculator(): calc = EMT() return calc
def test_COCu111_2(): Optimizer = BFGS # Distance between Cu atoms on a (111) surface: a = 3.6 d = a / sqrt(2) fcc111 = Atoms(symbols='Cu', cell=[(d, 0, 0), (d / 2, d * sqrt(3) / 2, 0), (d / 2, d * sqrt(3) / 6, -a / sqrt(3))], pbc=True) initial = fcc111 * (2, 2, 4) initial.set_cell([2 * d, d * sqrt(3), 1]) initial.set_pbc((1, 1, 0)) initial.calc = EMT() Z = initial.get_positions()[:, 2] indices = [i for i, z in enumerate(Z) if z < Z.mean()] constraint = FixAtoms(indices=indices) initial.set_constraint(constraint) print('Relax initial image') dyn = Optimizer(initial) dyn.run(fmax=0.05) Z = initial.get_positions()[:, 2] print(Z[0] - Z[1]) print(Z[1] - Z[2]) print(Z[2] - Z[3]) b = 1.2 h = 1.5 initial += Atom('C', (d / 2, -b / 2, h)) initial += Atom('O', (d / 2, +b / 2, h)) dyn = Optimizer(initial) dyn.run(fmax=0.05) # view(initial) print('Relax final image') final = initial.copy() final.calc = EMT() final.set_constraint(constraint) final[-2].position = final[-1].position final[-1].x = d final[-1].y = d / sqrt(3) dyn = Optimizer(final) dyn.run(fmax=0.1) # view(final) print('Create neb with 2 intermediate steps') neb = SingleCalculatorNEB([initial, final]) neb.refine(2) assert neb.n() == 4 print('Optimize neb using a single calculator') neb.set_calculators(EMT()) # print('0001', id(neb.images[0]), id(neb.images[0].calc.atoms)) dyn = Optimizer(neb, maxstep=0.04, trajectory='mep_2coarse.traj') dyn.run(fmax=0.1) # dyn.run(fmax=39.1) print('Optimize neb using a many calculators') neb = SingleCalculatorNEB([initial, final]) neb.refine(2) neb.set_calculators([EMT() for i in range(neb.n())]) dyn = Optimizer(neb, maxstep=0.04, trajectory='mep_2coarse.traj') dyn.run(fmax=0.1) # dyn.run(fmax=39.1) # read from the trajectory neb = SingleCalculatorNEB('mep_2coarse.traj', index='-4:') # refine in the important region neb.refine(2, 1, 3) neb.set_calculators(EMT()) print('Optimize refined neb using a single calculator') dyn = Optimizer(neb, maxstep=0.04, trajectory='mep_2fine.traj') dyn.run(fmax=0.1) assert len(neb.images) == 8
def get_calculator(): return EMT()
# creates: precon.png from ase.build import bulk from ase.calculators.emt import EMT from ase.optimize.precon import Exp, PreconLBFGS from ase.calculators.loggingcalc import LoggingCalculator import matplotlib.pyplot as plt a0 = bulk('Cu', cubic=True) a0 *= [3, 3, 3] del a0[0] a0.rattle(0.1) nsteps = [] energies = [] log_calc = LoggingCalculator(EMT()) for precon, label in [(None, 'None'), (Exp(A=3, mu=1.0), 'Exp(A=3)')]: log_calc.label = label atoms = a0.copy() atoms.calc = log_calc opt = PreconLBFGS(atoms, precon=precon, use_armijo=True) opt.run(fmax=1e-3) log_calc.plot(markers=['r-', 'b-'], energy=False, lw=2) plt.savefig('precon.png')
pair_cor_cum_diff=0.015, pair_cor_max=0.7, dE=0.02, mic=False) pairing = CutAndSplicePairing(slab, n_to_optimize, blmin) mutations = OperationSelector([1., 1., 1.], [ MirrorMutation(blmin, n_to_optimize), RattleMutation(blmin, n_to_optimize), PermutationMutation(n_to_optimize) ]) # Relax all unrelaxed structures (e.g. the starting population) while da.get_number_of_unrelaxed_candidates() > 0: a = da.get_an_unrelaxed_candidate() a.set_calculator(EMT()) print('Relaxing starting candidate {0}'.format(a.info['confid'])) dyn = BFGS(a, trajectory=None, logfile=None) dyn.run(fmax=0.05, steps=100) a.set_raw_score(-a.get_potential_energy()) da.add_relaxed_step(a) # create the population population = Population(data_connection=da, population_size=population_size, comparator=comp) # test n_to_test new candidates for i in xrange(n_to_test): print('Now starting configuration number {0}'.format(i)) a1, a2 = population.get_two_candidates()
def ref_atoms(): atoms = bulk('Al', a=3.994) * 2 atoms.calc = EMT() i, j, r = neighbor_list('ijd', atoms, cutoff=3.0) bonds = [Bond(I, J, k=1.0, b0=R) for (I, J, R) in zip(i, j, r)] return atoms, bonds
from ase.eos import EquationOfState from ase.build import bulk from ase.build import fcc100, add_adsorbate, molecule from ase.constraints import FixAtoms from ase.optimize import BFGS from ase.calculators.emt import EMT from al_mlp.preset_learners import EnsembleLearner from al_mlp.base_calcs.morse import MultiMorse from al_mlp.atomistic_methods import Relaxation from amptorch.trainer import AtomsTrainer torch.set_num_threads(1) parent_calc = EMT() # Make a simple C on Cu slab. # Sets calculator to parent_calc. energies = [] volumes = [] LC = [3.5, 3.55, 3.6, 3.65, 3.7, 3.75] for a in LC: cu_bulk = bulk("Cu", "fcc", a=a) calc = EMT() cu_bulk.set_calculator(calc) e = cu_bulk.get_potential_energy()
def test_calcs(): """Gaussian/Neural non-periodic standard. Checks that the answer matches that expected from previous Mathematica calculations. """ #: Making the list of non-periodic images images = [ Atoms( symbols="PdOPd2", pbc=np.array([False, False, False], dtype=bool), calculator=EMT(), cell=np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), positions=np.array([[0.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0], [1.0, 0.0, 0.0]]), ), Atoms( symbols="PdOPd2", pbc=np.array([False, False, False], dtype=bool), calculator=EMT(), cell=np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), positions=np.array([[0.0, 1.0, 0.0], [1.0, 2.0, 1.0], [-1.0, 1.0, 2.0], [1.0, 3.0, 2.0]]), ), Atoms( symbols="PdO", pbc=np.array([False, False, False], dtype=bool), calculator=EMT(), cell=np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), positions=np.array([[2.0, 1.0, -1.0], [1.0, 2.0, 1.0]]), ), Atoms( symbols="Pd2O", pbc=np.array([False, False, False], dtype=bool), calculator=EMT(), cell=np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), positions=np.array([[-2.0, -1.0, -1.0], [1.0, 2.0, 1.0], [3.0, 4.0, 4.0]]), ), Atoms( symbols="Cu", pbc=np.array([False, False, False], dtype=bool), calculator=EMT(), cell=np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), positions=np.array([[0.0, 0.0, 0.0]]), ), ] # Parameters hiddenlayers = {"O": (2, ), "Pd": (2, ), "Cu": (2, )} Gs = {} Gs["G2_etas"] = [0.2] Gs["G2_rs_s"] = [0] Gs["G4_etas"] = [0.4] Gs["G4_zetas"] = [1] Gs["G4_gammas"] = [1] Gs["cutoff"] = 6.5 elements = ["O", "Pd", "Cu"] G = make_symmetry_functions(elements=elements, type="G2", etas=Gs["G2_etas"]) G += make_symmetry_functions( elements=elements, type="G4", etas=Gs["G4_etas"], zetas=Gs["G4_zetas"], gammas=Gs["G4_gammas"], ) amp_images = amp_hash(images) descriptor = Gaussian(Gs=G, cutoff=Gs["cutoff"]) descriptor.calculate_fingerprints(amp_images, calculate_derivatives=True) fingerprints_range = calculate_fingerprints_range(descriptor, amp_images) np.random.seed(1) O_weights_1 = np.random.rand(10, 2) O_weights_2 = np.random.rand(1, 3).reshape(-1, 1) np.random.seed(2) Pd_weights_1 = np.random.rand(10, 2) Pd_weights_2 = np.random.rand(1, 3).reshape(-1, 1) np.random.seed(3) Cu_weights_1 = np.random.rand(10, 2) Cu_weights_2 = np.random.rand(1, 3).reshape(-1, 1) weights = OrderedDict([ ("O", OrderedDict([(1, O_weights_1), (2, O_weights_2)])), ("Pd", OrderedDict([(1, Pd_weights_1), (2, Pd_weights_2)])), ("Cu", OrderedDict([(1, Cu_weights_1), (2, Cu_weights_2)])), ]) scalings = OrderedDict([ ("O", OrderedDict([("intercept", 0), ("slope", 1)])), ("Pd", OrderedDict([("intercept", 0), ("slope", 1)])), ("Cu", OrderedDict([("intercept", 0), ("slope", 1)])), ]) calc = Amp( descriptor, model=NeuralNetwork( hiddenlayers=hiddenlayers, weights=weights, scalings=scalings, activation="tanh", fprange=fingerprints_range, mode="atom-centered", fortran=False, ), logging=False, ) amp_energies = [calc.get_potential_energy(image) for image in images] amp_forces = [calc.get_forces(image) for image in images] amp_forces = np.concatenate(amp_forces) torch_O_weights_1 = torch.FloatTensor(O_weights_1[:-1, :]).t() torch_O_bias_1 = torch.FloatTensor(O_weights_1[-1, :]) torch_O_weights_2 = torch.FloatTensor(O_weights_2[:-1, :]).t() torch_O_bias_2 = torch.FloatTensor(O_weights_2[-1, :]) torch_Pd_weights_1 = torch.FloatTensor(Pd_weights_1[:-1, :]).t() torch_Pd_bias_1 = torch.FloatTensor(Pd_weights_1[-1, :]) torch_Pd_weights_2 = torch.FloatTensor(Pd_weights_2[:-1, :]).t() torch_Pd_bias_2 = torch.FloatTensor(Pd_weights_2[-1, :]) torch_Cu_weights_1 = torch.FloatTensor(Cu_weights_1[:-1, :]).t() torch_Cu_bias_1 = torch.FloatTensor(Cu_weights_1[-1, :]) torch_Cu_weights_2 = torch.FloatTensor(Cu_weights_2[:-1, :]).t() torch_Cu_bias_2 = torch.FloatTensor(Cu_weights_2[-1, :]) device = "cpu" dataset = AtomsDataset( images, descriptor=Gaussian, cores=1, label="consistency", Gs=Gs, forcetraining=True, ) fp_length = dataset.fp_length batch_size = len(dataset) dataloader = DataLoader(dataset, batch_size, collate_fn=collate_amp, shuffle=False) model = FullNN(elements, [fp_length, 2, 2], device, forcetraining=True) model.state_dict()["elementwise_models.O.model_net.0.weight"].copy_( torch_O_weights_1) model.state_dict()["elementwise_models.O.model_net.0.bias"].copy_( torch_O_bias_1) model.state_dict()["elementwise_models.O.model_net.2.weight"].copy_( torch_O_weights_2) model.state_dict()["elementwise_models.O.model_net.2.bias"].copy_( torch_O_bias_2) model.state_dict()["elementwise_models.Pd.model_net.0.weight"].copy_( torch_Pd_weights_1) model.state_dict()["elementwise_models.Pd.model_net.0.bias"].copy_( torch_Pd_bias_1) model.state_dict()["elementwise_models.Pd.model_net.2.weight"].copy_( torch_Pd_weights_2) model.state_dict()["elementwise_models.Pd.model_net.2.bias"].copy_( torch_Pd_bias_2) model.state_dict()["elementwise_models.Cu.model_net.0.weight"].copy_( torch_Cu_weights_1) model.state_dict()["elementwise_models.Cu.model_net.0.bias"].copy_( torch_Cu_bias_1) model.state_dict()["elementwise_models.Cu.model_net.2.weight"].copy_( torch_Cu_weights_2) model.state_dict()["elementwise_models.Cu.model_net.2.bias"].copy_( torch_Cu_bias_2) import torch.nn as nn for name, layer in model.named_modules(): if isinstance(layer, MLP): layer.model_net = nn.Sequential(layer.model_net, Tanh()) for batch in dataloader: x = to_tensor(batch[0], device) y = to_tensor(batch[1], device) energy_pred, force_pred = model(x) for idx, i in enumerate(amp_energies): assert round(i, 4) == round( energy_pred.tolist()[idx][0], 4), "The predicted energy of image %i is wrong!" % (idx + 1) print("Energy predictions are correct!") for idx, sample in enumerate(amp_forces): for idx_d, value in enumerate(sample): predict = force_pred.tolist()[idx][idx_d] assert abs(value - predict) < 0.0001, ( "The predicted force of image % i, direction % i is wrong! Values: %s vs %s" % (idx + 1, idx_d, value, force_pred.tolist()[idx][idx_d])) print("Force predictions are correct!")
def ref_atoms(): atoms = bulk('Au') atoms.calc = EMT() atoms.get_potential_energy() return atoms
from ase.build import molecule from ase.neb import NEB from ase.calculators.emt import EMT from ase.optimize.fire import FIRE as QuasiNewton # Optimise molecule. initial = molecule('C2H6') initial.calc = EMT() relax = QuasiNewton(initial) relax.run(fmax=0.05) # Create final state. final = initial.copy() final.positions[2:5] = initial.positions[[3, 4, 2]] # Generate blank images. images = [initial] for i in range(9): images.append(initial.copy()) for image in images: image.calc = EMT() images.append(final) # Run IDPP interpolation. neb = NEB(images) neb.interpolate('idpp') # Run NEB calculation.
def test_basic_example_main_run(seed, testdir): # set up the random number generator rng = np.random.RandomState(seed) # create the surface slab = fcc111('Au', size=(4, 4, 1), vacuum=10.0, orthogonal=True) slab.set_constraint(FixAtoms(mask=len(slab) * [True])) # define the volume in which the adsorbed cluster is optimized # the volume is defined by a corner position (p0) # and three spanning vectors (v1, v2, v3) pos = slab.get_positions() cell = slab.get_cell() p0 = np.array([0., 0., max(pos[:, 2]) + 2.]) v1 = cell[0, :] * 0.8 v2 = cell[1, :] * 0.8 v3 = cell[2, :] v3[2] = 3. # Define the composition of the atoms to optimize atom_numbers = 2 * [47] + 2 * [79] # define the closest distance two atoms of a given species can be to each other unique_atom_types = get_all_atom_types(slab, atom_numbers) blmin = closest_distances_generator(atom_numbers=unique_atom_types, ratio_of_covalent_radii=0.7) # create the starting population sg = StartGenerator(slab=slab, blocks=atom_numbers, blmin=blmin, box_to_place_in=[p0, [v1, v2, v3]], rng=rng) # generate the starting population population_size = 5 starting_population = [ sg.get_new_candidate() for i in range(population_size) ] # from ase.visualize import view # uncomment these lines # view(starting_population) # to see the starting population # create the database to store information in d = PrepareDB(db_file_name=db_file, simulation_cell=slab, stoichiometry=atom_numbers) for a in starting_population: d.add_unrelaxed_candidate(a) # XXXXXXXXXX This should be the beginning of a new test, # but we are using some resources from the precious part. # Maybe refactor those things as (module-level?) fixtures. # Change the following three parameters to suit your needs population_size = 5 mutation_probability = 0.3 n_to_test = 5 # Initialize the different components of the GA da = DataConnection('gadb.db') atom_numbers_to_optimize = da.get_atom_numbers_to_optimize() n_to_optimize = len(atom_numbers_to_optimize) slab = da.get_slab() all_atom_types = get_all_atom_types(slab, atom_numbers_to_optimize) blmin = closest_distances_generator(all_atom_types, ratio_of_covalent_radii=0.7) comp = InteratomicDistanceComparator(n_top=n_to_optimize, pair_cor_cum_diff=0.015, pair_cor_max=0.7, dE=0.02, mic=False) pairing = CutAndSplicePairing(slab, n_to_optimize, blmin, rng=rng) mutations = OperationSelector([1., 1., 1.], [ MirrorMutation(blmin, n_to_optimize, rng=rng), RattleMutation(blmin, n_to_optimize, rng=rng), PermutationMutation(n_to_optimize, rng=rng) ], rng=rng) # Relax all unrelaxed structures (e.g. the starting population) while da.get_number_of_unrelaxed_candidates() > 0: a = da.get_an_unrelaxed_candidate() a.calc = EMT() print('Relaxing starting candidate {0}'.format(a.info['confid'])) with BFGS(a, trajectory=None, logfile=None) as dyn: dyn.run(fmax=0.05, steps=100) set_raw_score(a, -a.get_potential_energy()) da.add_relaxed_step(a) # create the population population = Population(data_connection=da, population_size=population_size, comparator=comp, rng=rng) # test n_to_test new candidates for i in range(n_to_test): print('Now starting configuration number {0}'.format(i)) a1, a2 = population.get_two_candidates() a3, desc = pairing.get_new_individual([a1, a2]) if a3 is None: continue da.add_unrelaxed_candidate(a3, description=desc) # Check if we want to do a mutation if rng.rand() < mutation_probability: a3_mut, desc = mutations.get_new_individual([a3]) if a3_mut is not None: da.add_unrelaxed_step(a3_mut, desc) a3 = a3_mut # Relax the new candidate a3.calc = EMT() with BFGS(a3, trajectory=None, logfile=None) as dyn: dyn.run(fmax=0.05, steps=100) set_raw_score(a3, -a3.get_potential_energy()) da.add_relaxed_step(a3) population.update() write('all_candidates.traj', da.get_all_relaxed_candidates())
p = NDPoly(len(x[0]), order) p.fit(x, y) return p a0 = 3.52 / np.sqrt(2) c0 = np.sqrt(8 / 3.0) * a0 print('%.4f %.3f' % (a0, c0 / a0)) for i in range(3): traj = Trajectory('Ni.traj', 'w') eps = 0.01 for a in a0 * np.linspace(1 - eps, 1 + eps, 4): for c in c0 * np.linspace(1 - eps, 1 + eps, 4): ni = bulk('Ni', 'hcp', a=a, covera=c / a) ni.set_calculator(EMT()) ni.get_potential_energy() traj.write(ni) traj.close() configs = read('Ni.traj@:') energies = [config.get_potential_energy() for config in configs] ac = [(config.cell[0, 0], config.cell[2, 2]) for config in configs] p = polyfit(ac, energies, 2) from scipy.optimize import fmin_bfgs a0, c0 = fmin_bfgs(p, (a0, c0)) print('%.4f %.3f' % (a0, c0 / a0)) assert abs(a0 - 2.466) < 0.001 assert abs(c0 / a0 - 1.632) < 0.005
from ase import Atoms from ase.calculators.emt import EMT from ase.optimize import QuasiNewton system = Atoms('H2', positions=[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) calc = EMT() system.set_calculator(calc) opt = QuasiNewton(system, trajectory='h2.emt.traj') opt.run(fmax=0.05)
def calculate(self, *args, **kwargs): force_evaluations[0] += 1 OrigEMT.calculate(self, *args, **kwargs)
def calculate(self, atoms=None, properties=['energy'], system_changes=all_changes): Calculator.calculate(self, atoms, properties, system_changes) temp_atoms = self.atoms.copy() temp_atoms.set_calculator(EMT()) # calculate fingerprints and preprocessing image_data = calculate_fp(temp_atoms, self.elements, self.params_set) n_atoms = len(self.atoms) n_features = len(self.params_set[self.elements[0]]['i']) atom_idx = image_data['atom_idx'] image_fp = torch.zeros([n_atoms, n_features]) image_dfpdX = torch.zeros([n_atoms, n_features, n_atoms, 3]) image_e_mask = torch.zeros([n_atoms, len(self.elements)]) for ie in range(1, len(self.elements) + 1): el = self.elements[ie - 1] image_fp[atom_idx == ie, :] = torch.FloatTensor( image_data['x'][el]) image_dfpdX[atom_idx == ie, :, :, :] = torch.FloatTensor( image_data['dx'][el]) image_e_mask[atom_idx == ie, ie - 1] = 1 image_fp = (image_fp - self.scale['fp_min']) / ( self.scale['fp_max'] - self.scale['fp_min'] + 1e-10) image_dfpdX /= (self.scale['fp_max'] - self.scale['fp_min'] + 1e-10).view(1, -1, 1, 1) image_fp.requires_grad = True image_dfpdX = image_dfpdX.reshape(n_atoms * n_features, n_atoms * 3) # calculate energy and forces nrg_preds = [] force_preds = [] for model in self.models_list: image_nrg_pre_raw = model(image_fp) # [N_atoms, N_elements] image_nrg_pre_cluster = torch.sum(image_nrg_pre_raw * image_e_mask) # [N_atoms] image_b_dnrg_dfp = torch.autograd.grad( image_nrg_pre_cluster, image_fp, create_graph=True, retain_graph=True)[0].reshape(1, -1) image_force_pre = -torch.mm(image_b_dnrg_dfp, image_dfpdX).reshape( n_atoms, 3) nrg_preds.append(image_nrg_pre_cluster.detach().item()) force_preds.append(image_force_pre.detach().numpy()) self.energy = np.mean(nrg_preds) self.uncertainty = np.std(nrg_preds) self.forces = np.mean(force_preds, axis=0) self.results['energy'] = self.energy # use the key "free_energy" to store uncertainty self.results['free_energy'] = self.uncertainty self.results['forces'] = self.forces
continue c = connect(name) print(name, c) if 'postgres' in name or 'mysql' in name or 'mariadb' in name: c.delete([row.id for row in c.select()]) id = c.reserve(abc=7) c.delete([d.id for d in c.select(abc=7)]) id = c.reserve(abc=7) assert c[id].abc == 7 a = c.get_atoms(id) c.write(Atoms()) ch4 = molecule('CH4', calculator=EMT()) ch4.constraints = [FixAtoms(indices=[1]), FixBondLength(0, 2)] f1 = ch4.get_forces() print(f1) c.delete([d.id for d in c.select(C=1)]) chi = np.array([1 + 0.5j, 0.5]) id = c.write(ch4, data={'1-butyne': 'bla-bla', 'chi': chi}) row = c.get(id) print(row.data['1-butyne'], row.data.chi) assert (row.data.chi == chi).all() print(row) assert len(c.get_atoms(C=1).constraints) == 2
import cmr except (Exception, ImportError): raise NotAvailable('CMR is required') from ase.calculators.emt import EMT from ase.structure import molecule from ase.io import write # project id: must uniquely identify the project! project_id = 'simple reaction energies' reaction = [('N2', -1), ('N', 2)] calculator = EMT() for (formula, coef) in reaction: m = molecule(formula) m.set_calculator(calculator) m.get_potential_energy() cmr_params = { "db_keywords": [project_id], # add project_id also as a field to support search across projects "project_id": project_id, "formula": formula, "calculator": calculator.name, } write(filename=('reactions_xsimple.%s.db' % formula), images=m, format='db',
from ase.neb import NEB from ase.io import Trajectory # 2x2-Al(001) surface with 3 layers and an # Au atom adsorbed in a hollow site: slab = fcc100('Al', size=(2, 2, 3)) add_adsorbate(slab, 'Au', 1.7, 'hollow') slab.center(axis=2, vacuum=4.0) # Fix second and third layers: mask = [atom.tag > 1 for atom in slab] # print(mask) slab.set_constraint(FixAtoms(mask=mask)) # Use EMT potential: slab.calc = EMT() # Initial state: qn = QuasiNewton(slab) qn.run(fmax=0.05) initial = slab.copy() # Final state: slab[-1].x += slab.get_cell()[0, 0] / 2 qn = QuasiNewton(slab) qn.run(fmax=0.05) final = slab.copy() # constraints constraint = FixAtoms(mask=[atom.tag > 1 for atom in initial])
x2 = 4.137 x3 = 2.759 y1 = 0.0 y2 = 2.238 z1 = 7.165 z2 = 6.439 #Add the adatom to the list of atoms and set constraints of surface atoms. slab += Atoms('N', [((x2 + x1) / 2, y1, z1 + 1.5)]) mask = [atom.symbol == 'Pt' for atom in slab] slab.set_constraint(FixAtoms(mask=mask)) #optimise the initial state # Atom below step initial = slab.copy() initial.set_calculator(EMT()) relax = QuasiNewton(initial) relax.run(fmax=0.05) view(initial) #optimise the initial state # Atom above step slab[-1].position = (x3, y2 + 1, z2 + 3.5) final = slab.copy() final.set_calculator(EMT()) relax = QuasiNewton(final) relax.run(fmax=0.05) view(final) #create a list of images for interpolation images = [initial]
""" import os from ase.structure import molecule from ase.lattice.surface import fcc111, add_adsorbate from ase.optimize import QuasiNewton from ase.constraints import FixAtoms from ase.calculators.emt import EMT from ase.vibrations import Vibrations import ase.io import chemcoord as cc if os.path.exists('CH3_Al.traj'): slab = ase.io.read('CH3_Al.traj') slab.set_calculator(EMT()) # Need to reset when loading from traj file else: slab = fcc111('Al', size=(2, 2, 2), vacuum=3.0) CH3 = molecule('CH3') add_adsorbate(slab, CH3, 2.5, 'ontop') constraint = FixAtoms(mask=[a.symbol == 'Al' for a in slab]) slab.set_constraint(constraint) slab.set_calculator(EMT()) dyn = QuasiNewton(slab, trajectory='QN_slab.traj') dyn.run(fmax=0.05) ase.io.write('CH3_Al.traj', slab)
from ase.constraints import FixAtoms from ase.calculators.emt import EMT from ase.vibrations import Vibrations sys.path.append("../..") from __init__ import AnharmonicModes slab = fcc111('Au', size=(2, 2, 2), vacuum=4.0) H = molecule('H') add_adsorbate(slab, H, 3.0, 'bridge') constraint = FixAtoms(mask=[a.symbol == 'Au' for a in slab]) slab.set_constraint(constraint) slab.set_calculator(EMT()) dyn = QuasiNewton(slab) dyn.run(fmax=0.01) # Running vibrational analysis vib = Vibrations(slab, indices=[8]) vib.run() vib.summary() # Here the number of initial sampling points are increased such # that the potential energy surface of the translation comes # out looking good. # The result with the default value of 5 (not setting n_initial), # will be a potential energy surface that is well fitted,
import matplotlib.pyplot as plt import scipy.stats as stats from collections import defaultdict from ase.visualize import view from amp_pytorch.lj_model import lj_optim from ase.io.trajectory import Trajectory images_emt = ase.io.read("../datasets/COCu/COCu.traj", ":") images0 = [] for i in range(101): images0.append(images_emt[i]) images1 = ase.io.read("MD_results/MLMD_LJ_COCu.traj", ":") images2 = ase.io.read("MD_results/MLMD_COCu.traj", ":") for image in images1: image.set_calculator(EMT()) for image in images2: image.set_calculator(EMT()) # forces0 = np.array([np.amax(np.abs(image.get_forces())) for image in images0]).reshape( # -1, 1 # ) # print(np.mean(forces0)) # forces1 = np.array([np.amax(np.abs(image.get_forces())) for image in images1]).reshape( # -1, 1 # ) # print(np.mean(forces1)) # forces2 = np.array([np.amax(np.abs(image.get_forces())) for image in images2]).reshape( # -1, 1 # ) # print(np.mean(forces2))
import cmr except ImportError: raise NotAvailable('CMR is required') from ase.calculators.emt import EMT from ase.structure import molecule from ase.io import write # project id: must uniquely identify the project! project_id = 'simple reaction energies' reaction = [('N2', -1), ('N', 2)] calculator = EMT() for (formula, coef) in reaction: m = molecule(formula) m.set_calculator(calculator) m.get_potential_energy() cmr_params = { "db_keywords": [project_id], # add project_id also as a field to support search across projects "project_id": project_id, "formula": formula, "calculator": calculator.get_name(), } write(filename=('reactions_xsimple.%s.db' % formula), images=m, format='db', cmr_params=cmr_params)
import numpy as np from ase.calculators.emt import EMT from ase import Atoms a = 3.60 b = a / 2 cu = Atoms('Cu', positions=[(0, 0, 0)], cell=[(0, b, b), (b, 0, b), (b, b, 0)], pbc=1, calculator=EMT()) e0 = cu.get_potential_energy() print(e0) cu.set_cell(cu.get_cell() * 1.001, scale_atoms=True) e1 = cu.get_potential_energy() V = a**3 / 4 B = 2 * (e1 - e0) / 0.003**2 / V * 160.2 print(B) for i in range(4): x = 0.001 * i A = np.array([(x, b, b + x), (b, 0, b), (b, b, 0)]) cu.set_cell(A, scale_atoms=True) e = cu.get_potential_energy() - e0 if i == 0: print(i, e) else: print(i, e, e / x**2) A = np.array([(0, b, b), (b, 0, b), (6 * b, 6 * b, 0)])