def check_db(c, db, test=None): if test is None: print "%10s %10s %10s ( %10s )" \ % ( "bond", "value", "reference", "error" ) print "%10s %10s %10s ( %10s )" \ % ( "----", "-----", "---------", "-----" ) for mol, values in db.iteritems(): #if mol == 'H2O': if 1: print mol a = molecule(mol) a.center(vacuum=10.0) a.set_pbc(False) a.set_calculator(c) FIRE(a, logfile=None).run(fmax=0.001) for name, ( ( i1, i2 ), refvalue ) in values.iteritems(): value = a.get_distance(i1, i2) if test is None: print '%10s %10.3f %10.3f ( %10.3f )' % \ ( name, value, refvalue, abs(value-refvalue) ) else: test.assertTrue(abs(value-refvalue) < 0.01)
def setup_system(self, formula): """Create an Atoms object from the given formula. By default this will be loaded from the g2 database, setting the cell size by means of the molecule test's vacuum parameter.""" system = molecule(formula) system.center(vacuum=self.vacuum) return system
def main(): supported_elements = 'Ni, C, Pt, Ag, H, Al, O, N, Au, Pd, Cu'.split(', ') formulas = [ formula for formula in g1 if np.all([ symbol in supported_elements for symbol in molecule(formula).get_chemical_symbols() ]) ] atoms = [symbol for symbol in g2_atoms if symbol in supported_elements] dimers = [formula for formula in formulas if len(molecule(formula)) == 2] name1 = 'testfiles/energy' name2 = 'testfiles/bond' test1 = BatchTest(EMTEnergyTest(name1, vacuum=3.0)) test2 = BatchTest(EMTBondLengthTest(name2, vacuum=3.0)) print 'Energy test' print '-----------' test1.run(formulas + atoms) print print 'Bond length test' print '----------------' test2.run(dimers) print print 'Atomization energies' print '--------------------' atomic_energies = dict(test1.collect(atoms)) molecular_energies = dict(test1.collect(formulas)) atomization_energies = {} for formula, energy in molecular_energies.iteritems(): system = molecule(formula) atomic = [atomic_energies[s] for s in system.get_chemical_symbols()] atomization_energy = energy - sum(atomic) atomization_energies[formula] = atomization_energy print formula.rjust(10), '%.02f' % atomization_energy print print 'Bond lengths' print '------------' for formula, (d_i, e_i, d0, e0, poly) in test2.collect(dimers): system = molecule(formula) bref = np.linalg.norm(system.positions[1] - system.positions[0]) print formula.rjust(10), '%6.3f' % d0, ' g2ref =', '%2.3f' % bref
def do_calculations(self, formulas): """Perform calculation on molecules, write results to .gpw files.""" atoms = {} for formula in formulas: for symbol in string2symbols(formula.split('_')[0]): atoms[symbol] = None formulas = formulas + atoms.keys() for formula in formulas: if path.isfile(formula + '.gpw'): continue barrier() open(formula + '.gpw', 'w') s = molecule(formula) s.center(vacuum=self.vacuum) cell = s.get_cell() h = self.h s.set_cell((cell / (4 * h)).round() * 4 * h) s.center() calc = GPAW(h=h, xc=self.xc, eigensolver=self.eigensolver, setups=self.setups, basis=self.basis, fixmom=True, txt=formula + '.txt') if len(s) == 1: calc.set(hund=True) s.set_calculator(calc) if formula == 'BeH': calc.initialize(s) calc.nuclei[0].f_si = [(1, 0, 0.5, 0, 0), (0.5, 0, 0, 0, 0)] if formula in ['NO', 'ClO', 'CH']: s.positions[:, 1] += h * 1.5 try: energy = s.get_potential_energy() except (RuntimeError, ConvergenceError): if rank == 0: print >> sys.stderr, 'Error in', formula traceback.print_exc(file=sys.stderr) else: print >> self.txt, formula, repr(energy) self.txt.flush() calc.write(formula) if formula in diatomic and self.calculate_dimer_bond_lengths: traj = PickleTrajectory(formula + '.traj', 'w') d = diatomic[formula][1] for x in range(-2, 3): s.set_distance(0, 1, d * (1.0 + x * 0.02)) traj.write(s)
def main(): supported_elements = 'Ni, C, Pt, Ag, H, Al, O, N, Au, Pd, Cu'.split(', ') formulas = [formula for formula in g1 if np.all([symbol in supported_elements for symbol in molecule(formula).get_chemical_symbols()])] atoms = [symbol for symbol in g2_atoms if symbol in supported_elements] dimers = [formula for formula in formulas if len(molecule(formula)) == 2] name1 = 'testfiles/energy' name2 = 'testfiles/bond' test1 = BatchTest(EMTEnergyTest(name1, vacuum=3.0)) test2 = BatchTest(EMTBondLengthTest(name2, vacuum=3.0)) print 'Energy test' print '-----------' test1.run(formulas + atoms) print print 'Bond length test' print '----------------' test2.run(dimers) print print 'Atomization energies' print '--------------------' atomic_energies = dict(test1.collect(atoms)) molecular_energies = dict(test1.collect(formulas)) atomization_energies = {} for formula, energy in molecular_energies.iteritems(): system = molecule(formula) atomic = [atomic_energies[s] for s in system.get_chemical_symbols()] atomization_energy = energy - sum(atomic) atomization_energies[formula] = atomization_energy print formula.rjust(10), '%.02f' % atomization_energy print print 'Bond lengths' print '------------' for formula, (d_i, e_i, d0, e0, poly) in test2.collect(dimers): system = molecule(formula) bref = np.linalg.norm(system.positions[1] - system.positions[0]) print formula.rjust(10), '%6.3f' % d0, ' g2ref =', '%2.3f' % bref
def create_random_atoms(gd, nmolecules=10, name='H2O', mindist=4.5 / Bohr): """Create gas-like collection of atoms from randomly placed molecules. Applies rigid motions to molecules, translating the COM and/or rotating by a given angle around an axis of rotation through the new COM. These atomic positions obey the minimum distance requirement to zero-boundaries. Warning: This is only intended for testing parallel grid/LFC consistency. """ atoms = Atoms(cell=gd.cell_cv * Bohr, pbc=gd.pbc_c) # Store the original state of the random number generator randstate = np.random.get_state() np.random.seed(np.array([md5_array(data, numeric=True) for data in [nmolecules, gd.cell_cv, gd.pbc_c, gd.N_c]]).astype(int)) for m in range(nmolecules): amol = molecule(name) amol.set_cell(gd.cell_cv * Bohr) # Rotate the molecule around COM according to three random angles # The rotation axis is given by spherical angles phi and theta v,phi,theta = np.random.uniform(0.0, 2*np.pi, 3) # theta [0,pi[ really axis = np.array([cos(phi)*sin(theta), sin(phi)*sin(theta), cos(theta)]) amol.rotate(axis, v) # Find the scaled length we must transverse along the given axes such # that the resulting displacement vector is `mindist` from the cell # face corresponding to that direction (plane with unit normal n_v). sdist_c = np.empty(3) if not gd.orthogonal: for c in range(3): n_v = gd.xxxiucell_cv[c] / np.linalg.norm(gd.xxxiucell_cv[c]) sdist_c[c] = mindist / np.dot(gd.cell_cv[c], n_v) else: sdist_c[:] = mindist / gd.cell_cv.diagonal() assert np.all(sdist_c > 0), 'Displacment vectors must be inside cell.' # Scaled dimensions of the smallest possible box centered on the COM spos_ac = amol.get_scaled_positions() # NB! must not do a "% 1.0" scom_c = np.dot(gd.icell_cv, amol.get_center_of_mass()) sbox_c = np.abs(spos_ac-scom_c[np.newaxis,:]).max(axis=0) sdelta_c = (1-np.array(gd.pbc_c)) * (sbox_c + sdist_c) assert (sdelta_c < 1.0-sdelta_c).all(), 'Box is too tight to fit atoms.' scenter_c = [np.random.uniform(d,1-d) for d in sdelta_c] center_v = np.dot(scenter_c, gd.cell_cv) # Translate the molecule such that COM is located at random center offset_av = (center_v-amol.get_center_of_mass()/Bohr)[np.newaxis,:] amol.set_positions(amol.get_positions()+offset_av*Bohr) assert np.linalg.norm(center_v-amol.get_center_of_mass()/Bohr) < 1e-9 atoms.extend(amol) # Restore the original state of the random number generator np.random.set_state(randstate) assert compare_atoms(atoms) return atoms
def main(): formulas = g1 + atoms dimers = [formula for formula in g1 if len(molecule(formula)) == 2] kwargs = dict(vacuum=3.0, mode='lcao', basis='dzp') etest = BatchTest(GPAWEnergyTest('test/energy', **kwargs)) btest = BatchTest(GPAWBondLengthTest('test/bonds', **kwargs)) etest.run(formulas) btest.run(dimers)
def calculate_atomization_energies(self, molecular_energies, atomic_energies): atomic_energy_dict = dict(atomic_energies) for formula, molecular_energy in molecular_energies: try: system = molecule(formula) atomic = [atomic_energy_dict[s] for s in system.get_chemical_symbols()] atomization_energy = molecular_energy - sum(atomic) yield formula, atomization_energy except KeyError: pass
def calculate_atomization_energies(self, molecular_energies, atomic_energies): atomic_energy_dict = dict(atomic_energies) for formula, molecular_energy in molecular_energies: try: system = molecule(formula) atomic = [ atomic_energy_dict[s] for s in system.get_chemical_symbols() ] atomization_energy = molecular_energy - sum(atomic) yield formula, atomization_energy except KeyError: pass
def rotation_test(): molecule = 'NH3' a = 7. rcut = 5. l = 1 from gpaw.output import plot rotationvector = np.array([1.0, 1.0, 1.0]) angle_increment = 0.3 system = g2.molecule(molecule) system.set_cell([a, a, a]) system.center() calc = Calculator(h=0.27, txt=None) system.set_calculator(calc) pog = PolarizationOrbitalGenerator(rcut) r = np.linspace(0., rcut, 300) maxvalues = [] import pylab for i in range(0, int(6.28/angle_increment)): ascii = plot(system.positions, system.get_atomic_numbers(), system.get_cell().diagonal()) print ascii print 'angle=%.03f' % (angle_increment * i) energy = system.get_potential_energy() center = (system.positions / system.get_cell().diagonal())[0] orbital = pog.generate(l, calc.wfs.gd, calc.kpt_u[0].psit_nG, center) y = orbital(r) pylab.plot(r, y, label='%.02f' % (i * angle_increment)) maxvalues.append(max(y)) print 'Quality by orbital', #pretty(pog.optimizer.lastterms) system.rotate(rotationvector, angle_increment) system.center() print max(maxvalues) - min(maxvalues) pylab.legend() pylab.show()
def rotation_test(): molecule = 'NH3' a = 7. rcut = 5. l = 1 from gpaw.output import plot rotationvector = np.array([1.0, 1.0, 1.0]) angle_increment = 0.3 system = g2.molecule(molecule) system.set_cell([a, a, a]) system.center() calc = Calculator(h=0.27, txt=None) system.set_calculator(calc) pog = PolarizationOrbitalGenerator(rcut) r = np.linspace(0., rcut, 300) maxvalues = [] import pylab for i in range(0, int(6.28 / angle_increment)): ascii = plot(system.positions, system.get_atomic_numbers(), system.get_cell().diagonal()) print ascii print 'angle=%.03f' % (angle_increment * i) energy = system.get_potential_energy() center = (system.positions / system.get_cell().diagonal())[0] orbital = pog.generate(l, calc.wfs.gd, calc.kpt_u[0].psit_nG, center) y = orbital(r) pylab.plot(r, y, label='%.02f' % (i * angle_increment)) maxvalues.append(max(y)) print 'Quality by orbital', #pretty(pog.optimizer.lastterms) system.rotate(rotationvector, angle_increment) system.center() print max(maxvalues) - min(maxvalues) pylab.legend() pylab.show()
from ase.data.molecules import molecule from gpaw import GPAW from gpaw import dscf from gpaw.test import equal # Ground state calculation #------------------------------------------------------------------ calc_mol = GPAW(nbands=8, h=0.2, xc='PBE', spinpol=True, convergence={'energy': 100, 'density': 100, 'eigenstates': 1.0e-9, 'bands': -1}) CO = molecule('CO') CO.center(vacuum=3) CO.set_calculator(calc_mol) E_gs = CO.get_potential_energy() niter_gs = calc_mol.get_number_of_iterations() '''Get the pseudowavefunctions and projector overlaps of the state which is to be occupied. n=5,6 is the 2pix and 2piy orbitals''' n = 5 molecule = [0,1] wf_u = [kpt.psit_nG[n] for kpt in calc_mol.wfs.kpt_u] p_uai = [dict([(molecule[a], P_ni[n]) for a, P_ni in kpt.P_ani.items()]) for kpt in calc_mol.wfs.kpt_u] # Excited state calculations #-------------------------------------------- calc_1 = GPAW(nbands=8, h=0.2, xc='PBE', spinpol=True,
def run(argv=None): if argv is None: argv = sys.argv[1:] elif isinstance(argv, str): argv = argv.split() parser = build_parser() opt, args = parser.parse_args(argv) if len(args) != 1: parser.error("incorrect number of arguments") name = args[0] if world.rank == 0: out = sys.stdout#open('%s-%s.results' % (name, opt.identifier), 'w') else: out = devnull a = None try: symbols = string2symbols(name) except ValueError: # name was not a chemical formula - must be a file name: atoms = read(name) else: if opt.crystal_structure: a = opt.lattice_constant if a is None: a = estimate_lattice_constant(name, opt.crystal_structure, opt.c_over_a) out.write('Using an estimated lattice constant of %.3f Ang\n' % a) atoms = bulk(name, opt.crystal_structure, a, covera=opt.c_over_a, orthorhombic=opt.orthorhombic, cubic=opt.cubic) else: try: # Molecule? atoms = molecule(name) except NotImplementedError: if len(symbols) == 1: # Atom atoms = Atoms(name) elif len(symbols) == 2: # Dimer atoms = Atoms(name, positions=[(0, 0, 0), (opt.bond_length, 0, 0)]) else: raise ValueError('Unknown molecule: ' + name) if opt.magnetic_moment: magmom = opt.magnetic_moment.split(',') atoms.set_initial_magnetic_moments(np.tile(magmom, len(atoms) // len(magmom))) if opt.repeat is not None: r = opt.repeat.split(',') if len(r) == 1: r = 3 * r atoms = atoms.repeat([int(c) for c in r]) if opt.gui: view(atoms) return if opt.write_to_file: write(opt.write_to_file, atoms) return if opt.effective_medium_theory: Runner = EMTRunner else: Runner = GPAWRunner if opt.fit: strains = np.linspace(0.98, 1.02, 5) else: strains = None if opt.constrain_tags: tags = [int(t) for t in opt.constrain_tags.split(',')] constrain = FixAtoms(mask=[t in tags for t in atoms.get_tags()]) atoms.constraints = [constrain] runner = Runner(name, atoms, strains, tag=opt.identifier, clean=not opt.read, fmax=opt.relax, out=out) if not opt.effective_medium_theory: # Import stuff that eval() may need to know: from gpaw.wavefunctions.pw import PW from gpaw.occupations import FermiDirac, MethfesselPaxton if opt.parameters: input_parameters = eval(open(opt.parameters).read()) else: input_parameters = {} for key in defaults: value = getattr(opt, key) if value is not None: try: input_parameters[key] = eval(value) except (NameError, SyntaxError): input_parameters[key] = value runner.set_parameters(vacuum=opt.vacuum, write_gpw_file=opt.write_gpw_file, **input_parameters) runner.run() runner.summary(plot=opt.plot, a0=a) return runner
def run(formula='H2O', vacuum=1.5, cell=None, pbc=1, **morekwargs): print formula, parallel system = molecule(formula) kwargs = dict(basekwargs) kwargs.update(morekwargs) calc = GPAW(**kwargs) system.set_calculator(calc) system.center(vacuum) if cell is None: system.center(vacuum) else: system.set_cell(cell) system.set_pbc(pbc) try: system.get_potential_energy() except KohnShamConvergenceError: pass E = calc.hamiltonian.Etot F_av = calc.forces.calculate(calc.wfs, calc.density, calc.hamiltonian) global Eref, Fref_av if Eref is None: Eref = E Fref_av = F_av eerr = abs(E - Eref) ferr = abs(F_av - Fref_av).max() if calc.wfs.world.rank == 0: print 'Energy', E print print 'Forces' print F_av print print 'Errs', eerr, ferr if eerr > tolerance or ferr > tolerance: if calc.wfs.world.rank == 0: stderr = sys.stderr else: stderr = devnull if eerr > tolerance: print >> stderr, 'Failed!' print >> stderr, 'E = %f, Eref = %f' % (E, Eref) msg = 'Energy err larger than tolerance: %f' % eerr if ferr > tolerance: print >> stderr, 'Failed!' print >> stderr, 'Forces:' print >> stderr, F_av print >> stderr print >> stderr, 'Ref forces:' print >> stderr, Fref_av print >> stderr msg = 'Force err larger than tolerance: %f' % ferr print >> stderr print >> stderr, 'Args:' print >> stderr, formula, vacuum, cell, pbc, morekwargs print >> stderr, parallel raise AssertionError(msg)
H H Expected potential: ------- / \ / \ ----- ------ The height of the two potentials are tested to be the same. Enable if-statement in the bottom for nice plots """ system1 = molecule('H2O') system1.set_pbc((True, True, False)) system1.center(vacuum=3.0) system1.center(vacuum=10.0, axis=2) system2 = system1.copy() system2.positions *= [1.0, 1.0, -1.0] system2 += system1 system2.center(vacuum=6.0, axis=2) calc1 = GPAW(mode='lcao', gpts=h2gpts(0.3, system1.cell, idiv=8), poissonsolver=DipoleCorrection( PoissonSolver(relax='GS', eps=1e-11), 2)) system1.set_calculator(calc1)
from ase.data.molecules import molecule from ase.io import write atoms = molecule('CH3CN') atoms.center(vacuum=6) print 'unit cell' print '---------' print atoms.get_cell() write('images/ch3cn.png', atoms, show_unit_cell=2)
esolvers = ['cg', 'rmm-diis', 'dav'] E0 = {'cg': -17.612151335507559, 'rmm-diis': -17.612184220369553, 'dav': -17.612043641621657} I0 = {'cg': 6, 'rmm-diis': 7, 'dav': 8} calc = GPAW(xc='LDA', eigensolver='cg', convergence={'eigenstates': 1E-6}, txt=None, dtype=complex) mol = molecule('N2') mol.center(vacuum=3.0) mol.set_calculator(calc) Eini = mol.get_potential_energy() Iini = calc.get_number_of_iterations() print ('%10s: %12.6f eV in %3d iterations' % ('init(cg)', Eini, Iini)) equal(Eini, Eini0, 1E-8) equal(Iini, Iini0, 12) calc.write('N2.gpw', mode='all') del calc, mol E = {} I = {}
Expected potential: ------- / \ / \ ----- ------ The height of the two potentials are tested to be the same. Enable if-statement in the bottom for nice plots """ system1 = molecule('H2O') system1.set_pbc((True, True, False)) system1.center(vacuum=3.0) system1.center(vacuum=10.0, axis=2) system2 = system1.copy() system2.positions *= [1.0, 1.0, -1.0] system2 += system1 system2.center(vacuum=6.0, axis=2) calc1 = GPAW(mode='lcao', gpts=h2gpts(0.3, system1.cell, idiv=8), poissonsolver=DipoleCorrection(PoissonSolver(relax='GS', eps=1e-11), 2)) system1.set_calculator(calc1)
from ase import Atoms from ase.data.molecules import molecule from gpaw import GPAW, FermiDirac from gpaw.wavefunctions.pw import PW from gpaw.mpi import world k = 2 if world.size == 1: a = molecule('H', pbc=1, magmoms=[0]) a.center(vacuum=2) a.set_calculator( GPAW(mode=PW(250), kpts=(k, k, k))) a.get_potential_energy()
# This tests calculates the force on the atoms of a small molecule. # # If the test fails, set the fd boolean below to enable a (costly) finite # difference check. import numpy as np from ase.data.molecules import molecule from gpaw import GPAW from gpaw.atom.basis import BasisMaker obasis = BasisMaker('O').generate(2, 1, energysplit=0.3, tailnorm=0.03**.5) hbasis = BasisMaker('H').generate(2, 1, energysplit=0.3, tailnorm=0.03**.5) basis = {'O': obasis, 'H': hbasis} system = molecule('H2O') system.center(vacuum=1.5) system.rattle(stdev=.2, seed=42) system.set_pbc(1) calc = GPAW(h=0.2, mode='lcao', basis=basis, kpts=[(0., 0., 0.), (.3, .1, .4)], convergence={ 'density': 1e-5, 'energy': 1e-6 }) system.set_calculator(calc) F_ac = system.get_forces()
import numpy as np from ase.data.molecules import molecule from ase.dft import Wannier from gpaw import GPAW from gpaw.test import equal # Test of ase wannier using gpaw calc = GPAW(gpts=(32, 32, 32), nbands=4) atoms = molecule('H2', calculator=calc) atoms.center(vacuum=3.) e = atoms.get_potential_energy() niter = calc.get_number_of_iterations() pos = atoms.positions + np.array([[0, 0, .2339], [0, 0, -.2339]]) com = atoms.get_center_of_mass() wan = Wannier(nwannier=2, calc=calc, initialwannier='bloch') equal(wan.get_functional_value(), 2.964, 1e-3) equal(np.linalg.norm(wan.get_centers() - [com, com]), 0, 1e-4) wan = Wannier(nwannier=2, calc=calc, initialwannier='projectors') equal(wan.get_functional_value(), 3.100, 1e-3) equal(np.linalg.norm(wan.get_centers() - pos), 0, 1e-3) wan = Wannier(nwannier=2, calc=calc, initialwannier=[[0, 0, .5], [1, 0, .5]]) equal(wan.get_functional_value(), 3.100, 1e-3) equal(np.linalg.norm(wan.get_centers() - pos), 0, 1e-3) wan.localize() equal(wan.get_functional_value(), 3.100, 1e-3)
niter_tolerance = 0 systems = ['Li2'] # Add atoms for formula in systems: temp = split_formula(formula) for atom in temp: if atom not in systems: systems.append(atom) energies = {} niters = {} # Calculate energies for formula in systems: loa = molecule(formula) loa.set_cell(cell) loa.center() calc = GPAW( h=0.3, nbands=-2, xc='PBE', #fixmom=True, txt=formula + '.txt') if len(loa) == 1: calc.set(hund=True) else: pos = loa.get_positions() pos[1, :] = pos[0, :] + [0.0, 0.0, exp_bonds_dE[formula][0]] loa.set_positions(pos) loa.center()
def build(): p = OptionParser(usage='%prog [options] [ads@]surf [output file]', version='%prog 0.1', description='Example ads/surf: fcc-CO@2x2Ru0001') p.add_option('-l', '--layers', type='int', default=4, help='Number of layers.') p.add_option('-v', '--vacuum', type='float', default=5.0, help='Vacuum.') p.add_option('-x', '--crystal-structure', help='Crystal structure.', choices=['sc', 'fcc', 'bcc', 'hcp']) p.add_option('-a', '--lattice-constant', type='float', help='Lattice constant in Angstrom.') p.add_option('--c-over-a', type='float', help='c/a ratio.') p.add_option('--height', type='float', help='Height of adsorbate over surface.') p.add_option('--distance', type='float', help='Distance between adsorbate and nearest surface atoms.') p.add_option('-M', '--magnetic-moment', type='float', default=0.0, help='Magnetic moment.') p.add_option('-G', '--gui', action='store_true', help="Pop up ASE's GUI.") p.add_option('-P', '--python', action='store_true', help="Write Python script.") opt, args = p.parse_args() if not 1 <= len(args) <= 2: p.error("incorrect number of arguments") if '@' in args[0]: ads, surf = args[0].split('@') else: ads = None surf = args[0] if surf[0].isdigit(): i1 = surf.index('x') n = int(surf[:i1]) i2 = i1 + 1 while surf[i2].isdigit(): i2 += 1 m = int(surf[i1 + 1:i2]) surf = surf[i2:] else: n = 1 m = 1 if surf[-1].isdigit(): if surf[1].isdigit(): face = surf[1:] surf = surf[0] else: face = surf[2:] surf = surf[:2] else: face = None Z = atomic_numbers[surf] state = reference_states[Z] if opt.crystal_structure: x = opt.crystal_structure else: x = state['symmetry'] if opt.lattice_constant: a = opt.lattice_constant else: a = estimate_lattice_constant(surf, x, opt.c_over_a) script = ['from ase.lattice.surface import ', 'vac = %r' % opt.vacuum, 'a = %r' % a] if x == 'fcc': if face is None: face = '111' slab = fcc111(surf, (n, m, opt.layers), a, opt.vacuum) script[0] += 'fcc111' script += ['slab = fcc111(%r, (%d, %d, %d), a, vac)' % (surf, n, m, opt.layers)] r = a / np.sqrt(2) / 2 elif x == 'bcc': if face is None: face = '110' slab = bcc110(surf, (n, m, opt.layers), a, opt.vacuum) script[0] += 'bcc110' script += ['slab = bcc110(%r, (%d, %d, %d), a, vac)' % (surf, n, m, opt.layers)] r = a * np.sqrt(3) / 4 elif x == 'hcp': if face is None: face = '0001' if opt.c_over_a is None: c = np.sqrt(8 / 3.0) * a else: c = opt.c_over_a * a slab = hcp0001(surf, (n, m, opt.layers), a, c, opt.vacuum) script[0] += 'hcp0001' script += ['c = %r * a' % (c / a), 'slab = hcp0001(%r, (%d, %d, %d), a, c, vac)' % (surf, n, m, opt.layers)] r = a / 2 elif x == 'diamond': if face is None: face = '111' slab = diamond111(surf, (n, m, opt.layers), a, opt.vacuum) script[0] += 'diamond111' script += ['slab = diamond111(%r, (%d, %d, %d), a, vac)' % (surf, n, m, opt.layers)] r = a * np.sqrt(3) / 8 else: raise NotImplementedError magmom = opt.magnetic_moment if magmom is None: magmom = {'Ni': 0.6, 'Co': 1.2, 'Fe': 2.3}.get(surf, 0.0) slab.set_initial_magnetic_moments([magmom] * len(slab)) if magmom != 0: script += ['slab.set_initial_magnetic_moments([%r] * len(slab))' % magmom] slab.pbc = 1 script += ['slab.pbc = True'] name = '%dx%d%s%s' % (n, m, surf, face) if ads: site = 'ontop' if '-' in ads: site, ads = ads.split('-') name = site + '-' + ads + '@' + name symbols = string2symbols(ads) nads = len(symbols) if nads == 1: script[:0] = ['from ase import Atoms'] script += ['ads = Atoms(%r)' % ads] ads = Atoms(ads) else: script[:0] = ['from ase.data.molecules import molecule'] script += ['ads = molecule(%r)' % ads] ads = molecule(ads) add_adsorbate(slab, ads, 0.0, site) d = opt.distance if d is None: d = r + covalent_radii[ads[0].number] / 2 h = opt.height if h is None: R = slab.positions y = ((R[:-nads] - R[-nads])**2).sum(1).min()**0.5 h = (d**2 - y**2)**0.5 else: assert opt.distance is None slab.positions[-nads:, 2] += h script[1] += ', add_adsorbate' script += ['add_adsorbate(slab, ads, %r, %r)' % (h, site)] if len(args) == 2: write(args[1], slab) script[1:1] = ['from ase.io import write'] script += ['write(%r, slab)' % args[1]] elif not opt.gui: write(name + '.traj', slab) script[1:1] = ['from ase.io import write'] script += ['write(%r, slab)' % (name + '.traj')] if opt.gui: view(slab) script[1:1] = ['from ase.visualize import view'] script += ['view(slab)'] if opt.python: print('\n'.join(script))
import os from ase import Atoms from ase.calculators.dftb import Dftb from ase.optimize import QuasiNewton from ase.io import write from ase.data.molecules import molecule test = molecule('H2O') test.set_calculator( Dftb( label='h2o', atoms=test, Hamiltonian_MaxAngularMomentum_='', Hamiltonian_MaxAngularMomentum_O='"p"', Hamiltonian_MaxAngularMomentum_H='"s"', )) dyn = QuasiNewton(test, trajectory='test.traj') dyn.run(fmax=0.01) write('test.final.xyz', test)
if len(words) != 6: raise IOError('Number of columns in ACF file incorrect!\n' 'Check that Bader program version >= 0.25') sym = symbols[int(words[0]) - 1] charges.append(zval[sym] - float(words[j])) if displacement is not None: # check if the atom positions match xyz = np.array([float(w) for w in words[1:4]]) assert np.linalg.norm(positions[int(words[0]) - 1] - xyz) < displacement i += 1 if f_open: fileobj.close() # Now attach the resorted charges to the atom charges = np.array(charges)[resort] for atom in self: atom.charge = charges[atom.index] Atoms.attach_charges = attach_charges if __name__ == '__main__': from ase.data.molecules import molecule atoms = molecule('CH3CH2OH') print(atoms)
from ase.data.molecules import molecule from gpaw import GPAW a = 8.0 h = 0.2 energies = {} resultfile = open('results-%.2f.txt' % h, 'w') for name in ['H2O', 'H', 'O']: system = molecule(name) system.set_cell((a, a, a)) system.center() calc = GPAW(h=h, txt='gpaw-%s-%.2f.txt' % (name, h)) if name == 'H' or name == 'O': calc.set(hund=True) system.set_calculator(calc) energy = system.get_potential_energy() energies[name] = energy print >> resultfile, name, energy e_atomization = energies['H2O'] - 2 * energies['H'] - energies['O'] print >> resultfile, e_atomization
################# # who to send email to; please change to your email # SBATCH [email protected] ################# # task to run per node; each node has 16 cores # SBATCH --ntasks-per-node=16 ################# from ase.data.molecules import molecule from espresso import espresso from ase.optimize import QuasiNewton from ase.vibrations import Vibrations from ase.thermochemistry import IdealGasThermo from ase.all import view, read, write atoms = molecule("NH3") # molecular atoms.center(vacuum=10.0) atoms.set_cell([[10, 0, 0], [0, 10.1, 0], [0, 0, 10.2]]) calc = espresso( pw=500.0, dw=5000.0, nbands=-10, kpts=(1, 1, 1), xc="BEEF", outdir="outdir", psppath="/scratch/users/colinfd/psp/gbrv", sigma=10e-4, ) atoms.set_calculator(calc)
# This tests calculates the force on the atoms of a small molecule. # # If the test fails, set the fd boolean below to enable a (costly) finite # difference check. import numpy as np from ase.data.molecules import molecule from gpaw import GPAW from gpaw.atom.basis import BasisMaker obasis = BasisMaker('O').generate(2, 1, energysplit=0.3, tailnorm=0.03**.5) hbasis = BasisMaker('H').generate(2, 1, energysplit=0.3, tailnorm=0.03**.5) basis = {'O' : obasis, 'H' : hbasis} system = molecule('H2O') system.center(vacuum=1.5) system.rattle(stdev=.2, seed=42) system.set_pbc(1) calc = GPAW(h=0.2, mode='lcao', basis=basis, kpts=[(0., 0., 0.), (.3, .1, .4)], convergence={'density':1e-5, 'energy': 1e-6} ) system.set_calculator(calc) F_ac = system.get_forces()
from ase.data.molecules import molecule from gpaw import GPAW from gpaw.elf import ELF from gpaw.test import equal from gpaw.mpi import rank atoms = molecule('CO') atoms.center(2.0) calc = GPAW(h=0.24) atoms.set_calculator(calc) atoms.get_potential_energy() elf = ELF(calc) elf.initialize(calc) elf.update(calc.wfs) elf_G = elf.get_electronic_localization_function(spin=0, gridrefinement=1) elf_g = elf.get_electronic_localization_function(spin=0, gridrefinement=2) # integrate the CO bond if rank == 0: # bond area x0 = (atoms.positions[0][0] - 1.0) / atoms.get_cell()[0, 0] x1 = 1 - x0 y0 = (atoms.positions[0][1] - 1.0) / atoms.get_cell()[1, 1] y1 = 1 - y0 z0 = atoms.positions[1][2] / atoms.get_cell()[2, 2] z1 = atoms.positions[0][2] / atoms.get_cell()[2, 2] gd = calc.wfs.gd Gx0, Gx1 = gd.N_c[0] * x0, gd.N_c[0] * x1 Gy0, Gy1 = gd.N_c[1] * y0, gd.N_c[1] * y1 Gz0, Gz1 = gd.N_c[2] * z0, gd.N_c[2] * z1 finegd = calc.density.finegd
from ase.data.molecules import molecule from ase.parallel import rank, barrier from gpaw import GPAW, FermiDirac from gpaw.test import equal, gen # Generate setup for oxygen with a core-hole: gen('O', name='fch1s', xcname='PBE', corehole=(1, 0, 1.0)) atoms = molecule('H2O') atoms.center(vacuum=2.5) calc = GPAW(xc='PBE') atoms.set_calculator(calc) e1 = atoms.get_potential_energy() + calc.get_reference_energy() niter1 = calc.get_number_of_iterations() atoms[0].magmom = 1 calc.set(charge=-1, setups={'O': 'fch1s'}, occupations=FermiDirac(0.0, fixmagmom=True)) e2 = atoms.get_potential_energy() + calc.get_reference_energy() niter2 = calc.get_number_of_iterations() atoms[0].magmom = 0 calc.set(charge=0, setups={'O': 'fch1s'}, occupations=FermiDirac(0.0, fixmagmom=True), spinpol=True) e3 = atoms.get_potential_energy() + calc.get_reference_energy() niter3 = calc.get_number_of_iterations()
from ase.data.molecules import molecule from ase.io import write atoms = molecule('C6H6') # benzene # access properties on each atom print ' # sym p_x p_y p_z' print '------------------------------' for i, atom in enumerate(atoms): print '{0:3d}{1:^4s}{2:-8.2f}{3:-8.2f}{4:-8.2f}'.format(i, atom.symbol, atom.x, atom.y, atom.z) # get all properties in arrays sym = atoms.get_chemical_symbols() pos = atoms.get_positions() num = atoms.get_atomic_numbers() atom_indices = range(len(atoms)) print print ' # sym at# p_x p_y p_z' print '-------------------------------------' for i, s, n, p in zip(atom_indices, sym, num, pos): px, py, pz = p print '{0:3d}{1:>3s}{2:8d}{3:-8.2f}{4:-8.2f}{5:-8.2f}'.format(i, s, n, px, py, pz)
from ase.parallel import parprint from gpaw import GPAW from gpaw.cluster import Cluster from gpaw.analyse.hirshfeld import HirshfeldDensity, HirshfeldPartitioning from gpaw.analyse.wignerseitz import WignerSeitz from gpaw.test import equal h = 0.3 gpwname = 'H2O' + str(h) + '.gpw' try: calc = GPAW(gpwname + 'notfound', txt=None) # calc = GPAW(gpwname, txt=None) mol = calc.get_atoms() except: mol = Cluster(molecule('H2O')) mol.minimal_box(3, h=h) calc = GPAW(nbands=6, h=h, txt=None) calc.calculate(mol) calc.write(gpwname) # Hirshfeld ---------------------------------------- if 1: hd = HirshfeldDensity(calc) # check for the number of electrons expected = [ [None, 10], [[0, 1, 2], 10],
words = line.split() if assume6columns is True: if len(words) != 6: raise IOError('Number of columns in ACF file incorrect!\n' 'Check that Bader program version >= 0.25') sym = symbols[int(words[0]) - 1] charges.append(zval[sym] - float(words[j])) if displacement is not None: # check if the atom positions match xyz = np.array([float(w) for w in words[1:4]]) assert np.linalg.norm(positions[int(words[0]) - 1] - xyz) < displacement i += 1 if f_open: fileobj.close() # Now attach the resorted charges to the atom charges = np.array(charges)[resort] for atom in self: atom.charge = charges[atom.index] Atoms.attach_charges = attach_charges if __name__ == '__main__': from ase.data.molecules import molecule atoms = molecule('CH3CH2OH') print atoms
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.data.molecules import molecule from ase.io import write atoms1 = molecule('NH3') atoms2 = molecule('O2') atoms2.translate([3, 0, 0]) bothatoms = atoms1 + atoms2 bothatoms.center(5) write('images/bothatoms.png', bothatoms, show_unit_cell=2, rotation='90x')
# Benzene on the slab from jasp import * from ase.lattice.surface import fcc111, add_adsorbate from ase.data.molecules import molecule from ase.constraints import FixAtoms atoms = fcc111('Au', size=(3, 3, 3), vacuum=10) benzene = molecule('C6H6') benzene.translate(-benzene.get_center_of_mass()) # I want the benzene centered on the position in the middle of atoms # 20, 22, 23 and 25 p = (atoms.positions[20] + atoms.positions[22] + atoms.positions[23] + atoms.positions[25]) / 4.0 + [0.0, 0.0, 3.05] benzene.translate(p) atoms += benzene # now we constrain the slab c = FixAtoms(mask=[atom.symbol == 'Au' for atom in atoms]) atoms.set_constraint(c) #from ase.visualize import view; view(atoms) with jasp('surfaces/Au-benzene-pbe', xc='PBE', encut=350, kpts=(4, 4, 1), ibrion=1, nsw=100, atoms=atoms) as calc: print atoms.get_potential_energy()
import numpy as np from ase.data.molecules import molecule from gpaw import GPAW from gpaw.lcao.projected_wannier import get_lcao_projections_HSP atoms = molecule("C2H2") atoms.center(vacuum=3.0) calc = GPAW(gpts=(32, 32, 48)) atoms.set_calculator(calc) atoms.get_potential_energy() V_qnM, H_qMM, S_qMM, P_aqMi = get_lcao_projections_HSP(calc, bfs=None, spin=0, projectionsonly=False) # Test H and S eig = np.linalg.eigvals(np.linalg.solve(S_qMM[0], H_qMM[0])).real eig.sort() eig_ref = np.array( [ -17.87911292, -13.24864985, -11.43106707, -7.12558127, -7.12558127, 0.59294531, 0.59294531, 3.92526888, 7.45117399, 26.73466374, ]
the forces are nonzero. Energy is compared to a previous calculation; if it differs significantly, that is considered an error. Forces are compared to a previous finite-difference result. """ import numpy as np from ase.data.molecules import molecule from gpaw import GPAW from gpaw.utilities import unpack from gpaw.atom.basis import BasisMaker from gpaw.test import equal mol = molecule('H2O') mol.rattle(0.2) mol.center(vacuum=2.0) calc = GPAW(nbands=6, gpts=(32, 40, 40), setups='hgh', convergence=dict(eigenstates=1e-9, density=1e-5, energy=0.3e-5), txt='-') mol.set_calculator(calc) e = mol.get_potential_energy() niter = calc.get_number_of_iterations() F_ac = mol.get_forces() F_ac_ref = np.array([[ 7.33077718, 3.81069249, -6.07405156], [-0.9079617 , -1.18203514, 3.43777589], [-0.61642527, -0.41889306, 2.332415 ]])
the forces are nonzero. Energy is compared to a previous calculation; if it differs significantly, that is considered an error. Forces are compared to a previous finite-difference result. """ import numpy as np from ase.data.molecules import molecule from gpaw import GPAW from gpaw.utilities import unpack from gpaw.atom.basis import BasisMaker from gpaw.test import equal mol = molecule('H2O') mol.rattle(0.2) mol.center(vacuum=2.0) calc = GPAW(nbands=6, gpts=(32, 40, 40), setups='hgh', convergence=dict(eigenstates=1e-9, density=1e-5, energy=0.3e-5), txt='-') mol.set_calculator(calc) e = mol.get_potential_energy() niter = calc.get_number_of_iterations() F_ac = mol.get_forces() F_ac_ref = np.array([[7.33077718, 3.81069249, -6.07405156], [-0.9079617, -1.18203514, 3.43777589], [-0.61642527, -0.41889306, 2.332415]])
def calculate(element, h, vacuum, xc, magmom): atom = Atoms([Atom(element, (0, 0, 0))]) if magmom > 0.0: mms = [magmom for i in range(len(atom))] atom.set_initial_magnetic_moments(mms) atom.center(vacuum=vacuum) mixer = MixerSum(beta=0.2) if element == 'O': mixer = MixerSum(nmaxold=1, weight=100) atom.set_positions(atom.get_positions() + [0.0, 0.0, 0.0001]) calc_atom = GPAW(h=h, xc=data[element][xc][2], occupations=FermiDirac(0.0, fixmagmom=True), mixer=mixer, nbands=-2, txt='%s.%s.txt' % (element, xc)) atom.set_calculator(calc_atom) mixer = Mixer(beta=0.2, weight=100) compound = molecule(element + '2') if compound == 'O2': mixer = MixerSum(beta=0.2) mms = [1.0 for i in range(len(compound))] compound.set_initial_magnetic_moments(mms) calc = GPAW(h=h, xc=data[element][xc][2], mixer=mixer, txt='%s2.%s.txt' % (element, xc)) compound.set_distance(0, 1, data[element]['R_AA_B3LYP']) compound.center(vacuum=vacuum) compound.set_calculator(calc) if data[element][xc][3] == 'hyb_gga': # only for hybrids e_atom = atom.get_potential_energy() e_compound = compound.get_potential_energy() calc_atom.set(xc=xc) calc.set(xc=xc) if 0: qn = QuasiNewton(compound) qn.attach( PickleTrajectory(element + '2' + '_' + xc + '.traj', 'w', compound).write) qn.run(fmax=0.02) e_atom = atom.get_potential_energy() e_compound = compound.get_potential_energy() dHf_0 = (e_compound - 2 * e_atom + data[element]['ZPE_AA_B3LYP'] + 2 * data[element]['dHf_0_A']) dHf_298 = (dHf_0 + data[element]['H_298_H_0_AA_B3LYP'] - 2 * data[element]['H_298_H_0_A']) * (mol / kcal) dist_compound = compound.get_distance(0, 1) de = dHf_298 - data[element][xc][1] E[element][xc] = de if rank == 0: print(xc, h, vacuum, dHf_298, data[element][xc][1], de, de / data[element][xc][1]) if element == 'H': equal(dHf_298, data[element][xc][1], 0.25, msg=xc + ': ') # kcal/mol elif element == 'O': equal(dHf_298, data[element][xc][1], 7.5, msg=xc + ': ') # kcal/mol else: equal(dHf_298, data[element][xc][1], 2.15, msg=xc + ': ') # kcal/mol equal(de, E_ref[element][xc], 0.06, msg=xc + ': ') # kcal/mol
princ = pos(A, 0) + pos(B, 1) + pos(C, 2) large = (pos(princ, -8) + pos(princ, -4) + pos(princ, 0) + pos(A, 3) + pos(pyramid_BC, 4) + pos(inv_pyramid_BC, 3) + pos(princ, 4) + pos(princ, 8)) large.set_cell(cell * repeat, scale_atoms=True) large.cell[0, 0] = 7 * large.cell[0, 0] dist = 18. large.cell[0, 0] += dist - cell[0, 0] large.positions[-(9 * 6 + 4):, 0] += dist - cell[0, 0] tipL, tipR = large.positions[large.get_tags() == 2] tipdist = np.linalg.norm(tipL - tipR) mol = molecule('C6H6', pbc=True, tags=[3] * 6 + [4] * 6) mol.rotate('y', 'x') mol.rotate('z', 'y') large += mol large.positions[-len(mol):] += tipL large.positions[-len(mol):, 0] += tipdist / 2 old = large.cell.copy() large *= (1, 1, 3) large.set_cell(old) #view(large) colors = np.zeros((len(large), 3)) colors[:] = [1., 1., .75]
################# #who to send email to; please change to your email #SBATCH [email protected] ################# #task to run per node; each node has 16 cores #SBATCH --ntasks-per-node=16 ################# from ase.data.molecules import molecule from espresso import espresso from ase.optimize import QuasiNewton from ase.vibrations import Vibrations from ase.thermochemistry import IdealGasThermo from ase.all import view,read,write atoms = molecule('H2') # molecular 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')
from pylab import * from ase import * from hotbit import * from box.grids import GridData from ase.data.molecules import molecule atoms = molecule('C6H6') calc = Hotbit(SCC=True, width=0.05, txt='benzene.cal') atoms.set_calculator(calc) atoms.center(vacuum=3) atoms.get_potential_energy() #view(atoms) r = atoms.get_positions() calc.set_grid(h=0.4) ldos = calc.get_grid_LDOS(bias=-6) current = 4 # current in nanoamperes crit = 2E-4 * sqrt(current) stm = GridData(atoms, data=ldos) h = stm.scan(crit, bottom=r[:, 2].mean()).transpose() X, Y, Z = stm.get_grids() contourf(X, Y, h, 50) hot() scatter(r[:, 0], r[:, 1], color='blue', marker='o', s=2) xlabel(r'x ($\AA$)') ylabel(r'y ($\AA$)') xlim(xmin=0, xmax=X[-1]) ylim(ymin=0, ymax=Y[-1]) savefig('benzene_STM.png')
def run(formula='H2O', vacuum=2.0, cell=None, pbc=0, **morekwargs): print formula, parallel system = molecule(formula) kwargs = dict(basekwargs) kwargs.update(morekwargs) calc = GPAW(**kwargs) system.set_calculator(calc) system.center(vacuum) if cell is None: system.center(vacuum) else: system.set_cell(cell) system.set_pbc(pbc) try: system.get_potential_energy() except KohnShamConvergenceError: pass E = calc.hamiltonian.Etot F_av = calc.forces.calculate(calc.wfs, calc.density, calc.hamiltonian) global Eref, Fref_av if Eref is None: Eref = E Fref_av = F_av eerr = abs(E - Eref) ferr = abs(F_av - Fref_av).max() if calc.wfs.world.rank == 0: print 'Energy', E print print 'Forces' print F_av print print 'Errs', eerr, ferr if eerr > tolerance or ferr > tolerance: if calc.wfs.world.rank == 0: stderr = sys.stderr else: stderr = devnull if eerr > tolerance: print >> stderr, 'Failed!' print >> stderr, 'E = %f, Eref = %f' % (E, Eref) msg = 'Energy err larger than tolerance: %f' % eerr if ferr > tolerance: print >> stderr, 'Failed!' print >> stderr, 'Forces:' print >> stderr, F_av print >> stderr print >> stderr, 'Ref forces:' print >> stderr, Fref_av print >> stderr msg = 'Force err larger than tolerance: %f' % ferr print >> stderr print >> stderr, 'Args:' print >> stderr, formula, vacuum, cell, pbc, morekwargs print >> stderr, parallel raise AssertionError(msg)
################# #who to send email to; please change to your email #SBATCH [email protected] ################# #task to run per node; each node has 16 cores #SBATCH --ntasks-per-node=16 ################# from ase.data.molecules import molecule from espresso import espresso from ase.optimize import QuasiNewton from ase.vibrations import Vibrations from ase.thermochemistry import IdealGasThermo from ase.all import view, read, write atoms = molecule('N2') # molecular 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='calcdir', psppath="/scratch/users/colinfd/psp/gbrv", sigma=10e-4) atoms.set_calculator(calc) dyn = QuasiNewton(atoms, logfile='out.log', trajectory='out.traj')
from pylab import * from ase import * from hotbit import * from box.grids import GridData from ase.data.molecules import molecule atoms = molecule('C6H6') calc = Hotbit(SCC=True,width=0.05,txt='benzene.cal') atoms.set_calculator(calc) atoms.center(vacuum=3) atoms.get_potential_energy() #view(atoms) r = atoms.get_positions() calc.set_grid(h=0.4) ldos = calc.get_grid_LDOS(bias=-6) current=4 # current in nanoamperes crit = 2E-4*sqrt(current) stm = GridData(atoms,data=ldos) h = stm.scan(crit,bottom=r[:,2].mean()).transpose() X,Y,Z = stm.get_grids() contourf(X,Y,h,50) hot() scatter(r[:,0],r[:,1],color='blue',marker='o',s=2) xlabel(r'x ($\AA$)') ylabel(r'y ($\AA$)') xlim(xmin=0,xmax=X[-1]) ylim(ymin=0,ymax=Y[-1]) savefig('benzene_STM.png')
import os from ase.data.molecules import molecule from ase.io import write from ase.units import Bohr from gpaw import GPAW from gpaw.mpi import rank atoms = molecule('H2O', cell=[7.5, 9, 9], calculator=GPAW(h=.17, xc='PBE')) atoms.center() atoms.get_potential_energy() rho = atoms.calc.get_all_electron_density(gridrefinement=4) * Bohr**3 write('water_density.cube', atoms, data=rho) rho = atoms.calc.get_pseudo_density(gridrefinement=2) * Bohr**3 write('water_pseudo_density.cube', atoms, data=rho) if rank == 0: os.system('~/bin/bader -p all_atom -p atom_index water_density.cube')
#!/bin/python ''' Problem 2 ========= ''' from ase.data.molecules import molecule from jasp import * # Define molecules CO = molecule('CO') CO.set_cell([8, 8, 8], scale_atoms=False) CO.center() O2 = molecule('O2') O2.set_cell([8, 8, 8], scale_atoms=False) O2.center() CO2 = molecule('CO2') CO2.set_cell([8, 8, 8], scale_atoms=False) CO2.center() with jasp('molecules/hw03/CO_vib-{0}'.format(350), encut=400, ismear=0,# Gaussian smearing ibrion=6,# finite differences with symmetry nfree=2, # central differences (default) potim=0.015, # default as well ediff=1e-8, nsw=1, atoms=CO) as calc:
from ase import Atoms from ase.io import write from ase.data.molecules import molecule a = 5.64 # Lattice constant for NaCl cell = [a / np.sqrt(2), a / np.sqrt(2), a] atoms = Atoms(symbols='Na2Cl2', pbc=True, cell=cell, scaled_positions=[ (.0, .0, .0), (.5, .5, .5), (.5, .5, .0), (.0, .0, .5), ]) * (3, 4, 2) + molecule('C6H6') # Move molecule to 3.5Ang from surface, and translate one unit cell in xy atoms.positions[-12:, 2] += atoms.positions[:-12, 2].max() + 3.5 atoms.positions[-12:, :2] += cell[:2] # Mark a single unit cell atoms.cell = cell # View used to start ag, and find desired viewing angle #view(atoms) rot = '35x,63y,36z' # found using ag: 'view -> rotate' # Common kwargs for eps, png, pov kwargs = { 'rotation': rot, # text string with rotation (default='' )
def build(): p = OptionParser(usage='%prog [options] [ads@]surf [output file]', version='%prog 0.1', description='Example ads/surf: fcc-CO@2x2Ru0001') p.add_option('-l', '--layers', type='int', default=4, help='Number of layers.') p.add_option('-v', '--vacuum', type='float', default=5.0, help='Vacuum.') p.add_option('-x', '--crystal-structure', help='Crystal structure.', choices=['sc', 'fcc', 'bcc', 'hcp']) p.add_option('-a', '--lattice-constant', type='float', help='Lattice constant in Angstrom.') p.add_option('--c-over-a', type='float', help='c/a ratio.') p.add_option('--height', type='float', help='Height of adsorbate over surface.') p.add_option('--distance', type='float', help='Distance between adsorbate and nearest surface atoms.') p.add_option('-M', '--magnetic-moment', type='float', default=0.0, help='Magnetic moment.') p.add_option('-G', '--gui', action='store_true', help="Pop up ASE's GUI.") opt, args = p.parse_args() if not 1 <= len(args) <= 2: p.error("incorrect number of arguments") if '@' in args[0]: ads, surf = args[0].split('@') else: ads = None surf = args[0] if surf[0].isdigit(): i1 = surf.index('x') n = int(surf[:i1]) i2 = i1 + 1 while surf[i2].isdigit(): i2 += 1 m = int(surf[i1 + 1:i2]) surf = surf[i2:] else: n = 1 m = 1 if surf[-1].isdigit(): if surf[1].isdigit(): face = surf[1:] surf = surf[0] else: face = surf[2:] surf = surf[:2] else: face = None Z = atomic_numbers[surf] state = reference_states[Z] if opt.crystal_structure: x = opt.crystal_structure else: x = state['symmetry'].lower() if opt.lattice_constant: a = opt.lattice_constant else: a = estimate_lattice_constant(surf, x, opt.c_over_a) if x == 'fcc': if face is None: face = '111' slab = fcc111(surf, (n, m, opt.layers), a, opt.vacuum) r = a / np.sqrt(2) / 2 elif x == 'bcc': if face is None: face = '110' slab = bcc110(surf, (n, m, opt.layers), a, opt.vacuum) r = a * np.sqrt(3) / 4 elif x == 'hcp': if face is None: face = '0001' if opt.c_over_a is None: c = np.sqrt(8 / 3.0) * a else: c = opt.c_over_a * a slab = hcp0001(surf, (n, m, opt.layers), a, c, opt.vacuum) r = a / 2 else: raise NotImplementedError magmom = opt.magnetic_moment if magmom is None: magmom = {'Ni': 0.6, 'Co': 1.2, 'Fe': 2.3}.get(surf, 0.0) slab.set_initial_magnetic_moments([magmom] * len(slab)) slab.pbc = 1 name = '%dx%d%s%s' % (n, m, surf, face) if ads: site = 'ontop' if '-' in ads: site, ads = ads.split('-') name = site + '-' + ads + '@' + name symbols = string2symbols(ads) nads = len(symbols) if nads == 1: ads = Atoms(ads) else: ads = molecule(ads) add_adsorbate(slab, ads, 0.0, site) d = opt.distance if d is None: d = r + covalent_radii[ads[0].number] / 2 h = opt.height if h is None: R = slab.positions y = ((R[:-nads] - R[-nads])**2).sum(1).min()**0.5 print y h = (d**2 - y**2)**0.5 print h else: assert opt.distance is None slab.positions[-nads:, 2] += h if len(args) == 2: write(args[1], slab) elif not opt.gui: write(name + '.traj', slab) if opt.gui: view(slab)
from ase.data.molecules import molecule from jasp import * # first we define our molecules. These will automatically be at the coordinates from the G2 database. CO = molecule('CO') CO.set_cell([8, 8, 8], scale_atoms=False) H2O = molecule('H2O') H2O.set_cell([8, 8, 8], scale_atoms=False) CO2 = molecule('CO2') CO2.set_cell([8, 8, 8], scale_atoms=False) H2 = molecule('H2') H2.set_cell([8, 8, 8], scale_atoms=False) # now the calculators to get the energies with jasp('molecules/wgs/CO', xc='PBE', encut=350, ismear=0, ibrion=2, nsw=10, atoms=CO) as calc: try: eCO = CO.get_potential_energy() except (VaspSubmitted, VaspQueued): eCO = None with jasp('molecules/wgs/CO2', xc='PBE', encut=350, ismear=0, ibrion=2, nsw=10, atoms=CO2) as calc: try: