def test_replay(testdir): # Distance between Cu atoms on a (100) surface: d = 3.6 / sqrt(2) a = Atoms('Cu', positions=[(0, 0, 0)], cell=(d, d, 1.0), pbc=(True, True, False)) a *= (2, 2, 1) # 2x2 (100) surface-cell # Approximate height of Ag atom on Cu(100) surfece: h0 = 2.0 a += Atom('Ag', (d / 2, d / 2, h0)) if 0: view(a) constraint = FixAtoms(range(len(a) - 1)) a.calc = EMT() a.set_constraint(constraint) with QuasiNewton(a, trajectory='AgCu1.traj', logfile='AgCu1.log') as dyn1: dyn1.run(fmax=0.1) a = read('AgCu1.traj') a.calc = EMT() print(a.constraints) with QuasiNewton(a, trajectory='AgCu2.traj', logfile='AgCu2.log') as dyn2: dyn2.replay_trajectory('AgCu1.traj') dyn2.run(fmax=0.01)
def compare_forces(atoms: Atoms, calc1, calc2): print(f"atoms # {len(atoms.numbers)}") calc1.reset() atoms.calc = calc1 start = perf_counter() try: F1 = atoms.get_forces() t1 = perf_counter() - start except: print("Calculation failed") F1 = np.array([np.nan]) t1 = np.nan print(f"F1 {F1.shape} took {t1} sec") calc2.reset() atoms.calc = calc2 start = perf_counter() F2 = atoms.get_forces() t2 = perf_counter() - start print(f"F2 {F2.shape} took {t2} sec") # print(F2) print( f"diff {np.max(np.abs(F1 - F2))}, calc1/calc2 -> {t1 / t2} times faster" ) return t1, t2, F1, F2
def test_strain(): from math import sqrt from ase import Atoms from ase.constraints import StrainFilter from ase.optimize.mdmin import MDMin from ase.io import Trajectory 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.calc = EMT() f = StrainFilter(cu, [1, 1, 1, 0, 0, 0]) opt = MDMin(f, dt=0.01) t = Trajectory('Cu.traj', 'w', cu) opt.attach(t) opt.run(0.001) # HCP: from ase.build import bulk cu = bulk('Cu', 'hcp', a=a / sqrt(2)) cu.cell[1, 0] -= 0.05 cu *= (6, 6, 3) cu.calc = EMT() f = StrainFilter(cu) opt = MDMin(f, dt=0.01) t = Trajectory('Cu.traj', 'w', cu) opt.attach(t) opt.run(0.01)
def toatoms(self, attach_calculator=False, add_additional_information=False): """Create Atoms object.""" atoms = Atoms(self.numbers, self.positions, cell=self.cell, pbc=self.pbc, magmoms=self.get('initial_magmoms'), charges=self.get('initial_charges'), tags=self.get('tags'), masses=self.get('masses'), momenta=self.get('momenta'), constraint=self.constraints) if attach_calculator: params = self.get('calculator_parameters', {}) atoms.calc = get_calculator_class(self.calculator)(**params) else: results = {} for prop in all_properties: if prop in self: results[prop] = self[prop] if results: atoms.calc = SinglePointCalculator(atoms, **results) atoms.calc.name = self.get('calculator', 'unknown') if add_additional_information: atoms.info = {} atoms.info['unique_id'] = self.unique_id if self._keys: atoms.info['key_value_pairs'] = self.key_value_pairs data = self.get('data') if data: atoms.info['data'] = data
def _assert_energy_equal(calc1, calc2, atoms: Atoms): calc1.reset() atoms.calc = calc1 e1 = atoms.get_potential_energy() calc2.reset() atoms.calc = calc2 e2 = atoms.get_potential_energy() assert np.allclose(e1, e2, atol=1e-4, rtol=1e-4)
def test_change_cell_dimensions_and_pbc(factory, dimer_params, lj_epsilons): """Ensure that post_change_box commands are actually executed after changing the dimensions of the cell or its periodicity. This is done by setting up an isolated dimer with a Lennard-Jones potential and a set of post_changebox_cmds that specify the same potential but with a rescaled energy (epsilon) parameter. The energy is then computed twice, once before changing the cell dimensions and once after, and the values are compared to the expected values based on the two different epsilons to ensure that the modified LJ potential is used for the second calculation. The procedure is repeated but where the periodicity of the cell boundaries is changed rather than the cell dimensions. """ # Make a dimer in a large nonperiodic box dimer = Atoms(**dimer_params) spec, a = extract_dimer_species_and_separation(dimer) # Ensure LJ cutoff is large enough to encompass the dimer lj_cutoff = 3 * a calc_params = calc_params_lj_changebox(spec, lj_cutoff, **lj_epsilons) dimer.calc = factory.calc(**calc_params) energy_orig = dimer.get_potential_energy() # Shrink the box slightly to invalidate cached energy and force change_box # to be issued. This shouldn't actually affect the energy in and of itself # since our dimer has non-periodic boundaries. cell_orig = dimer.get_cell() dimer.set_cell(cell_orig * 1.01, scale_atoms=False) energy_modified = dimer.get_potential_energy() eps_scaling_factor = lj_epsilons["eps_modified"] / lj_epsilons["eps_orig"] assert energy_modified == pytest.approx(eps_scaling_factor * energy_orig, rel=1e-4) # Reset dimer cell. Also, create and attach new calculator so that # previous post_changebox_cmds won't be in effect. dimer.set_cell(cell_orig, scale_atoms=False) dimer.calc = factory.calc(**calc_params) # Compute energy of original configuration again so that a change_box will # be triggered on the next calculation after we change the pbcs energy_orig = dimer.get_potential_energy() # Change the periodicity of the cell along one direction. This shouldn't # actually affect the energy in and of itself since the cell is large # relative to the dimer dimer.set_pbc([False, True, False]) energy_modified = dimer.get_potential_energy() assert energy_modified == pytest.approx(eps_scaling_factor * energy_orig, rel=1e-4)
def systems_minimum(): """two atoms at potential minimum""" atoms = Atoms('H2', positions=[[0, 0, 0], [0, 0, 2**(1.0 / 6.0)]]) calc = LennardJones(rc=1.0e5) atoms.calc = calc yield atoms calc = LennardJones(rc=1.0e5, smooth=True) atoms.calc = calc yield atoms
def test_standardcomparator(): from ase.ga.standard_comparators import (InteratomicDistanceComparator, EnergyComparator, RawScoreComparator, SequentialComparator) from ase import Atoms from ase.calculators.singlepoint import SinglePointCalculator from ase.ga import set_raw_score a1 = Atoms('AgAgAg', positions=[[0, 0, 0], [1.5, 0, 0], [1.5, 1.5, 0]]) a2 = Atoms('AgAgAg', positions=[[0, 0, 0], [1.4, 0, 0], [1.5, 1.5, 0]]) e1 = 1.0 e2 = 0.8 a1.calc = SinglePointCalculator(a1, energy=e1) a2.calc = SinglePointCalculator(a2, energy=e2) comp1 = InteratomicDistanceComparator(n_top=3, pair_cor_cum_diff=0.03, pair_cor_max=0.7, dE=0.3) assert comp1.looks_like(a1, a2) comp2 = InteratomicDistanceComparator(n_top=3, pair_cor_cum_diff=0.03, pair_cor_max=0.7, dE=0.15) assert not comp2.looks_like(a1, a2) comp3 = InteratomicDistanceComparator(n_top=3, pair_cor_cum_diff=0.02, pair_cor_max=0.7, dE=0.3) assert not comp3.looks_like(a1, a2) hard_E_comp = EnergyComparator(dE=1.0) assert hard_E_comp.looks_like(a1, a2) soft_E_comp = EnergyComparator(dE=.01) assert not soft_E_comp.looks_like(a1, a2) set_raw_score(a1, .1) set_raw_score(a2, .27) rs_comp = RawScoreComparator(0.15) assert not rs_comp.looks_like(a1, a2) comp1 = SequentialComparator([hard_E_comp, rs_comp], [0, 0]) assert not comp1.looks_like(a1, a2) comp2 = SequentialComparator([hard_E_comp, rs_comp], [0, 1]) assert comp2.looks_like(a1, a2)
def main(): atom = Atoms('N') atom.calc = EMT() e_atom = atom.get_potential_energy() d = 1.1 molecule = Atoms('2N', [(0, 0, 0), (0, 0, d)]) molecule.calc = EMT() e_molecule = molecule.get_potential_energy() e_atomization = e_molecule - 2 * e_atom print('Nitrogen atom energy: %5.2f eV' % e_atom) print('Nitrogen molecule energy: %5.2f eV' % e_molecule) print('Atomization energy: %5.2f eV' % -e_atomization)
def test_finite_difference(): # ensure that we got the modified forces right h = 1e-10 r = 8.0 calc = LennardJones(smooth=True, ro=6, rc=10, sigma=3) atoms = Atoms('H2', positions=[[0, 0, 0], [r, 0, 0]]) atoms2 = Atoms('H2', positions=[[0, 0, 0], [r + h, 0, 0]]) atoms.calc = calc atoms2.calc = calc fd_force = (atoms2.get_potential_energy() - atoms.get_potential_energy()) / h force = atoms.get_forces()[0, 0] np.testing.assert_allclose(fd_force, force)
def lithiumBulk(comm): d = 3.5 li = Atoms("Li2", positions=[(0, 0, 0), (0.5 * d, 0.5 * d, 0.5 * d)], cell=np.eye(3) * d) from ase.dft import kpoints kpointList = kpoints.monkhorst_pack((4, 4, 4)) kpointList += np.asarray([0.125, 0.125, 0.125]) w = 1.0 / len(kpointList) if "--gpu" in sys.argv: li.calc = ElectronicMinimizeGPU(atoms=li, log=True, kpts=[(k, w) for k in kpointList], comm=comm) else: li.calc = ElectronicMinimize(atoms=li, log=True, kpts=[(k, w) for k in kpointList], comm=comm) li.calc.dragWavefunctions = False print(li.get_potential_energy() / Hartree)
def test_monoclinic(): """Test band structure from different variations of hexagonal cells.""" mc1 = Cell([[1, 0, 0], [0, 1, 0], [0, 0.2, 1]]) par = mc1.cellpar() mc2 = Cell.new(par) mc3 = Cell([[1, 0, 0], [0, 1, 0], [-0.2, 0, 1]]) mc4 = Cell([[1, 0, 0], [-0.2, 1, 0], [0, 0, 1]]) path = 'GYHCEM1AXH1' firsttime = True for cell in [mc1, mc2, mc3, mc4]: a = Atoms(cell=cell, pbc=True) a.cell *= 3 a.calc = FreeElectrons(nvalence=1, kpts={'path': path}) lat = a.cell.get_bravais_lattice() assert lat.name == 'MCL' a.get_potential_energy() bs = a.calc.band_structure() coords, labelcoords, labels = bs.get_labels() assert ''.join(labels) == path e_skn = bs.energies if firsttime: coords1 = coords labelcoords1 = labelcoords e_skn1 = e_skn firsttime = False else: for d in [coords - coords1, labelcoords - labelcoords1, e_skn - e_skn1]: print(abs(d).max()) assert abs(d).max() < 1e-13, d
def convergence(self, n, fd): a = 3.0 atoms = Atoms(self.symbol, cell=(a, a, a), pbc=True) M = 333 if 58 <= self.Z <= 70 or 90 <= self.Z <= 102: M = 999 mixer = {'mixer': Mixer(0.01, 5)} else: mixer = {} atoms.calc = GPAW(mode=PW(1500), xc='PBE', setups='ga' + str(n), symmetry='off', maxiter=M, txt=fd, **mixer) e0 = atoms.get_potential_energy() de0 = 0.0 for ec in range(800, 200, -100): atoms.calc.set(mode=PW(ec)) atoms.calc.set(eigensolver='rmm-diis') de = abs(atoms.get_potential_energy() - e0) if de > 0.1: ec0 = ec + (de - 0.1) / (de - de0) * 100 return ec0 de0 = de return 250
def test_struc_from_ase(): from ase import Atoms from ase.calculators.singlepoint import SinglePointCalculator results = { "forces": np.random.randn(20, 3), "energy": np.random.rand(), "stress": np.random.randn(6), } uc = Atoms( ["Pd" for i in range(10)] + ["Ag" for i in range(10)], positions=np.random.rand(20, 3), cell=np.random.rand(3, 3), ) calculator = SinglePointCalculator(uc, **results) uc.calc = calculator new_struc = Structure.from_ase_atoms(uc) assert np.all(new_struc.species_labels == uc.get_chemical_symbols()) assert np.all(new_struc.positions == uc.get_positions()) assert np.all(new_struc.cell == uc.get_cell()) assert np.all(new_struc.forces == results["forces"]) assert np.all(new_struc.energy == results["energy"]) assert np.all(new_struc.stress == results["stress"])
def to_ase(self): arrays_keys = set(self.arrays_keys) info_keys = set(self.info_keys) cell = self.pop('cell', None) pbc = self.pop('pbc', None) numbers = self.pop('numbers', None) positions = self.pop('positions', None) results_keys = self.derived['results_keys'] info_keys -= {'cell', 'pbc'} arrays_keys -= {'numbers', 'positions'} atoms = Atoms(cell=cell, pbc=pbc, numbers=numbers, positions=positions) if 'calculator_name' in self: # calculator_name = self['info'].pop('calculator_name') # atoms.calc = get_calculator(data['results']['calculator_name'])(**params) params = self.pop('calculator_parameters', {}) atoms.calc = SinglePointCalculator(atoms, **params) atoms.calc.results.update((key, self[key]) for key in results_keys) atoms.arrays.update((key, np.array(self[key])) for key in arrays_keys) atoms.info.update((key, self[key]) for key in info_keys) return atoms
def test_hex(): """Test band structure from different variations of hexagonal cells.""" firsttime = True for cell in [[[1, 0, 0], [0.5, 3**0.5 / 2, 0], [0, 0, 1]], [[1, 0, 0], [-0.5, 3**0.5 / 2, 0], [0, 0, 1]], [[0.5, -3**0.5 / 2, 0], [0.5, 3**0.5 / 2, 0], [0, 0, 1]]]: a = Atoms(cell=cell, pbc=True) a.cell *= 3 a.calc = FreeElectrons(nvalence=1, kpts={'path': 'GMKG'}) lat = a.cell.get_bravais_lattice() assert lat.name == 'HEX' print(repr(a.cell.get_bravais_lattice())) r = a.cell.reciprocal() k = get_special_points(a.cell)['K'] print(np.dot(k, r)) a.get_potential_energy() bs = a.calc.band_structure() coords, labelcoords, labels = bs.get_labels() assert ''.join(labels) == 'GMKG' e_skn = bs.energies if firsttime: coords1 = coords labelcoords1 = labelcoords e_skn1 = e_skn firsttime = False else: for d in [ coords - coords1, labelcoords - labelcoords1, e_skn - e_skn1 ]: assert abs(d).max() < 1e-13
def test_main(require_vasp): assert installed() # simple test calculation of CO molecule d = 1.14 co = Atoms('CO', positions=[(0, 0, 0), (0, 0, d)], pbc=True) co.center(vacuum=5.) calc = Vasp(xc='PBE', prec='Low', algo='Fast', ismear=0, sigma=1., istart=0, lwave=False, lcharg=False, ldipol=True) co.calc = calc energy = co.get_potential_energy() forces = co.get_forces() dipole_moment = co.get_dipole_moment() # check that parsing of vasprun.xml file works conf = read('vasprun.xml') assert conf.calc.parameters['kpoints_generation'] assert conf.calc.parameters['sigma'] == 1.0 assert conf.calc.parameters['ialgo'] == 68 assert energy - conf.get_potential_energy() == 0.0 assert np.allclose(conf.get_forces(), forces) assert np.allclose(conf.get_dipole_moment(), dipole_moment, atol=1e-6) # Cleanup calc.clean()
def test_h2of(): with open('def2-svp.gbs', 'w') as bfile: bfile.write(basis) atoms = Atoms('OH2F', positions=[(-1.853788, -0.071113, 0.000000), (-1.892204, 0.888768, 0.000000), (-0.888854, -0.232973, 0.000000), (1.765870, 0.148285, 0.000000)]) label = 'h2of-anion' calc = Gaussian(charge=-1.0, basis='gen', method='B3LYP', basisfile='@def2-svp.gbs/N', label=label, ioplist=['6/80=1', '6/35=4000000'], density='current', addsec=['%s.wfx' % label] ) # FIXME: the "addsec" argument above is correctly incorporated into the # input file, but it doesn't appear to do anything to the calculation. # What is it for? What is it suppsoed to do? atoms.calc = calc atoms.get_potential_energy()
def test_counterions(): """ Test AtomicCounterIon is force/energy consistent over PBCs and with cutoff """ import numpy as np from ase import Atoms from ase import units from ase.calculators.counterions import AtomicCounterIon as ACI sigma = 1.868 * (1.0 / 2.0)**(1.0 / 6.0) epsilon = 0.00277 * units.kcal / units.mol atoms = Atoms('3Na', positions=np.array([[0, 0, -2], [0, 0, 0], [0, 0, 2]])) atoms.cell = [10, 10, 10] atoms.pbc = True atoms.calc = ACI(1, epsilon, sigma, rc=4.5) points = np.arange(-15., 15., 0.2) for p in points: f = atoms.get_forces() fn = atoms.calc.calculate_numerical_forces(atoms, 1e-5) df = (f - fn) assert abs(df).max() < 1e-8
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 _assert_energy_force_stress_equal(calc1, calc2, atoms: Atoms): calc1.reset() atoms.calc = calc1 f1 = atoms.get_forces() e1 = atoms.get_potential_energy() calc2.reset() atoms.calc = calc2 f2 = atoms.get_forces() e2 = atoms.get_potential_energy() assert np.allclose(e1, e2, atol=1e-4, rtol=1e-4) assert np.allclose(f1, f2, atol=1e-5, rtol=1e-5) if np.all(atoms.pbc == np.array([True, True, True])): s1 = atoms.get_stress() s2 = atoms.get_stress() assert np.allclose(s1, s2, atol=1e-5, rtol=1e-5)
def ase_vib(embedder, coords, atomnos, logfunction=None, title='temp'): ''' ''' atoms = Atoms(atomnos, positions=coords) atoms.calc = get_ase_calc(embedder) vib = Vibrations(atoms, name=title) if os.path.isdir(title): os.chdir(title) for f in os.listdir(): os.remove(f) os.chdir(os.path.dirname(os.getcwd())) else: os.mkdir(title) os.chdir(title) t_start = time.perf_counter() with HiddenPrints(): vib.run() # freqs = vib.get_frequencies() freqs = vib.get_energies() * 8065.544 # from eV to cm-1 if logfunction is not None: elapsed = time.perf_counter() - t_start logfunction( f'{title} - frequency calculation completed ({time_to_string(elapsed)})' ) os.chdir(os.path.dirname(os.getcwd())) return freqs, np.count_nonzero(freqs.imag > 1e-3)
def die(): d = 0.9575 t = np.pi / 180 * 104.51 water = Atoms("H2O", positions=[(d, 0, 0), (d * np.cos(t), d * np.sin(t), 0), (0, 0, 0)]) water.calc = ElectronicMinimize(atoms=water, log=True) dyn = LBFGS(water) dyn.run(fmax=0.05)
def test_morse_cluster(internal, order, trajectory=None): rng = np.random.RandomState(4) nat = 4 atoms = Atoms(['Xe'] * nat, rng.normal(size=(nat, 3), scale=3.0)) # parameters from DOI: 10.1515/zna-1987-0505 atoms.calc = MorsePotential(alpha=226.9 * kB, r0=4.73, rho0=4.73 * 1.099) cons = Constraints(atoms) cons.fix_translation() cons.fix_rotation() opt = Sella( atoms, order=order, internal=internal, trajectory=trajectory, gamma=1e-3, constraints=cons, ) opt.run(fmax=1e-3) Ufree = opt.pes.get_Ufree() np.testing.assert_allclose(opt.pes.get_g() @ Ufree, 0, atol=5e-3) opt.pes.diag(gamma=1e-16) H = opt.pes.get_HL().project(Ufree) assert np.sum(H.evals < 0) == order, H.evals
def compareForces(): d = 0.9575 t = np.pi / 180 * 104.51 water = Atoms("H2O", positions=[(d, 0, 0), (d * np.cos(t), d * np.sin(t), 0), (0, 0, 0)], cell=np.eye(3) * 5.0) water.calc = ElectronicMinimize(atoms=water, log=False) print(water.get_forces()) print(water.calc.calculate_numerical_forces(water))
def get_example_adsorbate(type="CO2"): ''' Small function to return CO2 or Cu atoms Parameters: type: str Two adsorbate types - "CO2" and "2Cu". CO2 behaviour during optimisation is unrealistic in EMT. ''' from ase.build import molecule from ase import Atoms if type == "CO2": atoms = molecule("CO2") atoms.rotate(90, 'x') atoms.rotate(50, 'z') elif type == "2Cu": atoms = Atoms("2Cu", positions=[(0, 0, 0), (-4.08 / (2**(1 / 2)), 0, 0)]) # Make the model a bit more technically complete - include a calculator. from ase.calculators.emt import EMT atoms.calc = EMT() return atoms
def eggbox(self, fd, setup='de'): energies = [] for h in [0.16, 0.18, 0.2]: a0 = 16 * h atoms = Atoms(self.symbol, cell=(a0, a0, 2 * a0), pbc=True) if 58 <= self.Z <= 70 or 90 <= self.Z <= 102: M = 999 mixer = {'mixer': Mixer(0.01, 5)} else: M = 333 mixer = {} atoms.calc = GPAW(h=h, xc='PBE', symmetry='off', setups=self.setup, maxiter=M, txt=fd, **mixer) atoms.positions += h / 2 # start with broken symmetry e0 = atoms.get_potential_energy() atoms.positions -= h / 6 e1 = atoms.get_potential_energy() atoms.positions -= h / 6 e2 = atoms.get_potential_energy() atoms.positions -= h / 6 e3 = atoms.get_potential_energy() energies.append(np.ptp([e0, e1, e2, e3])) # print(energies) return energies
def to_labeled_system(self, data, *args, **kwargs): '''Convert System to ASE Atoms object.''' from ase import Atoms from ase.calculators.singlepoint import SinglePointCalculator structures = [] species = [data['atom_names'][tt] for tt in data['atom_types']] for ii in range(data['coords'].shape[0]): structure = Atoms(symbols=species, positions=data['coords'][ii], pbc=not data.get('nopbc', False), cell=data['cells'][ii]) results = { 'energy': data["energies"][ii], 'forces': data["forces"][ii] } if "virials" in data: # convert to GPa as this is ase convention v_pref = 1 * 1e4 / 1.602176621e6 vol = structure.get_volume() results['stress'] = data["virials"][ii] / (v_pref * vol) structure.calc = SinglePointCalculator(structure, **results) structures.append(structure) return structures
def H2Morse(state=0): """Return H2 as a Morse-Potential with calculator attached.""" atoms = Atoms('H2', positions=np.zeros((2, 3))) atoms[1].position[2] = Re[state] atoms.calc = H2MorseCalculator(state=state) atoms.get_potential_energy() return atoms
def test_tip4p(): """Test TIP4P forces.""" from math import cos, sin from ase import Atoms from ase.calculators.tip4p import TIP4P, rOH, angleHOH r = rOH a = angleHOH dimer = Atoms('H2OH2O', [(r * cos(a), 0, r * sin(a)), (r, 0, 0), (0, 0, 0), (r * cos(a / 2), r * sin(a / 2), 0), (r * cos(a / 2), -r * sin(a / 2), 0), (0, 0, 0)]) # tip4p sequence OHH, OHH, .. dimer = dimer[[2]] + dimer[:2] + dimer[[-1]] + dimer[3:5] dimer.positions[3:, 0] += 2.8 dimer.calc = TIP4P(rc=4.0, width=2.0) # put O-O distance in the cutoff range F = dimer.get_forces() print(F) dF = dimer.calc.calculate_numerical_forces(dimer) - F print(dF) assert abs(dF).max() < 2e-6
def build(self, lines: _CHUNK) -> Atoms: """Apply outcar chunk parsers, and build an atoms object""" self.update_parser_headers() # Ensure header is in sync results = self.parse(lines) symbols = self.header['symbols'] constraint = self.header.get('constraint', None) atoms_kwargs = dict(symbols=symbols, constraint=constraint) # Find some required properties in the parsed results. # Raise ParseError if they are not present for prop in ('positions', 'cell'): try: atoms_kwargs[prop] = results.pop(prop) except KeyError: raise ParseError( 'Did not find required property {} during parse.'.format( prop)) atoms = Atoms(**atoms_kwargs) kpts = results.pop('kpts', None) calc = SinglePointDFTCalculator(atoms, **results) if kpts is not None: calc.kpts = kpts calc.name = 'vasp' atoms.calc = calc return atoms
def Al_atom_pair(pair_distance=pair_distance): atoms = Atoms('AlAl', positions=[[-pair_distance / 2, 0, 0], [pair_distance / 2, 0, 0]]) atoms.center(vacuum=10) atoms.calc = EMT() return atoms
def test_lammpslib_small_nonperiodic(): # test that lammpslib handle nonperiodic cases where the cell size # in some directions is small (for example for a dimer). import numpy as np from ase.calculators.lammpslib import LAMMPSlib from ase import Atoms cmds = ["pair_style eam/alloy", "pair_coeff * * NiAlH_jea.eam.alloy Ni H"] lammps = LAMMPSlib(lmpcmds=cmds, atom_types={ 'Ni': 1, 'H': 2 }, log_file='test.log', keep_alive=True) a = 2.0 dimer = Atoms("NiNi", positions=[(0, 0, 0), (a, 0, 0)], cell=(1000 * a, 1000 * a, 1000 * a), pbc=(0, 0, 0)) dimer.calc = lammps energy_ref = -1.10756669119 energy = dimer.get_potential_energy() print("Computed energy: {}".format(energy)) np.testing.assert_allclose(energy, energy_ref, atol=1e-4, rtol=1e-4) forces_ref = np.array([[-0.9420162329811532, 0., 0.], [+0.9420162329811532, 0., 0.]]) forces = dimer.get_forces() print(np.array2string(forces)) np.testing.assert_allclose(forces, forces_ref, atol=1e-4, rtol=1e-4)
def color(gui): a = Atoms('C10', magmoms=np.linspace(1, -1, 10)) a.positions[:] = np.linspace(0, 9, 10)[:, None] a.calc = SinglePointCalculator(a, forces=a.positions) gui.new_atoms(a) c = gui.colors_window() c.toggle('force') text = c.toggle('magmom') assert [button.active for button in c.radio.buttons] == [1, 0, 1, 0, 0, 1] assert text.rsplit('[', 1)[1].startswith('-1.000000,1.000000]')
def optimizeWater(): d = 0.9575 t = np.pi / 180 * 104.51 water = Atoms("H2O", positions=[(d, 0, 0), (d * np.cos(t), d * np.sin(t), 0), (0, 0, 0)], cell=np.eye(3) * 7.0) water.calc = ElectronicMinimize(atoms=water, log=True) water.calc.dragWavefunctions = False # dyn = SciPyFminBFGS(water, callback_always=True) # dyn = BFGSLineSearch(water) # dyn = BFGS(water) # dyn.run(fmax=0.000005, steps = 10) print(water.get_potential_energy() / Hartree)
def get_hydrogen_chain_dielectric_function(NH, NK): a = Atoms('H', cell=[1, 1, 1], pbc=True) a.center() a = a.repeat((1, 1, NH)) a.calc = GPAW(mode=PW(200), kpts={'size': (1, 1, NK), 'gamma': True}, parallel={'band': 1}, dtype=complex, gpts=(10, 10, 10 * NH)) a.get_potential_energy() a.calc.diagonalize_full_hamiltonian(nbands=2 * NH) a.calc.write('H_chain.gpw', 'all') DF = DielectricFunction('H_chain.gpw', ecut=1e-3, hilbert=False, omega2=np.inf, intraband=False) eps_NLF, eps_LF = DF.get_dielectric_function(direction='z') omega_w = DF.get_frequencies() return omega_w, eps_LF
def toatoms(self, attach_calculator=False, add_additional_information=False): """Create Atoms object.""" atoms = Atoms(self.numbers, self.positions, cell=self.cell, pbc=self.pbc, magmoms=self.get('initial_magmoms'), charges=self.get('initial_charges'), tags=self.get('tags'), masses=self.get('masses'), momenta=self.get('momenta'), constraint=self.constraints) if attach_calculator: params = decode(self.get('calculator_parameters', '{}')) atoms.calc = get_calculator(self.calculator)(**params) else: results = {} for prop in all_properties: if prop in self: results[prop] = self[prop] if results: atoms.calc = SinglePointCalculator(atoms, **results) atoms.calc.name = self.calculator if add_additional_information: atoms.info = {} atoms.info['unique_id'] = self.unique_id if self._keys: atoms.info['key_value_pairs'] = self.key_value_pairs data = self.get('data') if data: atoms.info['data'] = data return atoms
def read_old_gpw(filename): from gpaw.io.tar import Reader r = Reader(filename) positions = r.get('CartesianPositions') * Bohr numbers = r.get('AtomicNumbers') cell = r.get('UnitCell') * Bohr pbc = r.get('BoundaryConditions') tags = r.get('Tags') magmoms = r.get('MagneticMoments') energy = r.get('PotentialEnergy') * Hartree if r.has_array('CartesianForces'): forces = r.get('CartesianForces') * Hartree / Bohr else: forces = None atoms = Atoms(positions=positions, numbers=numbers, cell=cell, pbc=pbc) if tags.any(): atoms.set_tags(tags) if magmoms.any(): atoms.set_initial_magnetic_moments(magmoms) magmom = magmoms.sum() else: magmoms = None magmom = None atoms.calc = SinglePointDFTCalculator(atoms, energy=energy, forces=forces, magmoms=magmoms, magmom=magmom) kpts = [] if r.has_array('IBZKPoints'): for w, kpt, eps_n, f_n in zip(r.get('IBZKPointWeights'), r.get('IBZKPoints'), r.get('Eigenvalues'), r.get('OccupationNumbers')): kpts.append(SinglePointKPoint(w, kpt[0], kpt[1], eps_n[0], f_n[0])) atoms.calc.kpts = kpts return atoms
i = LJInteractions({('O', 'O'): (epsilon0, sigma0)}) for calc in [TIP3P(), SimpleQMMM([0, 1, 2], TIP3P(), TIP3P(), TIP3P()), SimpleQMMM([0, 1, 2], TIP3P(), TIP3P(), TIP3P(), vacuum=3.0), EIQMMM([0, 1, 2], TIP3P(), TIP3P(), i), EIQMMM([3, 4, 5], TIP3P(), TIP3P(), i, vacuum=3.0), EIQMMM([0, 1, 2], TIP3P(), TIP3P(), i, vacuum=3.0)]: dimer = Atoms('H2OH2O', [(r * cos(a), 0, r * sin(a)), (r, 0, 0), (0, 0, 0), (r * cos(a / 2), r * sin(a / 2), 0), (r * cos(a / 2), -r * sin(a / 2), 0), (0, 0, 0)]) dimer.calc = calc E = [] F = [] for d in D: dimer.positions[3:, 0] += d - dimer.positions[5, 0] E.append(dimer.get_potential_energy()) F.append(dimer.get_forces()) F = np.array(F) # plt.plot(D, E) F1 = np.polyval(np.polyder(np.polyfit(D, E, 7)), D) F2 = F[:, :3, 0].sum(1) error = abs(F1 - F2).max()
from ase import Atoms from gpaw import GPAW from gpaw.test import equal # Self-consistent calculation: a = 2.5 slab = Atoms('Li', cell=(a, a, 2 * a), pbc=1) slab.calc = GPAW(kpts=(3,3,1), txt='li.txt', parallel=dict(kpt=1)) slab.get_potential_energy() slab.calc.write('Li.gpw') # Gamma point: e1 = slab.calc.get_eigenvalues(kpt=0)[0] # Fix density and continue: kpts = [(0,0,0)] slab.calc.set(fixdensity=True, nbands=5, kpts=kpts, usesymm=None, eigensolver='cg') slab.get_potential_energy() e2 = slab.calc.get_eigenvalues(kpt=0)[0] # Start from gpw-file: calc = GPAW('Li.gpw', fixdensity=True, nbands=5, kpts=kpts,
from ase import Atoms from gpaw import GPAW from gpaw.xc.noncollinear import NonCollinearFunctional, \ NonCollinearLCAOEigensolver, NonCollinearMixer from gpaw.xc import XC a = 2.84 fe = Atoms('Fe2', scaled_positions=[(0, 0, 0), (0.5, 0.5, 0.5)], magmoms=[2.3, 2.3], cell=(a, a, a), pbc=True) k = 4 fe.calc = GPAW(txt='fec.txt', mode='lcao', basis='dz(dzp)', kpts=(k, k, k), convergence=dict(energy=1e-6)) e0 = fe.get_potential_energy() fe.set_initial_magnetic_moments() fe.set_initial_magnetic_moments([(2.3, 0, 0), (2.3, 0, 0)]) fe.calc = GPAW(txt='fenc.txt', mode='lcao', basis='dz(dzp)', kpts=(k, k, k), convergence=dict(energy=1e-6), usesymm=False, xc=NonCollinearFunctional(XC('LDA')), mixer=NonCollinearMixer(), eigensolver=NonCollinearLCAOEigensolver()) e = fe.get_potential_energy() assert abs(e - e0) < 7e-5
from gpaw.xc.hybridg import HybridXC a = 2.0 li = Atoms("Li", cell=(a, a, a), pbc=1) for spinpol in [False, True]: for usesymm in [True, False, None]: if size == 8 and not spinpol and usesymm: continue for qparallel in [False, True]: if rank == 0: print (spinpol, usesymm, qparallel) li.calc = GPAW( mode=PW(300), kpts=(2, 3, 4), spinpol=spinpol, usesymm=usesymm, parallel={"band": 1}, txt=None, idiotproof=False, ) e = li.get_potential_energy() if qparallel: li.calc.write("li", mode="all") calc = GPAW("li", txt=None, communicator=serial_comm) else: calc = li.calc exx = HybridXC("EXX", logfilename=None, method="acdf") de = calc.get_xc_difference(exx) exx = HybridXC("EXX", logfilename=None, method="acdf", bandstructure=True, bands=[0, 1]) de2 = calc.get_xc_difference(exx) kd = calc.wfs.kd
# creates: ase-db.out, ase-db-long.out import ase.db c = ase.db.connect('abc.db') from ase import Atoms from ase.calculators.emt import EMT h2 = Atoms('H2', [(0, 0, 0), (0, 0, 0.7)]) h2.calc = EMT() h2.get_forces() c.write(h2, relaxed=False) from ase.optimize import BFGS BFGS(h2).run(fmax=0.01) c.write(h2, relaxed=True, data={'abc': [1, 2, 3]}) for d in c.select('molecule'): print(d.forces[0, 2], d.relaxed) h = Atoms('H') h.calc = EMT() h.get_potential_energy() c.write(h) import subprocess with open('ase-db.out', 'w') as fd: fd.write('$ ase-db abc.out\n') output = subprocess.check_output(['ase-db', 'abc.db']) fd.write(output) with open('ase-db-long.out', 'w') as fd: fd.write('$ ase-db abc.out relaxed=1 -l\n')
c = {"energy": 0.001, "eigenstates": 1, "density": 1} d = 0.75 gen("H", xcname="PBEsol") for xc, E0, dE0 in [("mBEEF", 4.86, 0.16), ("BEEF-vdW", 5.13, 0.20), ("mBEEF-vdW", 4.74, 0.36)]: print(xc) if not newlibxc and xc[0] == "m": print("Skipped") continue # H2 molecule: h2 = Atoms("H2", [[0, 0, 0], [0, 0, d]]) h2.center(vacuum=2) h2.calc = GPAW(txt="H2-" + xc + ".txt", convergence=c) h2.get_potential_energy() h2.calc.set(xc=xc) h2.get_potential_energy() h2.get_forces() ens = BEEFEnsemble(h2.calc) e_h2 = ens.get_ensemble_energies() # H atom: h = Atoms("H", cell=h2.cell, magmoms=[1]) h.center() h.calc = GPAW(txt="H-" + xc + ".txt", convergence=c) h.get_potential_energy() h.calc.set(xc=xc) h.get_potential_energy() ens = BEEFEnsemble(h.calc)
(0.0000, 0.0000, -1.1560)]), 'Be2': ('Be2', [(0.0000, 0.0000, 0.0000), (0.0000, 0.0000, 2.460)])} c = ase.db.connect('results.db') for name in ex_atomization.keys() + 'H Li Be B C N O F Cl P'.split(): id = c.reserve(name=name) if id is None: continue if name in extra: a = Atoms(*extra[name]) else: a = molecule(name) if name in bondlengths: a.set_distance(0, 1, bondlengths[name]) a.cell = [11, 12, 13] a.center() a.calc = GPAW(xc='PBE', mode=PW(500), txt=name + '.txt', dtype=complex) a.get_potential_energy() exx = EXX(a.calc) exx.calculate() eexx = exx.get_total_energy() c.write(a, name=name, exx=eexx) del c[id]
from ase import Atoms from gpaw import GPAW, PW h = Atoms('H', cell=(5, 5, 5)) h.center() h.calc = GPAW(setups='ae', txt='H.ae.txt') for ecut in range(200, 1001, 100): h.calc.set(mode=PW(ecut)) e = h.get_potential_energy()
a = 4.23 / 2.0 a1 = Atoms('Na', scaled_positions=[[0, 0, 0]], cell=(a, a, a), pbc=True) # Expanding along x-direction a2 = Atoms('Na2', scaled_positions=[[0, 0, 0], [0.5, 0, 0]], cell=(2 * a, a, a), pbc=True) a1.calc = GPAW(gpts=(10, 10, 10), mode=PW(300), kpts={'size': (8, 8, 8), 'gamma': True}, parallel={'band': 1}, txt='small.txt') # Kpoint sampling should be halved in the expanded direction. a2.calc = GPAW(gpts=(20, 10, 10), mode=PW(300), kpts={'size': (4, 8, 8), 'gamma': True}, parallel={'band': 1}, txt='large.txt') a1.get_potential_energy() a2.get_potential_energy() # Use twice as many bands for expanded structure a1.calc.diagonalize_full_hamiltonian(nbands=20)
from gpaw.mpi import rank, size, serial_comm from gpaw.xc.hybridg import HybridXC a = 2.0 li = Atoms('Li', cell=(a, a, a), pbc=1) for spinpol in [False, True]: for symm in [{}, 'off', {'time_reversal': False, 'point_group': False}]: if size == 8 and not spinpol and symm == {}: continue for qparallel in [False, True]: if rank == 0: print((spinpol, symm, qparallel)) li.calc = GPAW(mode=PW(300), kpts=(2, 3, 4), spinpol=spinpol, symmetry=symm, parallel={'band': 1}, txt=None, idiotproof=False) e = li.get_potential_energy() if qparallel: li.calc.write('li', mode='all') calc = GPAW('li', txt=None, communicator=serial_comm) else: calc = li.calc exx = HybridXC('EXX', logfilename=None, method='acdf') de = calc.get_xc_difference(exx) exx = HybridXC('EXX', logfilename=None,
"""Test TIP3P forces.""" from math import cos, sin, pi from ase import Atoms from ase.calculators.tip3p import TIP3P, rOH, angleHOH from ase.calculators.tip4p import TIP4P r = rOH a = angleHOH * pi / 180 dimer = Atoms('H2OH2O', [(r * cos(a), 0, r * sin(a)), (r, 0, 0), (0, 0, 0), (r * cos(a / 2), r * sin(a / 2), 0), (r * cos(a / 2), -r * sin(a / 2), 0), (0, 0, 0)]) dimer = dimer[[2, 0, 1, 5, 3, 4]] dimer.positions[3:, 0] += 2.8 for TIPnP in [TIP3P, TIP4P]: # put O-O distance in the cutoff range dimer.calc = TIPnP(rc=4.0, width=2.0) F = dimer.get_forces() print(F) dF = dimer.calc.calculate_numerical_forces(dimer) - F print(dF) assert abs(dF).max() < 2e-6
from ase import Atoms from gpaw import GPAW from gpaw.xc.noncollinear import NonCollinearFunctional, \ NonCollinearLCAOEigensolver, NonCollinearMixer from gpaw.xc import XC h = Atoms('H', magmoms=[1]) h.center(vacuum=2) h.calc = GPAW(txt='c.txt', mode='lcao', basis='dz(dzp)', h=0.25) e0 = h.get_potential_energy() h.set_initial_magnetic_moments() h.set_initial_magnetic_moments([(0.1, 0.2, 0.3)]) h.calc = GPAW(txt='nc.txt', mode='lcao', basis='dz(dzp)', h=0.25, xc=NonCollinearFunctional(XC('LDA')), mixer=NonCollinearMixer(), eigensolver=NonCollinearLCAOEigensolver()) e = h.get_potential_energy() assert abs(e - e0) < 2e-5, (e, e0) from ase.io import write write('h.traj', h)
from ase import Atoms from gpaw import GPAW, PW, FermiDirac # Setup up bulk NiO in an antiferromagnetic configuration: a = 4.19 # lattice constants b = a / 2**0.5 m = 2.0 atoms = Atoms('Ni2O2', pbc=True, cell=(b, b, a), positions=[(0, 0, 0), (b / 2, b / 2, a / 2), (0, 0, a / 2), (b / 2, b / 2, 0)], magmoms=[m, -m, 0, 0]) k = 2 # number of k-points atoms.calc = GPAW(mode=PW(400), occupations=FermiDirac(width=0.05), setups={'Ni': ':d,6.0'}, # U=6 eV for Ni d orbitals txt='nio.txt', kpts=(k, k, k), xc='PBE') e = atoms.get_potential_energy()
from ase import Atoms from gpaw import GPAW from gpaw.mpi import world, serial_comm a = Atoms('H', cell=(1, 3, 3), pbc=1) a.calc = GPAW(mode='pw', h=0.15, kpts=(4, 1, 1), basis='dzp', nbands=4, eigensolver='rmm-diis', txt=None) a.get_potential_energy() w1 = a.calc.get_pseudo_wave_function(0, 1) e1 = a.calc.get_eigenvalues(1) a.calc.write('H') if world.size <= 2: scalapack = None else: mb = world.size // 4 scalapack = (2, world.size // 4, 32) a.calc.diagonalize_full_hamiltonian(nbands=100, scalapack=scalapack) w2 = a.calc.get_pseudo_wave_function(0, 1) e2 = a.calc.get_eigenvalues(1)
from ase import Atoms from gpaw import GPAW from gpaw.mpi import world, serial_comm a = Atoms('H2', [(0, 0, 0), (0, 0, 0.74)], cell=(3, 3, 3), pbc=1) a.calc = GPAW(mode='pw', eigensolver='rmm-diis', nbands=8, dtype=complex, basis='dzp', txt=None) a.get_potential_energy() w1 = a.calc.get_pseudo_wave_function(0) e1 = a.calc.get_eigenvalues() a.calc.write('H2') if world.size == 1: scalapack = None else: scalapack = (2, world.size // 2, 32) a.calc.diagonalize_full_hamiltonian(nbands=120, scalapack=scalapack) w2 = a.calc.get_pseudo_wave_function(0) e2 = a.calc.get_eigenvalues() calc = GPAW('H2', txt=None)
from ase import Atoms from gpaw import GPAW, FermiDirac, Mixer #from gpaw.xc.noncolinear import NonColinearLDA, NonColinearLCAOEigensolver, \ # NonColinearMixer h = Atoms('H', magmoms=[1]) h.center(vacuum=2) xc = 'LDA' c = GPAW(txt='c.txt', mode='lcao', basis='dz(dzp)', #setups='ncpp', h=0.25, xc=xc, #occupations=FermiDirac(0.01), mixer=Mixer(), #noncolinear=[(2,0,0)], )#eigensolver=NonColinearLCAOEigensolver()) c.set(nbands=1) h.calc = c h.get_potential_energy()
from math import log from ase import Atoms from ase.units import Bohr from gpaw import GPAW, FermiDirac from gpaw.test import equal a = 4.0 h = 0.2 hydrogen = Atoms('H', [(a / 2, a / 2, a / 2)], cell=(a, a, a)) hydrogen.calc = GPAW(h=h, nbands=1, convergence={'energy': 1e-7}) e1 = hydrogen.get_potential_energy() equal(e1, 0.526939, 0.001) dens = hydrogen.calc.density c = dens.gd.find_center(dens.nt_sG[0]) * Bohr equal(abs(c - a / 2).max(), 0, 1e-13) kT = 0.001 hydrogen.calc.set(occupations=FermiDirac(width=kT)) e2 = hydrogen.get_potential_energy() equal(e1, e2 + log(2) * kT, 3.0e-7)
from ase import Atoms from ase.units import Bohr from gpaw.jellium import JelliumSurfacePoissonSolver from gpaw import GPAW, Mixer rs = 5.0 * Bohr # Wigner-Seitz radius h = 0.2 # grid-spacing a = 8 * h # lattice constant v = 3 * a # vacuum L = 10 * a # thickness k = 12 # number of k-points (k*k*1) ne = a**2 * L / (4 * np.pi / 3 * rs**3) ps = JelliumSurfacePoissonSolver(z1=v, z2=v + L) surf = Atoms(pbc=(True, True, False), cell=(a, a, v + L + v)) surf.calc = GPAW(poissonsolver=ps, xc='LDA_X+LDA_C_WIGNER', eigensolver='dav', charge=-ne, kpts=[k, k, 1], h=h, maxiter=300, convergence={'density': 0.001}, mixer=Mixer(0.03, 7, 100), nbands=int(ne / 2) + 15, txt='surface.txt') e = surf.get_potential_energy() surf.calc.write('surface.gpw')
from gpaw.test import equal a = 5.0 d = 1.0 x = d / 3**0.5 atoms = Atoms([Atom('C', (0.0, 0.0, 0.0)), Atom('H', (x, x, x)), Atom('H', (-x, -x, x)), Atom('H', (x, -x, -x)), Atom('H', (-x, x, -x))], cell=(a, a, a), pbc=False) atoms.positions[:] += a / 2 calc = GPAW(h=0.25, nbands=4, convergence={'eigenstates': 7.8e-10}) atoms.calc = calc energy = atoms.get_potential_energy() niter = calc.get_number_of_iterations() # The three eigenvalues e[1], e[2], and e[3] must be degenerate: e = calc.get_eigenvalues() print(e[1] - e[3]) equal(e[1], e[3], 9.3e-8) energy_tolerance = 0.0003 niter_tolerance = 0 equal(energy, -23.6277, energy_tolerance) # Calculate non-selfconsistent PBE eigenvalues: from gpaw.xc.tools import vxc epbe0 = e - vxc(calc)[0, 0] + vxc(calc, 'PBE')[0, 0]
import numpy as np from ase import Atoms from ase.units import Bohr from gpaw.jellium import JelliumPoissonSolver from gpaw import GPAW rs = 5.0 * Bohr # Wigner-Seitz radius h = 0.2 # grid-spacing a = 8 * h # lattice constant k = 12 # number of k-points (k*k*k) ne = a**3 / (4 * np.pi / 3 * rs**3) bulk = Atoms(pbc=True, cell=(a, a, a)) bulk.calc = GPAW(poissonsolver=JelliumPoissonSolver(), xc='LDA_X+LDA_C_WIGNER', charge=-ne, nbands=5, kpts=[k, k, k], h=h, txt='bulk.txt') e0 = bulk.get_potential_energy()
S. Suhai: *Electron correlation in extended systems: Fourth-order many-body perturbation theory and density-functional methods applied to an infinite chain of hydrogen atoms*, Phys. Rev. B 50, 14791-14801 (1994) """ import numpy as np from ase import Atoms from gpaw import GPAW, FermiDirac k = 8 a = 6.0 d0 = 1.0 h2 = Atoms('H2', cell=(2 * d0, a, a), pbc=True, positions=[(0, 0, 0), (d0 + 0.1, 0, 0)]) h2.center(axis=1) h2.center(axis=2) h2.calc = GPAW(kpts=(k, 1, 1), usesymm=False, occupations=FermiDirac(0.01), txt='h2c.txt') for d in np.linspace(0.0, 0.4, 21): h2[1].x = d0 + d e = h2.get_potential_energy() h2.calc.write('h2c-%.2f.gpw' % d)
from ase import Atoms from gpaw import GPAW n = Atoms('N', magmoms=[3]) n.center(vacuum=3.5) # Calculation with no +U correction: n.calc = GPAW(mode='lcao', basis='dzp', txt='no_u.txt', xc='PBE') e1 = n.get_potential_energy() # Calculation with a correction U=6 eV normalized: n.calc.set(setups={'N': ':p,6.0'}, txt='normalized_u.txt') e2 = n.get_potential_energy() # Calculation with a correction U=6 eV not normalized: n.calc.set(setups={'N': ':p,6.0,0'}, txt='not_normalized_u.txt') e3 = n.get_potential_energy()