def calc_stacking_fault(self, structure, elements): if structure != 'fcc': raise ValueError( "Cannot calculate stacking fault energy of structure " + structure) a = self.latticeconstants[(structure, elements)] atoms = fcc111(elements[0], (1, 2, 5), orthogonal=True, a=a) atoms.set_pbc(True) atoms = atoms.repeat(self.properties['sf_repeat']) atoms.set_calculator(self.get_calc()) dyn = QuasiNewton(atoms, logfile=None, trajectory=None) dyn.run(fmax=0.02) e_sf = atoms.get_potential_energy() n_sf = len(atoms) atoms = fcc111(elements[0], (1, 2, 6), orthogonal=True, a=a) atoms.set_pbc(True) atoms = atoms.repeat(self.properties['sf_repeat']) atoms.set_calculator(self.get_calc()) dyn = QuasiNewton(atoms, logfile=None, trajectory=None) dyn.run(fmax=0.02) e_bulk = atoms.get_potential_energy() n_bulk = len(atoms) layers = self.properties['sf_repeat'][2] uc = atoms.get_cell() area = uc[0, 0] * uc[1, 1] result = (e_sf - e_bulk * n_sf / n_bulk) / layers / area result /= 1e-3 * kJ * 1e-20 self.values[('stacking_fault', structure, elements)] = result
def runVaspASEOptimizer(fname_in, fname_out, vaspflags): fname_in = str(fname_in) fname_out = str(fname_out) #read the input atoms object atoms = read(str(fname_in)) #set ibrion=-1 and nsw=0 vaspflags['ibrion'] = -1 vaspflags['nsw'] = 0 #update vasprc file to set mode to "run" to ensure that this runs immediately Vasp.vasprc(mode='run') #set ppn>1 so that it knows to do an mpi job, the actual ppn will guessed by Vasp module Vasp.VASPRC['queue.ppn'] = 2 vaspflags['NPAR'] = 4 #set up the calculation and run calc = Vasp('./', atoms=atoms, **vaspflags) #calc.update() #calc.read_results() qn = QuasiNewton(atoms, logfile='relax.log', trajectory='relax.traj') qn.run(fmax=vaspflags['ediffg'] if 'ediffg' in vaspflags else 0.05) atoms.write(fname_out) #Write a text file with the energy with open('energy.out', 'w') as fhandle: fhandle.write(str(atoms.get_potential_energy())) return str(atoms), open( 'relax.traj', 'r').read().encode('hex'), atoms.get_potential_energy()
def test_md(factory): # XXX ugly hack ver = factory.factory.version() if LooseVersion(ver) < '3.8': pytest.skip('No stress tensor until openmx 3.8+') bud = Atoms('CH4', np.array([[0.000000, 0.000000, 0.100000], [0.682793, 0.682793, 0.682793], [-0.682793, -0.682793, 0.68279], [-0.682793, 0.682793, -0.682793], [0.682793, -0.682793, -0.682793]]), cell=[10, 10, 10]) calc = factory.calc( label='ch4', xc='GGA', energy_cutoff=300 * Ry, convergence=1e-4 * Ha, # Use 'C_PBE19' and 'H_PBE19' for version 3.9 definition_of_atomic_species=[['C', 'C5.0-s1p1', 'C_PBE13'], ['H', 'H5.0-s1', 'H_PBE13']], kpts=(1, 1, 1), eigensolver='Band') bud.calc = calc with Trajectory('example.traj', 'w', bud) as traj: ucf = UnitCellFilter(bud, mask=[True, True, False, False, False, False]) dyn = QuasiNewton(ucf) dyn.attach(traj.write) dyn.run(fmax=0.1) bud.get_potential_energy()
def main(): CO = molecule("CO") fname = "data/CO.traj" calc = GPAW(h=0.2, txt="data/CO.txt") CO.set_cell([6, 6, 6]) CO.center() if (os.path.isfile(fname)): traj = Trajectory(fname) CO = traj[-1] else: # Optimize the CO structure opt = QuasiNewton(CO, trajectory=fname) opt.run(fmax=0.05) fname = "data/CO.gpw" CO.set_calculator(calc) CO.get_potential_energy() calc.write(fname) for band in range(calc.get_number_of_bands()): wf = calc.get_pseudo_wave_function(band=band) with h5.File("data/CO_%d.cmap" % (band)) as hf: hf.create_dataset("wf", data=wf)
def optimize(self, calculator='siesta'): from ase.optimize import QuasiNewton if calculator == 'siesta': calc = Siesta( label=self.label, xc='CA', mesh_cutoff=400 * eV, energy_shift=0.03 * eV, basis_set='SZ', fdf_arguments=self.extra_fdf, ) elif calculator == 'dftb': extras = {} for S in set(self.mol.get_chemical_symbols()): key = 'Hamiltonian_MaxAngularMomentum_' + S if S == 'H': value = '"s"' else: value = '"p"' extras[key] = value calc = Dftb(label=self.label, atoms=self.mol, **extras) tempdir = "." + self.label try: os.mkdir(tempdir) except: pass os.chdir(tempdir) self.mol.set_calculator(calc) dyn = QuasiNewton(self.mol, trajectory=self.label + '.traj') dyn.run(fmax=0.5) os.chdir('../')
def _main(): si = make_displaced_Si_cell() # Set up GPAW calculator for the ground-state charge density. # This will be used repeatedly as the structure is moved toward the # equilibrium structure. calc = GPAW( mode=PW(200), # plane-wave basis, 200 eV wavefunction cutoff energy # PBE exchange-correlation functional xc='PBE', # Sample the Brillouin zone with 8 k-points in each reciprocal lattice direction kpts=(8, 8, 8), # Smear step functions appearing in Brillouin zone integrals using Fermi-Dirac # distribution at temperature k_B T = 0.01 eV. occupations=FermiDirac(0.01), # Start calculation using random wavefunctions. # We have a physically-reasonable initial value for the charge density based # on the atomic positions. # The Hamiltonian is diagonalized iteratively, so we also need an initial guess for # the wavefunctions. Random starting wavefunctions generally work well. random=True, # Set the log file for the ground-state DFT calculation. txt="Si_relax.txt") si.calc = calc opt = QuasiNewton( si, # Set the (non-plaintext) log file for the structural optimization steps. trajectory="Si.traj") # Relax structure until all forces are less than 0.05 eV/Angstrom. opt.run(fmax=0.05)
def generate_data(count, filename, temp, hook, cons_t=False): """Generates test or training data with a simple MD simulation.""" traj = ase.io.Trajectory(filename, "w") slab = fcc100("Cu", size=(3, 3, 3)) ads = molecule("CO") add_adsorbate(slab, ads, 5, offset=(1, 1)) cons = FixAtoms(indices=[ atom.index for atom in slab if (atom.tag == 2 or atom.tag == 3) ]) if hook: cons2 = Hookean(a1=28, a2=27, rt=1.58, k=10.0) slab.set_constraint([cons, cons2]) else: slab.set_constraint(cons) slab.center(vacuum=13., axis=2) slab.set_pbc(True) slab.wrap(pbc=[True] * 3) slab.set_calculator(EMT()) slab.get_forces() dyn = QuasiNewton(slab) dyn.run(fmax=0.05) traj.write(slab) if cons_t is True: dyn = Langevin(slab, 1.0 * units.fs, temp * units.kB, 0.002) else: dyn = VelocityVerlet(slab, dt=1.0 * units.fs) for step in range(count): dyn.run(20) traj.write(slab)
def test_example(): from ase import Atoms from ase.constraints import FixAtoms from ase.io import Trajectory from ase.optimize import QuasiNewton from ase.calculators.morse import MorsePotential atoms = Atoms('H7', positions=[(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0), (0.5, 0.5, 1)], constraint=[FixAtoms(range(6))], calculator=MorsePotential()) traj = Trajectory('H.traj', 'w', atoms) dyn = QuasiNewton(atoms, maxstep=0.2) dyn.attach(traj.write) dyn.run(fmax=0.01, steps=100) print(atoms) del atoms[-1] print(atoms) del atoms[5] print(atoms) assert len(atoms.constraints[0].index) == 5
def test_dftb_relax_bulk(): import os from ase.test import require from ase.test.testsuite import datafiles_directory from ase.build import bulk from ase.calculators.dftb import Dftb from ase.optimize import QuasiNewton from ase.constraints import ExpCellFilter require('dftb') os.environ['DFTB_PREFIX'] = datafiles_directory calc = Dftb(label='dftb', kpts=(3,3,3), Hamiltonian_SCC='Yes') atoms = bulk('Si') atoms.set_calculator(calc) ecf = ExpCellFilter(atoms) dyn = QuasiNewton(ecf) dyn.run(fmax=0.01) e = atoms.get_potential_energy() assert abs(e - -73.150819) < 1., e
def evaluate(self, imember): entry = self.population.get_entry(imember) pcm_structure = pychemia.Structure.from_dict(entry['structure']) ase_structure = pychemia.external.ase.pychemia2ase(pcm_structure) ase_structure.set_calculator(LennardJones()) dyn = QuasiNewton(ase_structure) dyn.run() ase_structure.set_constraint( FixAtoms(mask=[True for atom in ase_structure])) ucf = UnitCellFilter(ase_structure) qn = QuasiNewton(ucf) qn.run() new_structure = pychemia.external.ase.ase2pychemia(ase_structure) energy = ase_structure.get_potential_energy() forces = ase_structure.get_forces() stress = ase_structure.get_stress() new_properties = { 'energy': float(energy), 'forces': generic_serializer(forces), 'stress': generic_serializer(stress) } self.population.db.update(imember, structure=new_structure, properties=new_properties)
def test_NaCl_minimize(): from ase.calculators.lammpsrun import LAMMPS from ase.spacegroup import crystal from ase.data import atomic_numbers, atomic_masses from ase.optimize import QuasiNewton from ase.constraints import UnitCellFilter from numpy.testing import assert_allclose a = 6.15 n = 4 nacl = crystal(['Na', 'Cl'], [(0, 0, 0), (0.5, 0.5, 0.5)], spacegroup=225, cellpar=[a, a, a, 90, 90, 90]).repeat((n, n, n)) # Buckingham parameters from # https://physics.stackexchange.com/questions/250018 pair_style = 'buck/coul/long 12.0' pair_coeff = ['1 1 3796.9 0.2603 124.90'] pair_coeff += ['2 2 1227.2 0.3214 124.90'] pair_coeff += ['1 2 4117.9 0.3048 0.0'] masses = [ '1 {}'.format(atomic_masses[atomic_numbers['Na']]), '2 {}'.format(atomic_masses[atomic_numbers['Cl']]) ] with LAMMPS( specorder=['Na', 'Cl'], pair_style=pair_style, pair_coeff=pair_coeff, masses=masses, atom_style='charge', kspace_style='pppm 1.0e-5', keep_tmp_files=True, ) as calc: for a in nacl: if a.symbol == 'Na': a.charge = +1. else: a.charge = -1. nacl.set_calculator(calc) assert_allclose(nacl.get_potential_energy(), -1896.216737561538, atol=1e-4, rtol=1e-4) nacl.get_potential_energy() ucf = UnitCellFilter(nacl) dyn = QuasiNewton(ucf, force_consistent=False) dyn.run(fmax=1.0E-2) assert_allclose(nacl.get_potential_energy(), -1897.208861729178, atol=1e-4, rtol=1e-4)
def test_Ag_Cu100(): from math import sqrt from ase import Atom, Atoms from ase.neb import NEB from ase.constraints import FixAtoms from ase.vibrations import Vibrations from ase.calculators.emt import EMT from ase.optimize import QuasiNewton, BFGS # Distance between Cu atoms on a (100) surface: d = 3.6 / sqrt(2) initial = Atoms('Cu', positions=[(0, 0, 0)], cell=(d, d, 1.0), pbc=(True, True, False)) initial *= (2, 2, 1) # 2x2 (100) surface-cell # Approximate height of Ag atom on Cu(100) surfece: h0 = 2.0 initial += Atom('Ag', (d / 2, d / 2, h0)) # Make band: images = [initial.copy() for i in range(6)] neb = NEB(images, climb=True) # Set constraints and calculator: constraint = FixAtoms(range(len(initial) - 1)) for image in images: image.calc = EMT() image.set_constraint(constraint) # Displace last image: images[-1].positions[-1] += (d, 0, 0) # Relax height of Ag atom for initial and final states: dyn1 = QuasiNewton(images[0]) dyn1.run(fmax=0.01) dyn2 = QuasiNewton(images[-1]) dyn2.run(fmax=0.01) # Interpolate positions between initial and final states: neb.interpolate() for image in images: print(image.positions[-1], image.get_potential_energy()) dyn = BFGS(neb, trajectory='mep.traj') dyn.run(fmax=0.05) for image in images: print(image.positions[-1], image.get_potential_energy()) a = images[0] vib = Vibrations(a, [4]) vib.run() print(vib.get_frequencies()) vib.summary() print(vib.get_mode(-1)) vib.write_mode(-1, nimages=20)
def test_turbomole_h3o2m(): # http://jcp.aip.org/resource/1/jcpsa6/v97/i10/p7507_s1 doo = 2.74 doht = 0.957 doh = 0.977 angle = radians(104.5) initial = Atoms('HOHOH', positions=[(-sin(angle) * doht, 0., cos(angle) * doht), (0., 0., 0.), (0., 0., doh), (0., 0., doo), (sin(angle) * doht, 0., doo - cos(angle) * doht) ]) if 0: view(initial) final = Atoms('HOHOH', positions=[(-sin(angle) * doht, 0., cos(angle) * doht), (0., 0., 0.), (0., 0., doo - doh), (0., 0., doo), (sin(angle) * doht, 0., doo - cos(angle) * doht)]) if 0: view(final) # Make band: images = [initial.copy()] for i in range(3): images.append(initial.copy()) images.append(final.copy()) neb = NEB(images, climb=True) # Write all commands for the define command in a string define_str = ('\n\na coord\n\n*\nno\nb all 3-21g ' 'hondo\n*\neht\n\n-1\nno\ns\n*\n\ndft\non\nfunc ' 'pwlda\n\n\nscf\niter\n300\n\n*') # Set constraints and calculator: constraint = FixAtoms(indices=[1, 3]) # fix OO BUG No.1: fixes atom 0 and 1 # constraint = FixAtoms(mask=[0,1,0,1,0]) # fix OO #Works without patch for image in images: image.calc = Turbomole(define_str=define_str) image.set_constraint(constraint) # Relax initial and final states: if 1: dyn1 = QuasiNewton(images[0]) dyn1.run(fmax=0.10) dyn2 = QuasiNewton(images[-1]) dyn2.run(fmax=0.10) # Interpolate positions between initial and final states: neb.interpolate() if 1: for image in images: print(image.get_distance(1, 2), image.get_potential_energy()) dyn = BFGS(neb, trajectory='turbomole_h3o2m.traj') dyn.run(fmax=0.10) for image in images: print(image.get_distance(1, 2), image.get_potential_energy())
def emtOptimize(): 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 test_h3o2m(): # http://jcp.aip.org/resource/1/jcpsa6/v97/i10/p7507_s1 doo = 2.74 doht = 0.957 doh = 0.977 angle = radians(104.5) initial = Atoms('HOHOH', positions=[(-sin(angle) * doht, 0, cos(angle) * doht), (0., 0., 0.), (0., 0., doh), (0., 0., doo), (sin(angle) * doht, 0., doo - cos(angle) * doht) ]) if 0: view(initial) final = Atoms('HOHOH', positions=[(-sin(angle) * doht, 0., cos(angle) * doht), (0., 0., 0.), (0., 0., doo - doh), (0., 0., doo), (sin(angle) * doht, 0., doo - cos(angle) * doht)]) if 0: view(final) # Make band: images = [initial.copy()] for i in range(3): images.append(initial.copy()) images.append(final.copy()) neb = NEB(images, climb=True) def calculator(): return NWChem(task='gradient', theory='scf', charge=-1) # Set constraints and calculator: constraint = FixAtoms(indices=[1, 3]) # fix OO for image in images: image.calc = calculator() image.set_constraint(constraint) # Relax initial and final states: if 1: dyn1 = QuasiNewton(images[0]) dyn1.run(fmax=0.10) dyn2 = QuasiNewton(images[-1]) dyn2.run(fmax=0.10) # Interpolate positions between initial and final states: neb.interpolate() if 1: for image in images: print(image.get_distance(1, 2), image.get_potential_energy()) dyn = BFGS(neb, trajectory='nwchem_h3o2m.traj') dyn.run( fmax=0.10) # use better basis (e.g. aug-cc-pvdz) for NEB to converge for image in images: print(image.get_distance(1, 2), image.get_potential_energy())
def optimize(self): from ase.optimize import QuasiNewton self.add_calculator() tempdir = "."+self.label try: os.mkdir(tempdir) except: pass os.chdir(tempdir) dyn = QuasiNewton(self, trajectory=self.label+'.traj') dyn.run(fmax=0.5) os.chdir('../')
def main(): molecule, calc = gp.restart("H2.gpw", txt="H2-relaxed.txt") print("Getting potential energy") e2 = molecule.get_potential_energy() d0 = molecule.get_distance(0, 1) # Find the minimum energy by Quasi-Newton relax = QuasiNewton(molecule, logfile="qn.log") relax.run(fmax=0.05) d1 = molecule.get_distance(0, 1) print("Original bondlength: %.2f" % (d0)) print("Optimized bondlength: %.2f" % (d1))
def traj(tmpdir_factory): slab = fcc100('Al', size=(2, 2, 3)) add_adsorbate(slab, 'Au', 1.7, 'hollow') slab.center(axis=2, vacuum=4.0) mask = [atom.tag > 1 for atom in slab] fixlayers = FixAtoms(mask=mask) plane = FixedPlane(-1, (1, 0, 0)) slab.set_constraint([fixlayers, plane]) slab.set_calculator(EMT()) fn = tmpdir_factory.mktemp("data").join("AlAu.traj") # see /tmp/pytest-xx qn = QuasiNewton(slab, trajectory=str(fn)) qn.run(fmax=0.02) return fn
def test_dftb_relax_bulk(dftb_factory): calc = dftb_factory.calc(label='dftb', kpts=(3, 3, 3), Hamiltonian_SCC='Yes') atoms = bulk('Si') atoms.calc = calc ecf = ExpCellFilter(atoms) dyn = QuasiNewton(ecf) dyn.run(fmax=0.01) e = atoms.get_potential_energy() assert abs(e - -73.150819) < 1., e
def ase_vol_relax(): Al = bulk('Al', 'fcc', a=4.5, cubic=True) calc = Vasp(xc='LDA') Al.set_calculator(calc) from ase.constraints import StrainFilter sf = StrainFilter(Al) qn = QuasiNewton(sf, logfile='relaxation.log') qn.run(fmax=0.1, steps=5) print 'Stress:\n', calc.read_stress() print 'Al post ASE volume relaxation\n', calc.get_atoms().get_cell() return Al
def get_atoms(): # 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] slab.set_constraint(FixAtoms(mask=mask)) # Use EMT potential: slab.set_calculator(EMT()) # Initial state: qn = QuasiNewton(slab, logfile=None) qn.run(fmax=0.05) initial = slab.copy() # Final state: slab[-1].x += slab.get_cell()[0, 0] / 2 qn = QuasiNewton(slab, logfile=None) qn.run(fmax=0.05) final = slab.copy() # Setup a NEB calculation constraint = FixAtoms(mask=[atom.tag > 1 for atom in initial]) images = [initial] for i in range(3): image = initial.copy() image.set_constraint(constraint) images.append(image) images.append(final) neb = NEB(images, parallel=mpi.parallel) neb.interpolate() def set_calculator(calc): i = 0 for image in neb.images[1:-1]: if not mpi.parallel or mpi.rank // (mpi.size // 3) == i: image.set_calculator(calc) i += 1 neb.set_calculator = set_calculator return neb
def test_md(): import numpy as np import unittest from ase.units import Ry, Ha from ase.calculators.openmx import OpenMX from ase.io.trajectory import Trajectory from ase.optimize import QuasiNewton from ase.constraints import UnitCellFilter from ase.calculators.calculator import PropertyNotImplementedError from ase import Atoms """ Only OpenMX 3.8 or higher version pass this test""" bud = Atoms('CH4', np.array([ [0.000000, 0.000000, 0.100000], [0.682793, 0.682793, 0.682793], [-0.682793, -0.682793, 0.68279], [-0.682793, 0.682793, -0.682793], [0.682793, -0.682793, -0.682793]]), cell=[10, 10, 10]) calc = OpenMX( label='ch4', xc='GGA', energy_cutoff=300 * Ry, convergence=1e-4 * Ha, # Use 'C_PBE19' and 'H_PBE19' for version 3.9 definition_of_atomic_species=[['C', 'C5.0-s1p1', 'C_PBE13'], ['H', 'H5.0-s1', 'H_PBE13']], kpts=(4, 4, 4), eigensolver='Band' ) bud.set_calculator(calc) try: bud.get_stress() except PropertyNotImplementedError as err: raise unittest.SkipTest(err) traj = Trajectory('example.traj', 'w', bud) ucf = UnitCellFilter(bud, mask=[True, True, False, False, False, False]) dyn = QuasiNewton(ucf) dyn.attach(traj.write) dyn.run(fmax=0.1) bud.get_potential_energy() # XXX maybe assert something? traj.close()
def optimize(self, fmax=1.0e-2, steps=1000): """ Optimize a molecular geometry using the Quasi Newton optimizer in ase (BFGS + line search) Args: fmax (float): Maximum residual force change (default 1.e-2) steps (int): Maximum number of steps (default 1000) """ name = 'optimization' optimize_file = os.path.join(self.working_dir, name) optimizer = QuasiNewton(self.molecule, trajectory='%s.traj' % optimize_file, restart='%s.pkl' % optimize_file) optimizer.run(fmax, steps) # Save final geometry in xyz format self.save_molecule(name)
def traj(tmp_path_factory): slab = fcc100('Al', size=(2, 2, 3)) add_adsorbate(slab, 'Au', 1.7, 'hollow') slab.center(axis=2, vacuum=4.0) mask = [atom.tag > 1 for atom in slab] fixlayers = FixAtoms(mask=mask) plane = FixedPlane(-1, (1, 0, 0)) slab.set_constraint([fixlayers, plane]) slab.calc = EMT() temp_path = tmp_path_factory.mktemp("data") trajectory = temp_path / 'AlAu.traj' qn = QuasiNewton(slab, trajectory=str(trajectory)) qn.run(fmax=0.02) return str(trajectory)
def test_filter(): """Test that the filter and trajectories are playing well together.""" from ase.build import molecule from ase.constraints import Filter from ase.optimize import QuasiNewton from ase.calculators.emt import EMT atoms = molecule('CO2') atoms.set_calculator(EMT()) filter = Filter(atoms, indices=[1, 2]) opt = QuasiNewton(filter, trajectory='filter-test.traj', logfile='filter-test.log') opt.run()
def optimizeH2O(dbname): database = db.connect(dbname) sqdb = sq.connect(dbname) cur = sqdb.cursor() cur.execute( "SELECT _rowid_,CellSize,XC,JobType,AtomID FROM InputParams WHERE STATUS=?", ("RUN", )) jobs = cur.fetchall() sqdb.close() for job in jobs: jobtype = job[3] atomID = int(job[4]) if (atomID >= 0): print("Using Atoms object with ID %d" % (atomID)) system = database.get_atoms(selection=atomID) else: system = Atoms(["H", "H", "O"], positions=[[3.0, 3.8, 2.4], [3, 2.23, 2.4], [3, 3, 3]]) size = job[1] system.set_cell([size, size, size]) system.center() xc = job[2] calc = gp.GPAW(xc=xc) system.set_calculator(calc) if (jobtype == "Optimize"): opt = QuasiNewton(system, trajectory="H2O.gpw.traj") opt.run(fmax=0.05) elif (jobtype == "GS"): e1 = system.get_potential_energy() lastID = database.write(system) row = int(job[0]) # Update ID print("Updating entry in database") sqdb = sq.connect(dbname) cur = sqdb.cursor() cur.execute("UPDATE InputParams SET ID=?, STATUS=? WHERE _rowid_=?", (lastID, "FINISHED", row)) sqdb.commit() sqdb.close() print("Database updated")
def test_autoneb(asap3): EMT = asap3.EMT fmax = 0.02 # Pt atom adsorbed in a hollow site: slab = fcc211('Pt', size=(3, 2, 2), vacuum=4.0) add_adsorbate(slab, 'Pt', 0.5, (-0.1, 2.7)) # Fix second and third layers: slab.set_constraint(FixAtoms(range(6, 12))) # Use EMT potential: slab.calc = EMT() # Initial state: qn = QuasiNewton(slab, trajectory='neb000.traj') qn.run(fmax=fmax) # Final state: slab[-1].x += slab.get_cell()[0, 0] slab[-1].y += 2.8 qn = QuasiNewton(slab, trajectory='neb001.traj') qn.run(fmax=fmax) # Stops PermissionError on Win32 for access to # the traj file that remains open. del qn def attach_calculators(images): for i in range(len(images)): images[i].calc = EMT() autoneb = AutoNEB(attach_calculators, prefix='neb', optimizer='BFGS', n_simul=3, n_max=7, fmax=fmax, k=0.5, parallel=False, maxsteps=[50, 1000]) autoneb.run() nebtools = NEBTools(autoneb.all_images) assert abs(nebtools.get_barrier()[0] - 0.937) < 1e-3
def test_example(testdir): atoms = Atoms('H7', positions=[(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0), (0.5, 0.5, 1)], constraint=[FixAtoms(range(6))], calculator=MorsePotential()) with Trajectory('H.traj', 'w', atoms) as traj: dyn = QuasiNewton(atoms, maxstep=0.2) dyn.attach(traj.write) dyn.run(fmax=0.01, steps=100) print(atoms) del atoms[-1] print(atoms) del atoms[5] print(atoms) assert len(atoms.constraints[0].index) == 5
def test_H2O_aims(): water = Atoms('HOH', [(1, 0, 0), (0, 0, 0), (0, 1, 0)]) water_cube = AimsCube(points=(29, 29, 29), plots=('total_density', 'delta_density', 'eigenstate 5', 'eigenstate 6')) calc = Aims(xc='PBE', output=['dipole'], sc_accuracy_etot=1e-6, sc_accuracy_eev=1e-3, sc_accuracy_rho=1e-6, sc_accuracy_forces=1e-4, cubes=water_cube) water.calc = calc dynamics = QuasiNewton(water, trajectory='square_water.traj') dynamics.run(fmax=0.01)
def test_H2O_aims(factory): water = Atoms('HOH', [(1, 0, 0), (0, 0, 0), (0, 1, 0)]) water_cube = AimsCube(points=(29, 29, 29), plots=('total_density', 'delta_density', 'eigenstate 5', 'eigenstate 6')) calc = factory.calc(xc='LDA', output=['dipole'], sc_accuracy_etot=1e-2, sc_accuracy_eev=1e-1, sc_accuracy_rho=1e-2, sc_accuracy_forces=1e-1, cubes=water_cube) water.calc = calc dynamics = QuasiNewton(water) dynamics.run(fmax=0.2)
def aual100(site, height, calc=None): slab = fcc100('Al', size=(2, 2, 1)) add_adsorbate(slab, 'Au', height, site) slab.center(axis=2, vacuum=3.0) mask = [atom.symbol == 'Al' for atom in slab] fixlayer = FixAtoms(mask=mask) slab.set_constraint(fixlayer) if calc is None: calc = GPAW(h=0.25, kpts=(2, 2, 1), xc='PBE', txt=site + '.txt') slab.set_calculator(calc) qn = QuasiNewton(slab, trajectory=site + '.traj') qn.run(fmax=0.05) if isinstance(calc, GPAW): calc.write(site + '.gpw') return slab.get_potential_energy()
def evaluate(self, imember): entry = self.population.get_entry(imember) pcm_structure = pychemia.Structure.from_dict(entry['structure']) ase_structure = pychemia.external.ase.pychemia2ase(pcm_structure) ase_structure.set_calculator(LennardJones()) dyn = QuasiNewton(ase_structure) dyn.run() ase_structure.set_constraint(FixAtoms(mask=[True for atom in ase_structure])) ucf = UnitCellFilter(ase_structure) qn = QuasiNewton(ucf) qn.run() new_structure = pychemia.external.ase.ase2pychemia(ase_structure) energy = ase_structure.get_potential_energy() forces = ase_structure.get_forces() stress = ase_structure.get_stress() new_properties = {'energy': float(energy), 'forces': generic_serializer(forces), 'stress': generic_serializer(stress)} self.population.db.update(imember, structure=new_structure, properties=new_properties)
i = 0 array = [] while i < 6: if atoms.positions[i][0] <= -2.0: array.append(i) i += 1 else: i += 1 c = FixAtoms(indices = array) atoms.set_constraint(c) # relax with Quasi Newtonian qn = QuasiNewton(atoms, trajectory='qn.traj') qn.run(fmax=0.001) write('qn.final.xyz', atoms) # Set the momenta corresponding to T=300K MaxwellBoltzmannDistribution(atoms, 300*units.kB) print 'Removing linear momentum and angular momentum' Stationary(atoms) # zero linear momentum ZeroRotation(atoms) # zero angular momentum # We want to run MD using the VelocityVerlet algorithm. dyn = VelocityVerlet(atoms, 0.1*units.fs, trajectory='moldyn4.traj') # save trajectory. #Function to print the potential, kinetic and total energy. def printenergy(a=atoms): #store a reference to atoms in the definition. epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a)
atoms = Atoms('H7', positions=[(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0), (0.5, 0.5, 1)], constraint=[FixAtoms(range(6))], calculator=MorsePotential()) traj = Trajectory('H.traj', 'w', atoms) dyn = QuasiNewton(atoms, maxstep=0.2) dyn.attach(traj.write) dyn.run(fmax=0.01, steps=100) print(atoms) del atoms[-1] print(atoms) del atoms[5] print(atoms) assert len(atoms.constraints[0].index) == 5 fmax = 0.05 nimages = 3 print([a.get_potential_energy() for a in Trajectory('H.traj')])
#!/usr/bin/env python # import os from ase import Atoms from ase.calculators.dftb import Dftb from ase.optimize import QuasiNewton from ase.io import write, read from ase.structure import molecule test = molecule('H2O') test.set_calculator(Dftb(label='h2o',atoms=test, run_manyDftb_steps = True, Driver_='ConjugateGradient', Driver_MaxForceComponent='1E-4', Driver_MaxSteps=1000, Hamiltonian_MaxAngularMomentum_ = '', Hamiltonian_MaxAngularMomentum_O = '"p"', Hamiltonian_MaxAngularMomentum_H = '"s"', )) dyn = QuasiNewton(test, trajectory='test.traj') dyn.run(fmax=100, steps=0) test = read('geo_end.gen') write('test.final.xyz', test)
# see the module for the required format of reactions definition from ase.test.cmr.reactions import reactions # assure that all reactions define a reaction_id for r in reactions: assert r[-1][0] == 'reaction_id' optimize = True calculator = EMT() # find names of compounds # (in one of the most obscure ways - python list flattening) compounds = [c[0] for c in sum([r[:-1] for r in reactions], [])] # unique compounds = list(set(compounds)) for formula in compounds: m = molecule(formula) m.set_calculator(calculator) if optimize: dyn = QuasiNewton(m, logfile=('%s.log' % formula), trajectory=('%s.traj' % formula), ) dyn.run() else: e = m.get_potential_energy() write(filename=('%s.traj' % formula), images=m, format='traj')
else: from ase.calculators.emt import EMT size = 2 # Set up a nanoparticle atoms = FaceCenteredCubic('Cu', surfaces=[[1, 0, 0], [1, 1, 0], [1, 1, 1]], layers=(size, size, size), vacuum=4) # Describe the interatomic interactions with the Effective Medium Theory atoms.set_calculator(EMT()) # Do a quick relaxation of the cluster qn = QuasiNewton(atoms) qn.run(0.001, 10) # Set the momenta corresponding to T=1200K MaxwellBoltzmannDistribution(atoms, 1200 * units.kB) Stationary(atoms) # zero linear momentum ZeroRotation(atoms) # zero angular momentum # We want to run MD using the VelocityVerlet algorithm. # Save trajectory: dyn = VelocityVerlet(atoms, 5 * units.fs, trajectory='moldyn4.traj') def printenergy(a=atoms): # store a reference to atoms in the definition. """Function to print the potential, kinetic and total energy.""" epot = a.get_potential_energy() / len(a)
def add_displacement_energy(self, displacement): """Add the groundstate energy for a displacements along the translational path, and adds it to an_mode['displacement_energies']. Args: displacement (float): How much to follow translational path. """ # Will otherwise do a groundstate calculation at initial positions if displacement: if displacement != self.an_mode['transition_path_length']: self.atoms.set_positions( self.get_translation_positions(displacement)) # Do 1D optimization fix_environment = FixAtoms(mask=[ i not in self.an_mode['indices'] for i in range(len(self.atoms))]) axis_relax = self.an_mode.get('relax_axis') if axis_relax: if self.use_forces: warnings.warn(' '.join([ "relax along axis and force_consistent", "should only be used with ase releases after", "Jan 2017. See", "https://gitlab.com/ase/ase/merge_requests/354" ])) c = [] for i in self.an_mode['indices']: c.append(FixedLine(i, axis_relax)) # Fixing everything that is not the vibrating part c.append(fix_environment) self.atoms.set_constraint(c) # Optimization dyn = QuasiNewton(self.atoms, logfile='/dev/null') dyn.run(fmax=self.settings.get('fmax', 0.05)) self.atoms.set_constraint(fix_environment) if not self.an_mode.get('displacement_energies'): self.an_mode['displacement_energies'] = list() if self.use_forces: e = self.atoms.get_potential_energy(force_consistent=True) # For the forces, we need the projection of the forces # on the normal mode of the rotation at the current angle v_force = self.atoms.get_forces()[ self.an_mode['indices']].reshape(-1) f = float(np.dot( v_force, self.an_mode['mode_tangent'])) if not self.an_mode.get('displacement_forces'): self.an_mode['displacement_forces'] = [f] else: self.an_mode['displacement_forces'].append(f) else: e = self.atoms.get_potential_energy() if self.traj is not None: self.traj.write(self.atoms) self.an_mode['displacement_energies'].append(e) # adding to trajectory: if self.traj is not None: self.traj.write(self.atoms) self.atoms.set_positions(self.groundstate_positions) # save to backup file: if self.an_filename: self.save_to_backup()
# Initial state: # 2x2-Al(001) surface with 1 layer and an # Au atom adsorbed in a hollow site: slab = fcc100('Al', size=(2, 2, 2)) slab.center(axis=2, vacuum=3.0) add_adsorbate(slab, 'Au', 1.6, 'hollow') # Make sure the structure is correct: view(slab) # Fix the Al atoms: mask = [atom.symbol == 'Al' for atom in slab] print(mask) fixlayer = FixAtoms(mask=mask) slab.set_constraint(fixlayer) # Use GPAW: calc = GPAW(mode=PW(200), kpts=(2, 2, 1), xc='PBE', txt='hollow.txt') slab.set_calculator(calc) qn = QuasiNewton(slab, trajectory='hollow.traj') # Find optimal height. The stopping criterion is: the force on the # Au atom should be less than 0.05 eV/Ang qn.run(fmax=0.05) calc.write('hollow.gpw') # Write gpw output after the minimization print('energy:', slab.get_potential_energy()) print('height:', slab.positions[-1, 2] - slab.positions[0, 2])
from ase.data.molecules import molecule from ase.optimize import QuasiNewton from gpaw import GPAW for name in ['H2', 'N2', 'O2', 'NO']: mol = molecule(name) mol.center(vacuum=5.0) if name == 'NO': mol.translate((0, 0.1, 0)) calc = GPAW(xc='PBE', h=0.2, stencils=(3, 3), txt=name + '.txt') mol.set_calculator(calc) opt = QuasiNewton(mol, logfile=name + '.log', trajectory=name + '.traj') opt.run(fmax=0.05) calc.write(name)
from ase import Atoms from ase.visualize import view from ase.calculators.aims import Aims, AimsCube from ase.optimize import QuasiNewton water = Atoms('HOH', [(1,0,0), (0,0,0), (0,1,0)]) water_cube = AimsCube(points=(29,29,29), plots=('total_density','delta_density', 'eigenstate 5','eigenstate 6')) calc=Aims(xc='pbe', sc_accuracy_etot=1e-6, sc_accuracy_eev=1e-3, sc_accuracy_rho=1e-6, sc_accuracy_forces=1e-4, species_dir='/home/hanke/codes/fhi-aims/fhi-aims.workshop/species_defaults/light/', run_command='aims.workshop.serial.x', cubes=water_cube) water.set_calculator(calc) dynamics = QuasiNewton(water,trajectory='square_water.traj') dynamics.run(fmax=0.01) view(water)
atoms.center(vacuum = 10.0) atoms.set_cell([[10,0,0],[0,10.1,0],[0,0,10.2]]) calc = espresso(pw = 500., dw = 5000., nbands = -10, kpts=(1, 1, 1), xc = 'BEEF', outdir='outdir', psppath = "/scratch/users/colinfd/psp/gbrv", sigma = 10e-4) atoms.set_calculator(calc) dyn = QuasiNewton(atoms,logfile='out.log',trajectory='out.traj') dyn.run(fmax=0.01) electronicenergy = atoms.get_potential_energy() vib = Vibrations(atoms) # run vibrations on all atoms vib.run() vib_energies = vib.get_energies() thermo = IdealGasThermo(vib_energies=vib_energies, electronicenergy=electronicenergy, atoms=atoms, geometry='linear', # linear/nonlinear symmetrynumber=2, spin=0) # symmetry numbers from point group G = thermo.get_free_energy(temperature=300, pressure=101325.) # vapor pressure of water at room temperature e = open('e_energy.out','w')
from ase.optimize import QuasiNewton def set_work_cell(molecule,h,vacuum): molecule.center(vacuum=vacuum) cell = molecule.get_cell() for i in [0,1,2]: cell[i,i] = int(cell[i,i]/4./h)*4.*h molecule.set_cell(cell) return h=0.2 vacuum=4.5 atoms = read('init.traj') #atoms = read('testMolecule1nm.xyz') #atoms.set_pbc(True) #atoms.set_cell([10.0,10.0,10.0]) #set_work_cell(atoms,h,vacuum) ## gpaw calculator: calc = GPAW(h=h, nbands=-20, xc='PBE', txt='relax.txt', spinpol=True, charge=+1) atoms.set_calculator(calc) relax = QuasiNewton(atoms, logfile='relax.log',trajectory='relax.traj') relax.run(fmax=0.05) calc.write('relax.gpw',mode='all')
import numpy as np from ase import Atoms from ase.units import fs from ase.calculators.test import TestPotential from ase.calculators.emt import EMT from ase.md import VelocityVerlet from ase.io import PickleTrajectory, read from ase.optimize import QuasiNewton np.seterr(all='raise') a = Atoms('4X', masses=[1, 2, 3, 4], positions=[(0, 0, 0), (1, 0, 0), (0, 1, 0), (0.1, 0.2, 0.7)], calculator=TestPotential()) print a.get_forces() md = VelocityVerlet(a, dt=0.5 * fs, logfile='-', loginterval=500) traj = PickleTrajectory('4N.traj', 'w', a) md.attach(traj.write, 100) e0 = a.get_total_energy() md.run(steps=10000) del traj assert abs(read('4N.traj').get_total_energy() - e0) < 0.0001 qn = QuasiNewton(a) qn.run(0.001) assert abs(a.get_potential_energy() - 1.0) < 0.000002
e_shifts = [0.01,0.1,0.2,0.3,0.4,0.5] # Run the relaxation for each energy shift, and print out the # corresponding total energy, bond length and angle for e_s in e_shifts: starttime = time.time() calc = Siesta('h2o',meshcutoff=200.0 * units.Ry, mix=0.5, pulay=4) calc.set_fdf('PAO.EnergyShift', e_s * units.eV) calc.set_fdf('PAO.SplitNorm', 0.15) calc.set_fdf('PAO.BasisSize', 'SZ') h2o.set_calculator(calc) # Make a -traj file named h2o_current_shift.traj: dyn = QuasiNewton(h2o, trajectory='h2o_%s.traj' % e_s) dyn.run(fmax=0.02) # Perform the relaxation E = h2o.get_potential_energy() print # Make the output more readable print "E_shift: %.2f" %e_s print "----------------" print "Total Energy: %.4f" % E # Print total energy d = h2o.get_distance(0,2) print "Bond length: %.4f" % d # Print bond length p = h2o.positions d1 = p[0] - p[2] d2 = p[1] - p[2] r = np.dot(d1, d2) / (np.linalg.norm(d1) * np.linalg.norm(d2)) angle = np.arccos(r) / pi * 180 print "Bond angle: %.4f" % angle # Print bond angle endtime = time.time() walltime = endtime - starttime
from ase.constraints import FixAtoms from ase.calculators.emt import EMT from ase.vibrations import Vibrations from __init__ import AnharmonicModes 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, logfile='/dev/null') dyn.run(fmax=0.05) vib = Vibrations(slab, indices=[8, 9, 10, 11]) vib.run() vib.summary(log='/dev/null') vib.clean() AM = AnharmonicModes(vibrations_object=vib) rot_mode = AM.define_rotation( basepos=[0., 0., -1.], branch=[9, 10, 11], symnumber=3) AM.run() AM.summary(log='/dev/null') AM.clean()
cell=[10, 10, 10]) c_basis = """2 nodes 1.00 0 1 S 0.20 P 1 0.20 6.00 5.00 1.00 1 2 S 0.20 P 1 E 0.20 6.00 6.00 5.00 1.00 0.95""" specie = Specie(symbol='C', basis_set=PAOBasisBlock(c_basis)) calc = Siesta( label='ch4', basis_set='SZ', xc='LYP', mesh_cutoff=300 * Ry, species=[specie], restart='ch4.XV', ignore_bad_restart_file=True, fdf_arguments={'DM.Tolerance': 1E-5, 'DM.MixingWeight': 0.15, 'DM.NumberPulay': 3, 'MaxSCFIterations': 200, 'ElectronicTemperature': 0.02585 * eV, # 300 K 'SaveElectrostaticPotential': True}) bud.set_calculator(calc) dyn = QuasiNewton(bud, trajectory=traj) dyn.run(fmax=0.02) e = bud.get_potential_energy()
"""Test that the filter and trajectories are playing well together.""" from ase.build import molecule from ase.constraints import Filter from ase.optimize import QuasiNewton from ase.calculators.emt import EMT atoms = molecule('CO2') atoms.set_calculator(EMT()) filter = Filter(atoms, indices=[1, 2]) opt = QuasiNewton(filter, trajectory='filter-test.traj', logfile='filter-test.log') opt.run()
Hamiltonian_MaxAngularMomentum_='', Hamiltonian_MaxAngularMomentum_H='"s"', )) c = Hookean_Always(a1=0, a2=1, k=0, rt=0.6) atoms.set_constraint(c) OP = [] def print_distance(a=atoms): distance = a.get_distance(a0=0,a1=1) OP.append(distance) epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) ETOT = epot+ekin OP.append(ETOT) dyn = QuasiNewton(atoms, trajectory='atoms.traj') dyn.attach(print_distance) dyn.run(steps=10) print atoms.get_distance(a0=0, a1=1) write('test.final.xyz', atoms) OP_f = [OP[i:i+2] for i in xrange(0,len(OP),2)] OP_f_text = np.savetxt('out.tmp', OP_f) # reads array and saves into a file as a string OP_f_infile = open('out.tmp','r') # open file to write string array onto OP_f_text = OP_f_infile.read() text_file.write(OP_f_text) text_file.close()
constraint = FixAtoms(indices=[1, 3]) # fix OO for image in images: image.set_calculator(EMT()) image.set_constraint(constraint) for image in images: # O-H(shared) distance print(image.get_distance(1, 2), image.get_potential_energy()) # Relax initial and final states: if 1: # XXX: Warning: # One would have to optimize more tightly in order to get # symmetric anion from both images[0] and [1], but # if one optimizes tightly one gets rotated(H2O) ... OH- instead dyn1 = QuasiNewton(images[0]) dyn1.run(fmax=0.01) dyn2 = QuasiNewton(images[-1]) dyn2.run(fmax=0.01) # Interpolate positions between initial and final states: neb.interpolate() for image in images: print(image.get_distance(1, 2), image.get_potential_energy()) dyn = BFGS(neb, trajectory='emt_h3o2m.traj') dyn.run(fmax=0.05) for image in images: print(image.get_distance(1, 2), image.get_potential_energy())
constraint = FixAtoms(indices=[1, 3]) # fix OO #BUG No.1: fixes atom 0 and 1 #constraint = FixAtoms(mask=[0,1,0,1,0]) # fix OO #Works without patch for image in images: image.set_calculator(Turbomole()) #BUG No.2: (Over-)writes coord file image.set_constraint(constraint) # Write all commands for the define command in a string define_str = '\n\na coord\n\n*\nno\nb all 3-21g hondo\n*\neht\n\n-1\nno\ns\n*\n\ndft\non\nfunc pwlda\n\n\nscf\niter\n300\n\n*' # Run define p = Popen('define', stdout=PIPE, stdin=PIPE, stderr=STDOUT) stdout = p.communicate(input=define_str) # Relax initial and final states: if 1: dyn1 = QuasiNewton(images[0]) dyn1.run(fmax=0.10) dyn2 = QuasiNewton(images[-1]) dyn2.run(fmax=0.10) # Interpolate positions between initial and final states: neb.interpolate() if 1: for image in images: print image.get_distance(1, 2), image.get_potential_energy() dyn = BFGS(neb, trajectory='turbomole_h3o2m.traj') dyn.run(fmax=0.10) for image in images: print image.get_distance(1, 2), image.get_potential_energy()