def test_water(): from ase.calculators.gaussian import Gaussian from ase.atoms import Atoms from ase.optimize.lbfgs import LBFGS from ase.io import read # First test to make sure Gaussian works calc = Gaussian(xc='pbe', chk='water.chk', label='water') calc.clean() water = Atoms('OHH', positions=[(0, 0, 0), (1, 0, 0), (0, 1, 0)], calculator=calc) opt = LBFGS(water) opt.run(fmax=0.05) forces = water.get_forces() energy = water.get_potential_energy() positions = water.get_positions() # Then test the IO routines water2 = read('water.log') forces2 = water2.get_forces() energy2 = water2.get_potential_energy() positions2 = water2.get_positions() # Compare distances since positions are different in standard orientation. dist = water.get_all_distances() dist2 = read('water.log', index=-1).get_all_distances() assert abs(energy - energy2) < 1e-7 assert abs(forces - forces2).max() < 1e-9 assert abs(positions - positions2).max() < 1e-6 assert abs(dist - dist2).max() < 1e-6
def __init__(self, calculator, params, max_iterations, geometry_rmsd_manager): self.params = params self.max_iterations = max_iterations self.calculator = calculator self.geometry_rmsd_manager = geometry_rmsd_manager self.ase_atoms = calculator.ase_atoms self.ase_atoms.set_positions(flex.vec3_double(self.calculator.x)) self.opt = LBFGS(atoms=self.ase_atoms) self.number_of_function_and_gradients_evaluations = 0 self.b_rmsd = self._get_bond_rmsd( sites_cart=flex.vec3_double(self.calculator.x)) print(" step: %3d bond rmsd: %8.6f" % (self.number_of_function_and_gradients_evaluations, self.b_rmsd)) self.run(nstep=max_iterations) # Syncing and cross-checking begin e = 1.e-4 assert approx_equal(self.ase_atoms.get_positions(), self.opt.atoms.get_positions(), e) self.calculator.update(x=self.opt.atoms.get_positions()) assert approx_equal(self.calculator.x, self.opt.atoms.get_positions(), e) if (params.refine.mode == "refine"): assert approx_equal( flex.vec3_double(self.calculator.x), self.calculator.fmodel.xray_structure.sites_cart(), e) else: assert approx_equal(flex.vec3_double(self.calculator.x), self.calculator.xray_structure.sites_cart(), e) b_rmsd = self._get_bond_rmsd( sites_cart=flex.vec3_double(self.calculator.x)) assert approx_equal(self.b_rmsd, b_rmsd, e)
def opt_emt_lbfgs(atoms): from ase.calculators.emt import EMT from ase.optimize.lbfgs import LBFGS tmpAtoms = atoms.copy() tmpAtoms.calc = EMT() geomOpt = LBFGS(tmpAtoms, maxstep=0.1, trajectory=None, logfile=None) geomOpt.run(fmax=0.01, steps=1000) return tmpAtoms
def optimize(self, name, atoms): mask = [t in self.constrain_tags for t in atoms.get_tags()] if mask: constrain = FixAtoms(mask=mask) atoms.constraints = [constrain] optimizer = LBFGS(atoms, trajectory=self.get_filename(name, ".traj"), logfile=None) optimizer.run(self.fmax)
def optimize(self, name, atoms): mask = [t in self.constrain_tags for t in atoms.get_tags()] if mask: constrain = FixAtoms(mask=mask) atoms.constraints = [constrain] optimizer = LBFGS(atoms, trajectory=self.get_filename(name, '.traj'), logfile=None) optimizer.run(self.fmax)
def opt_xtb_lbfgs(atoms): from xtb.ase.calculator import XTB from ase.optimize.lbfgs import LBFGS tmpAtoms = atoms.copy() tmpAtoms.calc = XTB(method='GFN1-xTB') geomOpt = LBFGS( tmpAtoms, maxstep=0.1, trajectory=None, # logfile=None ) geomOpt.run(fmax=0.05, steps=400) return tmpAtoms
class lbfgs_gradient(object): def __init__(self, atoms, restraints): self.restraints = restraints self.opt = LBFGS(atoms=atoms) def step(self): pos = self.opt.atoms.get_positions() sites_cart = flex.vec3_double(pos) e, g = self.restraints.target_and_gradients(sites_cart) forces = np.array(g) * -1 self.opt.step(forces) def write(self, file): write(file, self.opt.atoms) def run(self, nstep): for i in range(nstep): self.step()
def test_gfn2xtb_lbfgs(): """Perform geometry optimization with GFN2-xTB and L-BFGS""" thr = 1.0e-5 atoms = Atoms( symbols="NHCHC2H3OC2H3ONHCH3", positions=np.array([ [1.40704587284727, -1.26605342016611, -1.93713466561923], [1.85007200612454, -0.46824072777417, -1.50918242392545], [-0.03362432532150, -1.39269245193812, -1.74003582081606], [-0.56857009928108, -1.01764444489068, -2.61263467107342], [-0.44096297340282, -2.84337808903410, -1.48899734014499], [-0.47991761226058, -0.55230954385212, -0.55520222968656], [-1.51566045903090, -2.89187354810876, -1.32273881320610], [-0.18116520746778, -3.45187805987944, -2.34920431470368], [0.06989722340461, -3.23298998903001, -0.60872832703814], [-1.56668253918793, 0.00552120970194, -0.52884675001441], [1.99245341064342, -1.73097165236442, -3.08869239114486], [3.42884244212567, -1.30660069291348, -3.28712665743189], [3.87721962540768, -0.88843123009431, -2.38921453037869], [3.46548545761151, -0.56495308290988, -4.08311788302584], [4.00253374168514, -2.16970938132208, -3.61210068365649], [1.40187968630565, -2.43826111827818, -3.89034127398078], [0.40869198386066, -0.49101709352090, 0.47992424955574], [1.15591901335007, -1.16524842262351, 0.48740266650199], [0.00723492494701, 0.11692276177442, 1.73426297572793], [0.88822128447468, 0.28499001838229, 2.34645658013686], [-0.47231557768357, 1.06737634000561, 1.52286682546986], [-0.70199987915174, -0.50485938116399, 2.28058247845421], ]), ) calc = XTB(method="GFN2-xTB", solvent="water", accuracy=0.1) atoms.set_calculator(calc) opt = LBFGS(atoms) opt.run(fmax=0.1) assert approx(atoms.get_potential_energy(), thr) == -897.4533662470938 assert approx(np.linalg.norm(atoms.get_forces(), ord=2), thr) == 0.19359647527783497
def calculate(self, filename): """Run calculation and write results to file.""" self.log('Calculating', self.name, '...') config = self.atoms.copy() self.set_calculator(config, filename) traj = PickleTrajectory(filename, 'w', backup=False) cell = config.get_cell() self.energies = [] if self.fmax is not None: if (not config.constraints and not config.positions.any(axis=1).all()): # one atom is at (0,0,0) - fix it: mask = np.logical_not(config.positions.any(axis=1)) config.constraints = FixAtoms(mask=mask) dyn = LBFGS(config) dyn.attach(traj, 1, config) dyn.run(fmax=self.fmax) e = config.get_potential_energy() self.post_process(config) self.energies.append(e) elif not config.pbc.any() and len(config) == 2: # This is a dimer. self.bondlengths = [] d0 = config.get_distance(0, 1) for strain in self.strains: d = d0 * strain config.set_distance(0, 1, d) self.bondlengths.append(d) e = config.get_potential_energy() self.energies.append(e) self.post_process(config) traj.write(config) else: self.volumes = [] for strain in self.strains: config.set_cell(strain * cell, scale_atoms=True) self.volumes.append(config.get_volume()) e = config.get_potential_energy() self.energies.append(e) self.post_process(config) traj.write(config) return config
class minimizer_ase(object): def __init__(self, calculator, params, max_iterations, geometry_rmsd_manager): self.params = params self.max_iterations = max_iterations self.calculator = calculator self.geometry_rmsd_manager = geometry_rmsd_manager self.ase_atoms = calculator.ase_atoms self.ase_atoms.set_positions(flex.vec3_double(self.calculator.x)) self.opt = LBFGS(atoms=self.ase_atoms) self.number_of_function_and_gradients_evaluations = 0 self.b_rmsd = self._get_bond_rmsd( sites_cart=flex.vec3_double(self.calculator.x)) print(" step: %3d bond rmsd: %8.6f" % (self.number_of_function_and_gradients_evaluations, self.b_rmsd)) self.run(nstep=max_iterations) # Syncing and cross-checking begin e = 1.e-4 assert approx_equal(self.ase_atoms.get_positions(), self.opt.atoms.get_positions(), e) self.calculator.update(x=self.opt.atoms.get_positions()) assert approx_equal(self.calculator.x, self.opt.atoms.get_positions(), e) if (params.refine.mode == "refine"): assert approx_equal( flex.vec3_double(self.calculator.x), self.calculator.fmodel.xray_structure.sites_cart(), e) else: assert approx_equal(flex.vec3_double(self.calculator.x), self.calculator.xray_structure.sites_cart(), e) b_rmsd = self._get_bond_rmsd( sites_cart=flex.vec3_double(self.calculator.x)) assert approx_equal(self.b_rmsd, b_rmsd, e) # Syncing and cross-checking end def _get_bond_rmsd(self, sites_cart): b_mean = None if (self.geometry_rmsd_manager is not None): energies_sites = \ self.geometry_rmsd_manager.geometry.energies_sites( sites_cart = sites_cart.select(s), compute_gradients = False) b_mean = energies_sites.bond_deviations()[2] return b_mean def step(self): sites_cart = flex.vec3_double(self.opt.atoms.get_positions()) t, g = self.calculator.target_and_gradients(x=sites_cart) forces = numpy.array(g) * (-1) self.opt.step(forces) self.number_of_function_and_gradients_evaluations += 1 self.calculator.update(x=self.opt.atoms.get_positions()) # self.b_rmsd = self._get_bond_rmsd( sites_cart=flex.vec3_double(self.opt.atoms.get_positions())) print(" step: %3d bond rmsd: %8.6f" % (self.number_of_function_and_gradients_evaluations, self.b_rmsd)) if (self.params.refine.mode == "refine" and self.b_rmsd > self.params.refine.max_bond_rmsd and self.number_of_function_and_gradients_evaluations > 20): return False # return True def run(self, nstep): for i in range(nstep): v = self.step() if (not v): return
from ase.optimize.lbfgs import LBFGS from ase.constraints import StrainFilter, UnitCellFilter from ase.io import PickleTrajectory from ase.optimize.lbfgs import LBFGS 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 = PickleTrajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0) # HCP: from ase.lattice.surface 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 = PickleTrajectory('Cu-hcp.traj', 'w', cu)
from ase.optimize.lbfgs import LBFGS # First test to make sure Gaussian works calc = Gaussian(method='pbepbe', basis='sto-3g', force='force', nproc=1, chk='water.chk', label='water') calc.clean() water = Atoms('OHH', positions=[(0, 0, 0), (1, 0, 0), (0, 1, 0)], calculator=calc) opt = LBFGS(water) opt.run(fmax=0.05) forces = water.get_forces() energy = water.get_potential_energy() positions = water.get_positions() # Then test the IO routines from ase.io import read water2 = read('water.log') forces2 = water2.get_forces() energy2 = water2.get_potential_energy() positions2 = water2.get_positions() #compare distances since positions are different in standard orientation dist = water.get_all_distances() dist2 = read('water.log', quantity='structures')[-1].get_all_distances()
import sys from ase.io import read, write from ase.units import Hartree from ase.optimize.lbfgs import LBFGS from xtb.ase.calculator import XTB from ase.db import connect inpName = sys.argv[1] slab = read(inpName) slab.calc = XTB(method='GFN1-xTB', max_iterations=1000) relax = LBFGS( slab, maxstep=0.1, # logfile=None, # trajectory='ase.traj' ) relax.run(fmax=0.05) # get the final single point energy e = slab.get_potential_energy() print("Final energy: eV, Eh", e, e/Hartree) # write final geometry to file write('out-'+inpName, slab)
from pyscf import gto, scf, grad, mp import numpy as np import matplotlib.pyplot as plt # Read initial and final states: print(" -> read xyz") initial = io.read('react.xyz') final = io.read('prod.xyz') initial.set_calculator(PySCF_simple(initial, method='MP2', basis='6-31g*')) final.set_calculator(PySCF_simple(final, method='MP2', basis='6-31g*')) print(" -> opt react prod") dyn_react = LBFGS(initial) dyn_react.run(fmax=0.05) # dyn_prod = LBFGS(final) dyn_prod.run(fmax=0.05) # write output geometries of GO io.write("initial.xyz", initial) io.write("final.xyz", final) # Make a band consisting of N images: images = [initial] images += [initial.copy() for i in range(17)] images += [final] print(" -> set calculator")
from gpaw import GPAW, Mixer, FermiDirac tag = 'Ru001_Ru8' adsorbate_heights = {'H': 1.0, 'N': 1.108, 'O': 1.257} slab = hcp0001('Ru', size=(2, 2, 4), a=2.72, c=1.58*2.72, vacuum=7.0, orthogonal=True) slab.center(axis=2) if len(argv) > 1: adsorbate = argv[1] tag = adsorbate + tag add_adsorbate(slab, adsorbate, adsorbate_heights[adsorbate], 'hcp') slab.set_constraint(FixAtoms(mask=slab.get_tags() >= 3)) calc = GPAW(xc='PBE', h=0.2, mixer=Mixer(0.1, 5, weight=100.0), stencils=(3, 3), occupations=FermiDirac(width=0.1), kpts=[4, 4, 1], setups={'Ru': '8'}, txt=tag + '.txt') slab.set_calculator(calc) opt = LBFGS(slab, logfile=tag + '.log', trajectory=tag + '.traj') opt.run(fmax=0.05) calc.write(tag)
from ase.optimize.lbfgs import LBFGS from ase.constraints import StrainFilter, UnitCellFilter from ase.io import Trajectory from ase.optimize.lbfgs import LBFGS 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.lattice.surface 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)
adsorbate_heights = {'H': 1.0, 'N': 1.108, 'O': 1.257} slab = hcp0001('Ru', size=(2, 2, 4), a=2.72, c=1.58 * 2.72, vacuum=7.0, orthogonal=True) slab.center(axis=2) if len(argv) > 1: adsorbate = argv[1] tag = adsorbate + tag add_adsorbate(slab, adsorbate, adsorbate_heights[adsorbate], 'hcp') slab.set_constraint(FixAtoms(mask=slab.get_tags() >= 3)) calc = GPAW(xc='PBE', h=0.2, mixer=Mixer(0.1, 5, weight=100.0), stencils=(3, 3), occupations=FermiDirac(width=0.1), kpts=[4, 4, 1], setups={'Ru': '8'}, txt=tag + '.txt') slab.set_calculator(calc) opt = LBFGS(slab, logfile=tag + '.log', trajectory=tag + '.traj') opt.run(fmax=0.05) calc.write(tag)
def __init__(self, atoms, restraints): self.restraints = restraints self.opt = LBFGS(atoms=atoms)