def calculate(self, atoms, name): args = self.args if args.constrain_tags: tags = [int(t) for t in args.constrain_tags.split(',')] mask = [t in tags for t in atoms.get_tags()] atoms.constraints = FixAtoms(mask=mask) trajectory = PickleTrajectory(self.get_filename(name, 'traj'), 'w', atoms) if args.maximum_stress: optimizer = LBFGS(UnitCellFilter(atoms), logfile=self.logfile) fmax = args.maximum_stress else: optimizer = LBFGS(atoms, logfile=self.logfile) fmax = args.maximum_force optimizer.attach(trajectory) optimizer.run(fmax=fmax) data = RunCommand.calculate(self, atoms, name) if hasattr(optimizer, 'force_calls'): data['force calls'] = optimizer.force_calls return data
def test_qchem_calculator(): import numpy as np from ase.build import molecule from ase.calculators.qchem import QChem from ase.optimize import LBFGS mol = molecule('C2H6') calc = QChem(label='calc/ethane', method='B3LYP', basis='6-31+G*') mol.set_calculator(calc) # Check energy and forces np.testing.assert_allclose(mol.get_potential_energy(), -2172.379183703419, atol=10.) np.testing.assert_allclose(mol.get_forces(), np.array( [[0., 0.00240141, 0.04992568], [-0., -0.00240141, -0.04992568], [-0., 0.11626015, 0.07267481], [-0.10132204, -0.05804009, 0.07538475], [0.10132204, -0.05804009, 0.07538475], [-0., -0.11626015, -0.07267481], [-0.10132204, 0.05804009, -0.07538475], [0.10132204, 0.05804009, -0.07538475]]), atol=0.05) opt = LBFGS(mol) opt.run() assert opt.converged()
def opt(self, rdkmol, dhls, logger='optlog.out'): Na = rdkmol.GetNumAtoms() X, S = __convert_rdkitmol_to_nparr__(rdkmol) atm=Atoms(symbols=S, positions=X) atm.set_calculator(ANIENS(self.ens)) #Set the ANI Ensemble as the calculator phi_fix = [] for d in dhls: phi_restraint=atm.get_dihedral(d) phi_fix.append([phi_restraint, d]) c = FixInternals(dihedrals=phi_fix, epsilon=1.e-9) atm.set_constraint(c) dyn = LBFGS(atm, logfile=logger) #Choose optimization algorith dyn.run(fmax=self.fmax, steps=1000) #optimize molecule to Gaussian's Opt=Tight fmax criteria, input in eV/A (I think) e=atm.get_potential_energy()*hdt.evtokcal s=atm.calc.stddev*hdt.evtokcal phi_value = [] for d in dhls: phi_value.append(atm.get_dihedral(d)*180./np.pi) #X = mol.get_positions() if self.printer: print('Phi value (degrees), energy (kcal/mol), sigma= ', phi_value, "{0:.2f}".format(e), "{0:.2f}".format(s)) return phi_value, e, s, atm
def test_unitcellfilter(asap3): cu = bulk('Cu') * (6, 6, 6) cu.calc = asap3.EMT() f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0]) opt = LBFGS(f) t = Trajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0)
def optimize_rdkit_molecule(self, mrdk, cid, fmax=0.0001, steps=500, logger='opt.out'): mol = __convert_rdkitmol_to_aseatoms__(mrdk,cid) mol.set_calculator(ANI(False)) mol.calc.setnc(self.nc) dyn = LBFGS(mol,logfile=logger) #dyn = LBFGS(mol) dyn.run(fmax=fmax,steps=steps) stps = dyn.get_number_of_steps() xyz = mol.get_positions() for i,x in enumerate(xyz): mrdk.GetConformer(cid).SetAtomPosition(i,x)
def test_optimizer(atoms): pos = atoms.positions.copy() atoms.calc = get_calc(label='opt', scf='qc') opt_gauss = GaussianOptimizer(atoms) opt_gauss.run(fmax='tight') e_gaussopt = read('opt.log', index=-1).get_potential_energy() atoms.positions[:] = pos atoms.calc.set_label('sp') opt_ase = LBFGS(atoms, trajectory='ase_opt.traj') opt_ase.run(fmax=1e-2) e_aseopt = atoms.get_potential_energy() assert e_gaussopt - e_aseopt == pytest.approx(0., abs=1e-3)
def test_pressure(atoms, cellfilter): xcellfilter = cellfilter(atoms, scalar_pressure=10.0 * GPa) # test all derivatives f, fn = gradient_test(xcellfilter) assert abs(f - fn).max() < 5e-6 opt = LBFGS(xcellfilter) opt.run(1e-3) # check pressure is within 0.1 GPa of target sigma = atoms.get_stress() / GPa pressure = -(sigma[0] + sigma[1] + sigma[2]) / 3.0 assert abs(pressure - 10.0) < 0.1
def optimize_molecule(self, X, S, fmax=0.1, steps=10000, logger='opt.out'): mol = Atoms(symbols=S, positions=X) mol.set_pbc((False, False, False)) mol.set_calculator(ANIENS(self.ens)) dyn = LBFGS(mol,logfile=logger) #dyn = LBFGS(mol) #dyn = QuasiNewton(mol,logfile=logger) dyn.run(fmax=fmax,steps=steps) stps = dyn.get_number_of_steps() opt = True if steps == stps: opt = False return np.array(mol.get_positions(),dtype=np.float32), opt
def relax_atoms(atoms, tol=1e-3, method='lbfgs_precon', max_steps=1000, traj_file=None, **kwargs): import model atoms.set_calculator(model.calculator) if hasattr(model, 'Optimizer'): method = 'model_optimizer' opt = model.Optimizer(atoms) opt.run(tol, max_steps) elif method.startswith('lbfgs') or method == 'fire' or method == 'cg_n': if method == 'lbfgs_ASE': from ase.optimize import LBFGS opt = LBFGS(atoms, **kwargs) elif method == 'cg_n': from quippy import Minim opt = Minim(atoms, relax_positions=True, relax_cell=False, method='cg_n') else: from ase.optimize.precon.precon import Exp from ase.optimize.precon.lbfgs import PreconLBFGS precon = None if method.endswith('precon'): precon = Exp(3.0, recalc_mu=True) if method.startswith('lbfgs'): opt = PreconLBFGS(atoms, precon=precon, **kwargs) else: opt = FIRE(atoms, **kwargs) if traj_file is not None and method != 'cg_n': traj = open(traj_file, 'w') def write_trajectory(): write(traj, atoms, format='extxyz') opt.attach(write_trajectory) opt.run(tol, max_steps) try: traj.close() except: pass else: raise ValueError('unknown method %s!' % method) return atoms
def optimize(self, atoms, name): args = self.args if args.constrain_tags: tags = [int(t) for t in args.constrain_tags.split(',')] mask = [t in tags for t in atoms.get_tags()] atoms.constraints = FixAtoms(mask=mask) logfile = self.get_filename(name, 'log') if args.maximum_stress: optimizer = LBFGS(UnitCellFilter(atoms), logfile=logfile) fmax = args.maximum_stress else: optimizer = LBFGS(atoms, logfile=logfile) fmax = args.maximum_force trajectory = Trajectory(self.get_filename(name, 'traj'), 'w', atoms) optimizer.attach(trajectory) optimizer.run(fmax=fmax)
def SurfaceEnergy(images, natoms, calc, fmax=0.01, debug=False): """Calculate the surface energy from a list of slab images. Parameters ---------- images: List of slab images which the calculation is based on. The x and y dimensions of the images unit cell must be conserved. natoms: Number of atoms in a atomic layer in the slabs. calc: Calculator object that can be attached to the images. """ ucell = images[0].get_cell() layers = np.zeros(len(images)) energies = np.zeros(len(images)) if debug: print "Layers Energy LBFGS steps" for i, atoms in enumerate(images): cell = atoms.get_cell() if (ucell[0] != cell[0]).any() or (ucell[1] != cell[1]).any(): raise ValueError( "The x and y dimensions of the unit cell must be conserved.") atoms.set_calculator(calc) dyn = LBFGS(atoms, logfile=None, trajectory=None) dyn.run(fmax=fmax, steps=1000) assert dyn.converged(), "LBFGS not converged in 100 steps!" layers[i] = len(atoms) / natoms energies[i] = atoms.get_potential_energy() if debug: print "%4i%12.3f%10i" % (layers[i], energies[i], dyn.get_number_of_steps()) p = polyfit(layers.reshape((-1, 1)), energies, 1) surface_energy = p.c[0] / (2 * natoms) assert surface_energy > 0.0 return surface_energy
def make_methylamine(): # Construct Methylamine. atoms = Atoms('NH2CH3') # Define connectivity. atoms_bonds = [ [0,1], [0,2], [0,3], [3,4], [3,5], [3,6] ] # Displace atoms so that they aren't on top of each other. atoms.rattle(0.001) # Construct VSEPR calculator. calculator = VSEPR(atoms, atoms_bonds) atoms.set_calculator(calculator) atoms.center() # Run optimization. opt = LBFGS(atoms, logfile='/dev/null') opt.run() return atoms
def optimize_rdkit_molecule(self, mrdk, cid, fmax=0.1, steps=10000, logger='opt.out'): mol = __convert_rdkitmol_to_aseatoms__(mrdk,cid) mol.set_pbc((False, False, False)) mol.set_calculator(ANIENS(self.ens)) dyn = LBFGS(mol,logfile=logger) #dyn = LBFGS(mol) #dyn = QuasiNewton(mol,logfile=logger) dyn.run(fmax=fmax,steps=steps) stps = dyn.get_number_of_steps() opt = True if steps == stps: opt = False xyz = mol.get_positions() for i,x in enumerate(xyz): mrdk.GetConformer(cid).SetAtomPosition(i,x) return opt
def SurfaceEnergy(images, natoms, calc, fmax=0.01, debug=False): """Calculate the surface energy from a list of slab images. Parameters ---------- images: List of slab images which the calculation is based on. The x and y dimensions of the images unit cell must be conserved. natoms: Number of atoms in a atomic layer in the slabs. calc: Calculator object that can be attached to the images. """ ucell = images[0].get_cell() layers = np.zeros(len(images)) energies = np.zeros(len(images)) if debug: print "Layers Energy LBFGS steps" for i, atoms in enumerate(images): cell = atoms.get_cell() if (ucell[0] != cell[0]).any() or (ucell[1] != cell[1]).any(): raise ValueError("The x and y dimensions of the unit cell must be conserved.") atoms.set_calculator(calc) dyn = LBFGS(atoms, logfile=None, trajectory=None) dyn.run(fmax=fmax, steps=1000) assert dyn.converged(), "LBFGS not converged in 100 steps!" layers[i] = len(atoms) / natoms energies[i] = atoms.get_potential_energy() if debug: print "%4i%12.3f%10i" % (layers[i], energies[i], dyn.get_number_of_steps()) p = polyfit(layers.reshape((-1,1)), energies, 1) surface_energy = p.c[0] / (2 * natoms) assert surface_energy > 0.0 return surface_energy
def relax_bare_cluster(cluster, relax_fmax=0.05): c0 = cluster.copy() orig_index = c0.get_array("orig_index") fix_list = np.loadtxt("cp2k_fix_list.txt", dtype="int") - 1 fix_orig_index = [orig_index[i] for i in fix_list] hydrogens = np.where(c0.get_atomic_numbers() == 1)[0] del c0[hydrogens] new_fix_list = [i for i, j in enumerate(c0.get_array("orig_index")) if j in fix_orig_index] pot = calc c0.set_calculator(pot) c0.get_potential_energy() c0.set_array("fixdip", np.array([True if i in new_fix_list else False for i in range(len(c0))])) c0.set_array("dipoles", np.zeros((len(c0), 3))) # pot.atoms.arrays['dipoles']) # c0.arrays['dipoles'][new_fix_list, :] = 0.0 const = FixAtoms(indices=new_fix_list) c0.set_constraint(const) opt = LBFGS(c0) opt.run(fmax=relax_fmax) return c0
def test_Ar_minimize(): from ase.calculators.lammpsrun import LAMMPS from ase.cluster.icosahedron import Icosahedron from ase.data import atomic_numbers, atomic_masses from numpy.testing import assert_allclose from ase.optimize import LBFGS ar_nc = Icosahedron('Ar', noshells=2) ar_nc.cell = [[300, 0, 0], [0, 300, 0], [0, 0, 300]] ar_nc.pbc = True params = {} params['pair_style'] = 'lj/cut 8.0' params['pair_coeff'] = ['1 1 0.0108102 3.345'] params['masses'] = ['1 {}'.format(atomic_masses[atomic_numbers['Ar']])] with LAMMPS(specorder=['Ar'], **params) as calc: ar_nc.calc = calc assert_allclose(ar_nc.get_potential_energy(), -0.468147667942117, atol=1e-4, rtol=1e-4) assert_allclose(ar_nc.get_forces(), calc.calculate_numerical_forces(ar_nc), atol=1e-4, rtol=1e-4) dyn = LBFGS(ar_nc, force_consistent=False) dyn.run(fmax=1E-6) assert_allclose(ar_nc.get_potential_energy(), -0.4791815886953914, atol=1e-4, rtol=1e-4) assert_allclose(ar_nc.get_forces(), calc.calculate_numerical_forces(ar_nc), atol=1e-4, rtol=1e-4)
def add_ligand(atoms, ligand, site, position=None): atoms.set_tags(0) ligand = ligand.copy() # Extract nanoparticle. np_idx = [ i for i in xrange(len(atoms)) if atoms[i].number > 20 ] nanoparticle = atoms[np_idx] # Pick a binding site and shift ligand above it. com = nanoparticle.get_center_of_mass() v = atoms[site].position - com v /= numpy.linalg.norm(v) ligand.center() displacement_length = 1.1 * ligand_size(ligand) if position is None: ligand.positions += atoms.positions[site] + displacement_length*v else: ligand.positions += position + displacement_length*v ligand.set_tags(1) # Create combined system. atoms += ligand # Construct VSEPR calculator with N-Au interaction. ligand_mask = [tag == 1 for tag in atoms.get_tags()] ligand_bonds = connect_bonds(atoms, mask=ligand_mask) calculator = VSEPR(atoms, ligand_bonds + [[site,len(atoms)-len(ligand)]], nonbonded=connect_nonbonded(atoms, connect_angles(ligand_bonds), r_cut=displacement_length*2)) atoms.set_calculator(calculator) atoms.set_constraint(FixAtoms(indices=range(len(atoms)-len(ligand)))) # Run optimization. opt = LBFGS(atoms, memory=10, maxstep=0.2) opt.run(fmax=1e-2)
def optimize(self, atoms, name): args = self.args if args.constrain_tags: tags = [int(t) for t in args.constrain_tags.split(',')] mask = [t in tags for t in atoms.get_tags()] atoms.constraints = FixAtoms(mask=mask) trajectory = Trajectory(self.get_filename(name, 'traj'), 'w', atoms) if args.maximum_stress: optimizer = LBFGS(UnitCellFilter(atoms), logfile=self.logfile) fmax = args.maximum_stress else: optimizer = LBFGS(atoms, logfile=self.logfile) fmax = args.maximum_force optimizer.attach(trajectory) optimizer.run(fmax=fmax) data = {} if hasattr(optimizer, 'force_calls'): data['force_calls'] = optimizer.force_calls return data
def test_Ar_minimize(factory, ar_nc, params): with factory.calc(specorder=['Ar'], **params) as calc: ar_nc.calc = calc assert_allclose(ar_nc.get_potential_energy(), -0.468147667942117, atol=1e-4, rtol=1e-4) assert_allclose(ar_nc.get_forces(), calc.calculate_numerical_forces(ar_nc), atol=1e-4, rtol=1e-4) dyn = LBFGS(ar_nc, force_consistent=False) dyn.run(fmax=1E-6) assert_allclose(ar_nc.get_potential_energy(), -0.4791815886953914, atol=1e-4, rtol=1e-4) assert_allclose(ar_nc.get_forces(), calc.calculate_numerical_forces(ar_nc), atol=1e-4, rtol=1e-4)
def test_unitcellfilter(asap3): a = 3.6 b = a / 2 cu = Atoms('Cu', cell=[(0, b, b), (b, 0, b), (b, b, 0)], pbc=1) * (6, 6, 6) cu.calc = asap3.EMT() f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0]) opt = LBFGS(f) t = Trajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0) # HCP: from ase.build import bulk cu = bulk('Cu', 'hcp', a=a / sqrt(2)) 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) t = Trajectory('Cu-hcp.traj', 'w', cu) opt.attach(t) opt.run(0.2)
def test_unitcellfilter(): from math import sqrt from ase import Atoms from ase.optimize import LBFGS from ase.constraints import UnitCellFilter from ase.io import Trajectory from ase.optimize.mdmin import MDMin try: from asap3 import EMT except ImportError: pass else: a = 3.6 b = a / 2 cu = Atoms('Cu', cell=[(0, b, b), (b, 0, b), (b, b, 0)], pbc=1) * (6, 6, 6) cu.set_calculator(EMT()) f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0]) opt = LBFGS(f) t = Trajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0) # HCP: from ase.build import bulk cu = bulk('Cu', 'hcp', a=a / sqrt(2)) cu.cell[1, 0] -= 0.05 cu *= (6, 6, 3) cu.set_calculator(EMT()) print(cu.get_forces()) print(cu.get_stress()) f = UnitCellFilter(cu) opt = MDMin(f, dt=0.01) t = Trajectory('Cu-hcp.traj', 'w', cu) opt.attach(t) opt.run(0.2)
def relax(self): from ase.optimize import LBFGS cached = sys.__stdout__ try: optimizer = LBFGS(self.ucf) optimizer.logfile = None optimised = optimizer.run(fmax=0.05, steps=100) except Exception: optimised = False self.doc["optimised"] = bool(optimised) self.doc["positions_abs"] = self.atoms.get_positions().tolist() self.doc["lattice_cart"] = self.atoms.get_cell().tolist() self.doc["lattice_abc"] = cart2abc(self.doc["lattice_cart"]) self.doc["positions_frac"] = cart2frac(self.doc["lattice_cart"], self.doc["positions_abs"]) self.doc["enthalpy_per_atom"] = float(self.calc.results["energy"] / len(self.doc["atom_types"])) self.doc["enthalpy"] = float(self.calc.results["energy"]) self.queue.put(self.doc) sys.stdout = cached
!wget https://www.quantum-espresso.org/upf_files/Cl.pbesol-n-kjpaw_psl.1.0.0.UPF #---- from ase.build import bulk from ase.calculators.espresso import Espresso from ase.constraints import UnitCellFilter from ase.optimize import LBFGS import ase.io pseudopotentials = {'Na': 'Na.pbesol-spn-kjpaw_psl.1.0.0.UPF', 'Cl': 'Cl.pbesol-n-kjpaw_psl.1.0.0.UPF'} rocksalt = bulk('NaCl', crystalstructure='rocksalt', a=6.0) calc = Espresso(pseudopotentials=pseudopotentials,pseudo_dir = './', tstress=True, tprnfor=True, kpts=(3, 3, 3)) rocksalt.set_calculator(calc) ucf = UnitCellFilter(rocksalt) opt = LBFGS(ucf) opt.run(fmax=0.005) # cubic lattic constant print((8*rocksalt.get_volume()/len(rocksalt))**(1.0/3.0)) #---- # %cd /content !mkdir Cu # %cd Cu #---- !wget https://www.quantum-espresso.org/upf_files/Cu.pz-d-rrkjus.UPF #---- from ase import Atoms from ase.build import bulk from ase.calculators.espresso import Espresso atoms = bulk("Cu") pseudopotentials = {'Cu':'Cu.pz-d-rrkjus.UPF'} input_data = {
(-r * cos(a / 2), -r * sin(a / 2), 0), (0, 0, 0), (-r * cos(a), 0, r * sin(a)), (-r, 0, 0)]) dimer.positions[3:, 0] += 2.8 dimer.constraints = FixBondLengths([ ((selection[i] + 3) % 6, (selection[i - 1] + 3) % 6) for i in range(3) ]) dimer.calc = EIQMMM(selection, GPAW(txt=name + '.txt', h=0.16), TIP4P(), interaction, vacuum=4, embedding=Embedding(rc=0.2, rc2=20, width=1), output=name + '.out') opt = LBFGS(dimer, trajectory=name + '.traj') opt.run(0.02) monomer = dimer[selection] monomer.center(vacuum=4) monomer.calc = GPAW(txt=name + 'M.txt', h=0.16) opt = PreconLBFGS(monomer, precon=Exp(A=3), trajectory=name + 'M.traj') opt.run(0.02) e0 = monomer.get_potential_energy() be = dimer.get_potential_energy() - e0 d = dimer.get_distance(0, 3) print(name, be, d) if name == '012': assert abs(be - -0.288) < 0.002 assert abs(d - 2.76) < 0.02 else: assert abs(be - -0.316) < 0.002
atoms=read('../'+fo2+'.xsf') mask = [atom.position[2] < 17 for atom in atoms] fixlayers = FixAtoms(mask=mask) atoms.set_constraint(fixlayers) atoms.set_pbc([1,1,1]) # 2. Benchmark. ############################################################################### # 2.C Optimize using LBFGS. initial_lbfgs = atoms.copy() initial_lbfgs.set_calculator(calc) lbfgs_opt = LBFGS(initial_lbfgs, trajectory=fo2+'_lbfgs.traj') itime=time.default_timer() lbfgs_opt.run(fmax=0.01) logging.warning('lbfgs = %s', time.default_timer()-itime) # 2.D Optimize using FIRE. initial_fire = atoms.copy() initial_fire.set_calculator(calc) fire_opt = FIRE(initial_fire, trajectory=fo2+'_fire.traj') itime=time.default_timer() fire_opt.run(fmax=0.01) logging.warning('fires = %s', time.default_timer()-itime) # 2.A. Optimize structure using MLMin (CatLearn). initial_mlmin = atoms.copy() initial_mlmin.set_calculator(calc) mlmin_opt = MLMin(initial_mlmin, trajectory=fo2+'_catlearn.traj') itime=time.default_timer()
ediffg = float(line.split('=')[1]) ediffg = ediffg * -1.0 return nsw, pstress, tebeg, potim, ediffg if __name__ == '__main__': ''' stress format: XX XY XZ YY YZ ZZ units: kB ''' calc = GAP(rcut=6.0) nsw, pstress, _, _, ediffg = read_incar() my_atoms = read('POSCAR', format='vasp') my_atoms.set_calculator(calc) dyn = LBFGS(my_atoms, trajectory='ase.traj') dyn.run(fmax=ediffg, steps=nsw) atoms_lat = my_atoms.cell atoms_pos = my_atoms.positions atoms_force = my_atoms.get_forces() atoms_stress = my_atoms.get_stress() atoms_num = my_atoms.get_atomic_numbers() atoms_symbols = my_atoms.get_chemical_symbols() atoms_formula = my_atoms.get_chemical_formula() atoms_ene = my_atoms.get_potential_energy() atoms_vol = my_atoms.get_volume() element, ele = get_ele_dict(atoms_symbols) write_contcar(element, ele, atoms_lat, atoms_pos) write_outcar(element, ele, atoms_vol, atoms_lat, atoms_pos, \ atoms_ene, atoms_force, atoms_stress * 10.0, pstress)
# Construct pyNeuroChem class nc = pync.molecule(cnstfile, saefile, nnfdir, 0) files = [f for f in os.listdir(idir) if f.split(".")[1] == "ipt"] for i, f in enumerate(files): data = hdn.read_rcdb_coordsandnm(idir + f) X = data['coordinates'] S = data['species'] mol = Atoms(positions=X, symbols=S) mol.set_calculator(ANI(False)) mol.calc.setnc(nc) dyn = LBFGS(mol, logfile='optimization.log') dyn.run(fmax=0.00001, steps=1000) X = mol.get_positions() Nc = int(f.split(".")[0].split("-")[1]) Fp = f.split("-")[0] smiles = get_smiles(idir + f) print(i, 'of', len(files), ':', f, dyn.get_number_of_steps(), Nc) hdn.write_rcdb_input(X, S, Nc, sdir, Fp, 50, 'wb97x/6-31g*',
from ase.io import Trajectory from ase.optimize.mdmin import MDMin try: from asap3 import EMT except ImportError: pass else: a = 3.6 b = a / 2 cu = Atoms('Cu', cell=[(0, b, b), (b, 0, b), (b, b, 0)], pbc=1) * (6, 6, 6) cu.set_calculator(EMT()) f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0]) opt = LBFGS(f) t = Trajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0) # HCP: from ase.build import hcp0001 cu = hcp0001('Cu', (1, 1, 2), a=a / sqrt(2)) cu.cell[1, 0] += 0.05 cu *= (6, 6, 3) cu.set_calculator(EMT()) print(cu.get_forces()) print(cu.get_stress()) f = UnitCellFilter(cu) opt = MDMin(f, dt=0.01) t = Trajectory('Cu-hcp.traj', 'w', cu) opt.attach(t) opt.run(0.2)
#!/usr/bin/env python3 from ase import Atom, Atoms from ase.build import bulk, fcc100, add_adsorbate, add_vacuum from ase.calculators.vasp import Vasp from ase.calculators.kim.kim import KIM from ase.calculators.qmmm import ForceQMMM, RescaledCalculator from ase.constraints import StrainFilter from ase.optimize import LBFGS from ase.visualize import view atoms = bulk("Pd", "fcc", a=3.5, cubic=True) atoms.calc = KIM("MEAM_LAMMPS_JeongParkDo_2018_PdMo__MO_356501945107_000") opt = LBFGS(StrainFilter(atoms), logfile=None) opt.run(0.03, steps=30) length = atoms.cell.cellpar()[0] atoms = fcc100("Pd", (2,2,5), a=length, vacuum=10, periodic=True) add_adsorbate(atoms, Atoms([Atom("Mo")]), 1.2) qm_mask = [len(atoms)-1, len(atoms)-2] qm_calc = Vasp(directory="./qmmm") mm_calc = KIM("MEAM_LAMMPS_JeongParkDo_2018_PdMo__MO_356501945107_000") mm_calc = RescaledCalculator(mm_calc, 1, 1, 1, 1) qmmm = ForceQMMM(atoms, qm_mask, qm_calc, mm_calc, buffer_width=3) qmmm.initialize_qm_buffer_mask(atoms) atoms.pbc=True atoms.calc = qmmm print(atoms.get_forces())
params = {} params['pair_style'] = 'lj/cut 8.0' params['pair_coeff'] = ['1 1 0.0108102 3.345'] params['masses'] = ['1 {}'.format(atomic_masses[atomic_numbers['Ar']])] calc = LAMMPS(specorder=['Ar'], **params) ar_nc.set_calculator(calc) assert_allclose(ar_nc.get_potential_energy(), -0.468147667942117, atol=1e-4, rtol=1e-4) assert_allclose(ar_nc.get_forces(), calc.calculate_numerical_forces(ar_nc), atol=1e-4, rtol=1e-4) dyn = LBFGS(ar_nc, force_consistent=False) dyn.run(fmax=1E-6) assert_allclose(ar_nc.get_potential_energy(), -0.4791815886953914, atol=1e-4, rtol=1e-4) assert_allclose(ar_nc.get_forces(), calc.calculate_numerical_forces(ar_nc), atol=1e-4, rtol=1e-4)
dir = '/home/jujuman/Research/GDB-11-wB97X-6-31gd/dnntsgdb11_02/' #bz = read('C_100.xyz') #bz = read('/home/jujuman/Research/GDB-11-wB97X-6-31gd/dnnts_testdata/specialtest/test.xyz') bz = read(dir + 'molecule-0.xyz') #L = 16.0 #bz.set_cell(([[L,0,0],[0,L,0],[0,0,L]])) #bz.set_pbc((True, True, True)) bz.set_calculator(ANI(False)) bz.calc.setnc(nc) start_time = time.time() dyn = LBFGS(bz) dyn.run(fmax=0.0001) print('[ANI Total time:', time.time() - start_time, 'seconds]') # Write visualization of molecule #f = open("optmol_begin.xyz",'w') #f.write('\n' + str(len(bz)) + '\n') #for i in bz: # f.write(str(i.symbol) + ' ' + str(i.x) + ' ' + str(i.y) + ' ' + str(i.z) + '\n') #f.close() # Temperature T = 300.0 # We want to run MD with constant energy using the Langevin algorithm # with a time step of 5 fs, the temperature T and the friction # coefficient to 0.02 atomic units.
import numpy as np from ase.build import molecule from ase.calculators.qchem import QChem from ase.optimize import LBFGS mol = molecule('C2H6') calc = QChem(label='calc/ethane', method='B3LYP', basis='6-31+G*') mol.set_calculator(calc) # Check energy and forces np.testing.assert_allclose(mol.get_potential_energy(), -2172.379183703419, atol=10.) np.testing.assert_allclose(mol.get_forces(), np.array([[0., 0.00240141, 0.04992568], [-0., -0.00240141, -0.04992568], [-0., 0.11626015, 0.07267481], [-0.10132204, -0.05804009, 0.07538475], [0.10132204, -0.05804009, 0.07538475], [-0., -0.11626015, -0.07267481], [-0.10132204, 0.05804009, -0.07538475], [0.10132204, 0.05804009, -0.07538475]]), atol=0.05) opt = LBFGS(mol) opt.run() assert opt.converged()
from ase_interface import aniensloader import ase import time from ase import units from ase.io import read, write from ase.optimize import BFGS, LBFGS # Read molecule from xyz mol = read('data/water.xyz') # Current ANI model options are: # '../ani_models/ani-1ccx_8x.info' Coupled cluster transfer learned model # '../ani_models/ani-1x_8x.info' Full ANI-1x wb97x/6-31g* dataset model mol.set_calculator(ANIENS(aniensloader('../ani_models/ani-1ccx_8x.info', 0))) # Calculate energy ei = mol.get_potential_energy() print("Initial Energy: ", ei) # Optimize molecule print("Optimizing...") start_time = time.time() dyn = LBFGS(mol) dyn.run(fmax=0.001) print('[ANI Optimization - Total time:', time.time() - start_time, 'seconds]') # Calculate energy ef = mol.get_potential_energy() print("Final Energy: ", ef)
calc = fp_GD_Calculator() # atoms.set_calculator(calc) atoms.calc = calc ############################## Relaxation type ############################## ''' Ref : https://wiki.fysik.dtu.dk/ase/ase/optimize.html#module-optimize https://wiki.fysik.dtu.dk/ase/ase/constraints.html ''' af = atoms # af = StrainFilter(atoms) # af = UnitCellFilter(atoms) print(af.get_forces()) ############################## Relaxation method ############################## # opt = BFGS(af, maxstep = 1.e-3, trajectory = trajfile) # opt = FIRE(af, maxstep = 1.e-3, trajectory = trajfile) opt = LBFGS(af, maxstep = 1.e-1, trajectory = trajfile, memory = 10, use_line_search = True) # opt = LBFGS(af, maxstep = 1.e-3, trajectory = trajfile, memory = 10, use_line_search = False) # opt = SciPyFminCG(af, trajectory = trajfile) # opt = SciPyFminBFGS(af, trajectory = trajfile) opt.run(fmax = 1.e-10) traj = Trajectory(trajfile) ase.io.write('opt.vasp', traj[-1], direct = True, long_format=True, vasp5 = True)
from asap3 import * from ase.lattice.cubic import FaceCenteredCubic from ase.optimize import LBFGS import numpy as np calc = EMT() symbol = 'Cu' syms = ((True, True, True), (False, False, False), (True, True, False), (True, False, False)) for symmetry in syms: print "Periodicity:", symmetry for n in (4,6): atoms = FaceCenteredCubic(symbol=symbol, size=(4, 8, n), pbc=symmetry) atoms.set_calculator(calc) dyn = LBFGS(atoms, trajectory=None, logfile=None) dyn.run(fmax=0.05) e = atoms.get_potential_energy() print "Layers, energy: %2i %8.3f" % (n, e) print "TEST PASSED."
file_name = file_name_py.replace('.py', '') file_traj = file_name + '.traj' start_file = '../In2O3_110_clean.traj' mode = 'a' try: sys = Trajectory(file_traj, 'r')[-1] except (IOError, RuntimeError): print "Importing trajectory file from: %s" % start_file sys = read(start_file) sys.center(vacuum=5.0, axis=2) else: print "Importing trajectory file from: %s" % file_traj set_calc_In2O3(sys) print "Constraints:" print " c1: Fix bottom two layers." avg_z = np.mean([atom.z for atom in sys]) c1 = FixAtoms(mask=[atom.z < avg_z for atom in sys]) sys.set_constraint(c1) if testRun == True: run_testRun(sys) else: geo_traj = Trajectory(file_traj, mode, sys) dyn = LBFGS(sys, trajectory=geo_traj) dyn.run(fmax=0.05) energy = sys.get_potential_energy() print "Energy: %f" % energy print "Completed %s" % file_name_py
try: from asap3 import EMT except ImportError: pass else: a = 3.6 b = a / 2 cu = Atoms('Cu', cell=[(0, b, b), (b, 0, b), (b, b, 0)], pbc=1) * (6, 6, 6) cu.set_calculator(EMT()) f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0]) opt = LBFGS(f) t = Trajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0) # HCP: from ase.build import hcp0001 cu = hcp0001('Cu', (1, 1, 2), a=a / sqrt(2)) cu.cell[1, 0] += 0.05 cu *= (6, 6, 3) cu.set_calculator(EMT()) print(cu.get_forces()) print(cu.get_stress()) f = UnitCellFilter(cu) opt = MDMin(f, dt=0.01) t = Trajectory('Cu-hcp.traj', 'w', cu) opt.attach(t) opt.run(0.2)