Beispiel #1
0
def test_ace():
    label = "test"
    mol = Atoms('H2', [(0, 0, 0), (0, 0, 0.7)])
    basic = [dict(Cell='5.0')]
    ace = ACE(label=label, BasicInformation=basic)
    mol.calc = ace
    mol.get_forces()
Beispiel #2
0
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
Beispiel #3
0
def test_ace():
    import os
    import unittest

    from ase import Atoms
    from ase.calculators.acemolecule import ACE

    label = "test"
    mol = Atoms('H2',[(0, 0, 0),(0, 0, 0.7)])
    basic = [dict(Cell= '5.0')]
    if "ASE_ACE_COMMAND" not in os.environ:
        raise unittest.SkipTest('$ASE_ACE_COMMAND not defined') 
    ace = ACE(label=label, BasicInformation=basic)
    mol.set_calculator(ace)
    mol.get_forces()
Beispiel #4
0
def read_images(filename, state_number=None, mode=None):
    f = open(filename, 'r')
    atoms = []
    ener = []
    cycle = -1
    while True:
        elements = []
        positions = []
        forces = []
        line = f.readline()
        if not line:
            break
        if cycle == -1:
            atom_numb = int(line.split()[0])
        line = f.readline()
        ener.append(float(line.split()[0]))
        #read one particular structure assinged by state_number
        if state_number is not None:
            if cycle == state_number:
                for i in range(atom_numb):
                    line = f.readline()
                    fields = line.split()
                    elements.append(fields[0])
                    positions.append([float(fields[j + 1]) for j in range(3)])
                elements = np.array(elements)
                positions = np.array(positions)
                return Atoms(elements, positions=positions)
            else:
                for i in range(atom_numb):
                    f.readline()
        else:
            for i in range(atom_numb):
                line = f.readline()
                fields = line.split()
                elements.append(fields[0])
                positions.append([float(fields[j + 1]) for j in range(3)])
                forces.append([float(fields[j + 1]) for j in range(3, 6)])
            elements = np.array(elements)
            positions = np.array(positions)
            p = Atoms(elements, positions=positions)
            calc = force_setter()
            p.set_calculator(calc)
            print p.get_potential_energy()
            print p.get_forces()
            atoms.append(p)
        cycle += 1
    f.close()
    return atoms
Beispiel #5
0
def test_tipnp():
    """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
Beispiel #6
0
def run(calc, phonon, config_type, disp):
    supercells = phonon.get_supercells_with_displacements()
    # Force calculations by calculator
    set_of_forces = []
    for (i, scell) in enumerate(supercells):
        ##########
        at = Atoms(symbols=scell.get_chemical_symbols(),
                   scaled_positions=scell.get_scaled_positions(),
                   cell=scell.get_cell(),
                   pbc=True)

        at.set_calculator(calc)

        energy = at.get_potential_energy(force_consistent=True)
        forces = at.get_forces()
        stress = at.get_stress(voigt=False)

        drift_force = forces.sum(axis=0)
        print(("[Phonopy] Drift force:" + "%11.5f" * 3) % tuple(drift_force))
        # Simple translational invariance
        for force in forces:
            force -= drift_force / forces.shape[0]

        at.arrays["force"] = forces
        at.info["virial"] = -1.0 * at.get_volume() * stress
        at.info["energy"] = energy

        write("./Ti_{}_{}_scell2.xyz".format(config_type, disp), at)
        #write("{}_scell.xyz".format(i), at)
        set_of_forces.append(forces)
    return set_of_forces
def test_relax_co_ase_interactive_bfgs(tmpdir):

    tmpdir.chdir()

    co = Atoms('CO', [[2.256 * Bohr, 0.0, 0.0], [0.0, 0.0, 0.0]])
    co.set_cell(np.ones(3) * 12.0 * Bohr)

    calc = iEspresso(pw=24.0 * Rydberg,
                     dw=144.0 * Rydberg,
                     kpts='gamma',
                     xc='PBE',
                     calculation='relax',
                     ion_dynamics='ase3',
                     spinpol=False,
                     outdir='qe_ase_interactive_bfgs')

    co.set_calculator(calc)

    minimizer = BFGS(co, logfile='minimizer.log', trajectory='relaxed.traj')
    minimizer.run(fmax=0.01)

    ref_ene = -616.9017404193379

    ref_pos = np.array([[1.19233393e+00, 0.0e+00, 0.00000000e+00],
                        [1.48996586e-03, 0.00000000e+00, 0.00000000e+00]])

    ref_for = np.array([[0.00162288, 0.0, 0.0],
                        [-0.00162288, 0.0, 0.0]])

    assert np.allclose(co.get_potential_energy(), ref_ene)
    #assert np.allclose(co.positions, ref_pos)
    #assert np.allclose(co.get_forces(), ref_for)

    print(co.positions)
    print(co.get_forces())
Beispiel #8
0
def main():
    if sys.version_info < (2, 7):
        raise NotAvailable('read_xml requires Python version 2.7 or greater')

    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)

    co.set_calculator(calc)
    energy = co.get_potential_energy()
    forces = co.get_forces()

    # 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 array_almost_equal(conf.get_forces(), forces, tol=1e-4)

    # Cleanup
    calc.clean()
Beispiel #9
0
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))
Beispiel #10
0
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
Beispiel #11
0
def phonons(model, bulk, supercell, dx, mesh=None, points=None, n_points=50):

    import model

    unitcell = PhonopyAtoms(symbols=bulk.get_chemical_symbols(),
                            cell=bulk.get_cell(),
                            scaled_positions=bulk.get_scaled_positions())
    phonon = Phonopy(unitcell, supercell)
    phonon.generate_displacements(distance=dx)

    sets_of_forces = []

    for s in phonon.get_supercells_with_displacements():
        at = Atoms(cell=s.get_cell(),
                   symbols=s.get_chemical_symbols(),
                   scaled_positions=s.get_scaled_positions(),
                   pbc=3 * [True])
        at.set_calculator(model.calculator)
        sets_of_forces.append(at.get_forces())

    phonon.set_forces(sets_of_forces=sets_of_forces)
    phonon.produce_force_constants()

    properties = {}

    if mesh is not None:
        phonon.set_mesh(mesh, is_gamma_center=True)
        qpoints, weights, frequencies, eigvecs = phonon.get_mesh()

        properties["frequencies"] = frequencies.tolist()
        properties["weights"] = weights.tolist()

    if points is not None:
        bands = []
        for i in range(len(points) - 1):
            band = []
            for r in np.linspace(0, 1, n_points):
                band.append(points[i] + (points[i + 1] - points[i]) * r)
            bands.append(band)

        phonon.set_band_structure(bands,
                                  is_eigenvectors=True,
                                  is_band_connection=False)
        band_q_points, band_distances, band_frequencies, band_eigvecs = phonon.get_band_structure(
        )

        band_distance_max = np.max(band_distances)
        band_distances = [(_b / band_distance_max).tolist()
                          for _b in band_distances]

        band_frequencies = [_b.tolist() for _b in band_frequencies]

        properties["band_q_points"] = band_q_points
        properties["band_distances"] = band_distances
        properties["band_frequencies"] = band_frequencies
        properties["band_eigvecs"] = band_eigvecs

    properties["phonopy"] = phonon

    return properties
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
Beispiel #13
0
        def calc_force(iscell):
            scell = supercells[iscell]
            cell = Atoms(symbols=scell.get_chemical_symbols(),
                         scaled_positions=scell.get_scaled_positions(),
                         cell=scell.get_cell(),
                         pbc=True)
            if is_mag:
                cell.set_initial_magnetic_moments(sc_mag)
            cell.set_calculator(copy.deepcopy(calc))
            dir_name = "PHON_CELL%s" % iscell
            cur_dir = os.getcwd()
            if not os.path.exists(dir_name):
                os.mkdir(dir_name)
            if prepare_initial_wavecar:
                os.system('ln -s %s %s' %
                          (os.path.abspath("SUPERCELL0/WAVECAR"),
                           os.path.join(dir_name, 'WAVECAR')))

            os.chdir(dir_name)
            forces = cell.get_forces()
            print("[Phonopy] Forces: %s" % forces)
            # Do something other than calculating the forces with func.
            # func: func(atoms, calc, func_args)
            if func is not None:
                func(cell, calc, **func_args)
            os.chdir(cur_dir)
            drift_force = forces.sum(axis=0)
            print("[Phonopy] Drift force:", "%11.5f" * 3 % tuple(drift_force))
            # Simple translational invariance
            for force in forces:
                force -= drift_force / forces.shape[0]
            return forces
Beispiel #14
0
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)
Beispiel #15
0
def test_relax_co_ase_bfgs(tmpdir):

    tmpdir.chdir()

    co = Atoms('CO', [[2.256 * Bohr, 0.0, 0.0], [0.0, 0.0, 0.0]])
    co.set_cell(np.ones(3) * 12.0 * Bohr)

    calc = Espresso(pw=24.0 * Rydberg,
                    dw=144.0 * Rydberg,
                    kpts='gamma',
                    xc='PBE',
                    calculation='scf',
                    ion_dynamics=None,
                    spinpol=False,
                    outdir='qe_ase_bfgs')

    co.set_calculator(calc)

    minimizer = BFGS(co, logfile='minimizer.log', trajectory='relaxed.traj')
    minimizer.run(fmax=0.01)

    print('ase(scf) bfgs:')
    print('energy: ', co.get_potential_energy())
    print('positions: ', co.positions)
    print('forces: ', co.get_forces())
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)
Beispiel #17
0
def main():
    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.set_calculator(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()
Beispiel #18
0
def test_h2():
    from ase import Atoms
    from ase.calculators.emt import EMT

    h2 = Atoms('H2', positions=[(0, 0, 0), (0, 0, 1.1)], calculator=EMT())
    f1 = h2.calc.calculate_numerical_forces(h2, 0.0001)
    f2 = h2.get_forces()
    assert abs(f1 - f2).max() < 1e-6
 def test_ase(self):
     from ase import Atoms
     from deepmd.calculator import DP
     water0 = Atoms('OHHOHH',
                    positions=self.coords.reshape((-1, 3)),
                    cell=self.box.reshape((3, 3)),
                    calculator=DP(FROZEN_MODEL))
     water1 = Atoms('OHHOHH',
                    positions=self.coords.reshape((-1, 3)),
                    cell=self.box.reshape((3, 3)),
                    calculator=DP(COMPRESSED_MODEL))
     ee0 = water0.get_potential_energy()
     ff0 = water0.get_forces()
     ee1 = water1.get_potential_energy()
     ff1 = water1.get_forces()
     nframes = 1
     np.testing.assert_almost_equal(ff0, ff1, default_places)
     np.testing.assert_almost_equal(ee0, ee1, default_places)
Beispiel #20
0
    def testANIDataset(self):
        builtin = torchani.neurochem.Builtins()
        calculator = torchani.ase.Calculator(builtin.species,
                                             builtin.aev_computer,
                                             builtin.models,
                                             builtin.energy_shifter)
        default_neighborlist_calculator = torchani.ase.Calculator(
            builtin.species, builtin.aev_computer, builtin.models,
            builtin.energy_shifter, True)
        nnp = torch.nn.Sequential(builtin.aev_computer, builtin.models,
                                  builtin.energy_shifter)
        for i in range(N):
            datafile = os.path.join(path, 'test_data/ANI1_subset/{}'.format(i))
            with open(datafile, 'rb') as f:
                coordinates, species, _, _, _, _ = pickle.load(f)
                coordinates = coordinates[0]
                species = species[0]
                species_str = [builtin.consts.species[i] for i in species]

                atoms = Atoms(species_str, positions=coordinates)
                atoms.set_calculator(calculator)
                energy1 = atoms.get_potential_energy() / units.Hartree
                forces1 = atoms.get_forces() / units.Hartree

                atoms2 = Atoms(species_str, positions=coordinates)
                atoms2.set_calculator(default_neighborlist_calculator)
                energy2 = atoms2.get_potential_energy() / units.Hartree
                forces2 = atoms2.get_forces() / units.Hartree

                coordinates = torch.tensor(coordinates,
                                           requires_grad=True).unsqueeze(0)
                _, energy3 = nnp(
                    (torch.from_numpy(species).unsqueeze(0), coordinates))
                forces3 = -torch.autograd.grad(energy3.squeeze(),
                                               coordinates)[0].numpy()
                energy3 = energy3.item()

                self.assertLess(abs(energy1 - energy2), tol)
                self.assertLess(abs(energy1 - energy3), tol)

                diff_f12 = torch.tensor(forces1 - forces2).abs().max().item()
                self.assertLess(diff_f12, tol)
                diff_f13 = torch.tensor(forces1 - forces3).abs().max().item()
                self.assertLess(diff_f13, tol)
Beispiel #21
0
def main():
    if sys.version_info < (2, 7):
        raise NotAvailable('read_xml requires Python version 2.7 or greater')

    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='LDA',
                prec='Low',
                algo='Fast',
                ismear=0,
                sigma=1.,
                nbands=12,
                istart=0,
                nelm=3,
                lwave=False,
                lcharg=False,
                ldipol=True)

    co.set_calculator(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

    # Check some arrays
    assert np.allclose(conf.get_forces(), forces)
    assert np.allclose(conf.get_dipole_moment(), dipole_moment, atol=1e-6)

    # Check k-point-dependent properties
    assert len(conf.calc.get_eigenvalues(spin=0)) >= 12
    assert conf.calc.get_occupation_numbers()[2] == 2
    assert conf.calc.get_eigenvalues(spin=1) is None
    kpt = conf.calc.get_kpt(0)
    assert kpt.weight == 1.

    # Perform a spin-polarised calculation
    co.calc.set(ispin=2, ibrion=-1)
    co.get_potential_energy()
    conf = read('vasprun.xml')
    assert len(conf.calc.get_eigenvalues(spin=1)) >= 12
    assert conf.calc.get_occupation_numbers(spin=1)[0] == 1.

    # Cleanup
    calc.clean()
Beispiel #22
0
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))
Beispiel #23
0
def generate_images():
    '''Generates five images with varying configurations'''

    images = []
    for step in range(5):
        image = Atoms([
            Atom('Pd', (0., 0., 0.)),
            Atom('O', (0., 2., 0.)),
            Atom('Pd', (0., 0., 3.)),
            Atom('Pd', (1., 0., 0.))
        ])
        if step > 0:
            image[step - 1].position =  \
                image[step - 1].position + np.array([0., 1., 1.])

        image.set_calculator(EMT())
        image.get_potential_energy(apply_constraint=False)
        image.get_forces(apply_constraint=False)
        images.append(image)

    return images
Beispiel #24
0
    def _get_phono3pyobject_phono3py(self, structure, potential,
                                     kpoint_density,
                                     displacementdistancephono3py,
                                     max_distance_third_order):
        cell = get_phonopy_structure(structure)

        kpoint = Kpoints.automatic_density(structure=structure,
                                           kppa=kpoint_density,
                                           force_gamma=True)
        mesh = kpoint.kpts[0]
        phono3py = Phono3py(cell,
                            self.smat,
                            primitive_matrix=[[1, 0., 0.], [0., 1, 0.],
                                              [0., 0., 1]],
                            mesh=mesh,
                            log_level=1)

        phono3py.generate_displacements(
            distance=displacementdistancephono3py,
            cutoff_pair_distance=max_distance_third_order)
        scells_with_disps = phono3py.get_supercells_with_displacements()

        disp_dataset = phono3py.get_displacement_dataset()
        numatoms = len(scells_with_disps[0].get_scaled_positions())
        dummy_force = np.zeros((numatoms, 3))

        set_of_forces = []
        for scell in scells_with_disps:
            if scell is not None:
                # this part is adapted from: https://web.archive.org/web/20200610084959/https://github.com/phonopy/phonopy/blob/develop/example/ase/8Si-phonon.py
                # Copyright by Atsushi Togo
                cell = Atoms(symbols=scell.get_chemical_symbols(),
                             scaled_positions=scell.get_scaled_positions(),
                             cell=scell.get_cell(),
                             pbc=True)
                cell.set_calculator(potential)
                forces = cell.get_forces()
                drift_force = forces.sum(axis=0)
                print(("[Phonopy] Drift force:" + "%11.5f" * 3) %
                      tuple(drift_force))
                for force in forces:
                    force -= drift_force / forces.shape[0]
                set_of_forces.append(forces)
            else:
                set_of_forces.append(dummy_force)
        phono3py.produce_fc3(set_of_forces,
                             displacement_dataset=disp_dataset,
                             symmetrize_fc3r=True)

        fc3 = phono3py.get_fc3()

        show_drift_fc3(fc3)
        return phono3py
Beispiel #25
0
def test_aic():
    """Test Atomic Counter Ion calc forces."""
    import numpy as np
    from ase import Atoms
    from ase.calculators.counterions import AtomicCounterIon as ACI

    atoms = Atoms('2Na', positions=np.array([[0, 0, 0], [0, 0, 4]]))

    atoms.calc = ACI(1, 1.6642, 0.0001201186, rc=4.5)
    f = atoms.get_forces()
    df = atoms.calc.calculate_numerical_forces(atoms, 1e-6) - f
    print(df)
    assert abs(df).max() < 2e-6
Beispiel #26
0
    def prepare_slab_opt(self, slab: Atoms) -> None:
        ''' Prepare slab optimization with Quantum Espresso '''

        balsamcalc_module = __import__('pynta.balsamcalc',
                                       fromlist=[self.socket_calculator])

        sock_calc = getattr(balsamcalc_module, self.socket_calculator)

        # n_kpts = IO().get_kpoints(self.repeats_surface)

        job_kwargs = self.balsam_exe_settings.copy()
        extra_calc_keywords = self.calc_keywords.copy()
        # add kpoints and distribute it among nodes = n_kpts
        # extra_calc_keywords['kpts'] = self.repeats_surface
        # extra_calc_keywords['job_args'] = '-nk {}'.format(n_kpts)
        # change how k-points are distrubuted among nodes
        # job_kwargs.update([('num_nodes', n_kpts)])

        slab.pbc = (True, True, False)

        if self.socket_calculator == 'EspressoBalsamSocketIO':
            slab.calc = sock_calc(workflow='QE_Socket',
                                  job_kwargs=job_kwargs,
                                  pseudopotentials=self.pseudopotentials,
                                  pseudo_dir=self.pseudo_dir,
                                  **extra_calc_keywords)
        else:
            slab.calc = sock_calc(workflow='QE_Socket',
                                  job_kwargs=job_kwargs,
                                  **extra_calc_keywords)

        fname = os.path.join(self.creation_dir, self.slab_name)

        opt = BFGSLineSearch(atoms=slab, trajectory=fname + '.traj')
        opt.run(fmax=0.01)
        slab.get_potential_energy()
        slab.get_forces()
        slab.calc.close()
        write(fname + '.xyz', slab)
Beispiel #27
0
def run_dimers(dbfile, DftCalc, atomic_energies, element1, element2,
               minfrac=0.15, maxfrac=0.7, stepfrac=0.05, minE=5.):
    ''' Adds a dimer curve (with DFT energies and forces) for
    the given element pair to a database.

    dbfile: name of the database
    DftCalc: suitable DFT calculator class (see tango.main)
    atomic_energies: reference DFT energies of the separate atoms
    element1: symbol of the first element 
    element2: symbol of the second element
    minfrac, maxfrac, stepfrac: specifies the minimal and maximal
         dimer distances (and the spacing) in units of the sum of
         covalent radii
    minE: dimer distances where the dimer energy is less than minE
          above the sum of the reference energies are omitted
    '''
    positions = np.array([[6.] * 3, [8., 6., 6.]])
    atoms = Atoms(element1 + element2, cell=[12.] * 3,
                  positions=positions, pbc=True)

    calc = DftCalc(atoms, kpts=(1,1,1), run_type='dimer')

    db = connect(dbfile)
    num1 = atomic_numbers[element1]
    num2 = atomic_numbers[element2]
    e_ref = [atomic_energies['%s_DFT' % e] for e in [element1, element2]]
    crsum = covalent_radii[num1] + covalent_radii[num2]
    r = minfrac * crsum

    while True:
        if r * 1. / crsum > maxfrac:
            break

        positions[1, 0] = 6. + r
        atoms.set_positions(positions)
        atoms.set_calculator(calc)
        E = atoms.get_potential_energy()
        F = atoms.get_forces()

        if E - sum(e_ref) > minE:
            atoms.info['key_value_pairs'] = {}
            atoms.info['key_value_pairs']['e_dft_ref'] = convert_array(e_ref)
            atoms.info['key_value_pairs']['f_dft_ref'] = 0.
            finalize(atoms, energy=E, forces=F)
            db.write(atoms, r=r, **atoms.info['key_value_pairs'])
            r += stepfrac * crsum
        else:
            break

    calc.exit()
    return
Beispiel #28
0
def read_images(filename, state_number=None, mode=None):
    f = open(filename, 'r')
    atoms = []
    ener = []
    fmins = []
    fmaxs = []
    fnorms = []
    cycle = -1
    while True:
        elements = []
        positions = []
        forces = []
        line = f.readline()
        if not line:
            break
        if cycle == -1:
            atom_numb = int(line.split()[0])
        line = f.readline()
        energy = float(line.split(":")[1])
        #read one particular structure assinged by state_number
        for i in range(atom_numb):
            line = f.readline()
            fields = line.split()
            elements.append(fields[0])
            positions.append([float(fields[j + 1]) for j in range(3)])
            forces.append([float(fields[j + 1]) for j in range(3, 6)])
        elements = np.array(elements)
        positions = np.array(positions)
        p = Atoms(symbols=elements, positions=positions)
        calc = forces_setter(energy=energy, forces=np.array(forces))
        p.set_cell([[20., 0, 0], [0, 20., 0], [0, 0, 20.]], scale_atoms=False)
        p.set_pbc((True, True, True))
        p.set_calculator(calc)
        p.center()
        e = p.get_potential_energy()
        fs = np.absolute(p.get_forces())
        fmin = np.amin(fs)
        fmax = np.amax(fs)
        if fmax > 10.0:
            continue
        ener.append(energy)
        fnorm = np.linalg.norm(np.sum(np.array(forces), axis=0))
        atoms.append([p, [energy, fnorm, fmin, fmax]])
        fmins.append(fmin)
        fmaxs.append(fmax)
        fnorms.append(fnorm)
        cycle += 1
    f.close()
    return atoms, np.array(ener), np.array(fnorms), np.array(fmins), np.array(
        fmaxs)
Beispiel #29
0
def twoAtomForce():
    print "\nRunning LJ twoAtomForce"
    elements = [29]
    epsilon = [0.15]
    sigma = [2.7]

    atoms = Atoms(positions=[(0.0, 0.0, 0.0), (0.0, 0.0, 2.0)], symbols="Cu2")

    atoms.set_calculator(LennardJones(elements, epsilon, sigma, -1.0, False))

    result = atoms.get_potential_energy()

    r = atoms.get_positions()
    r.flat[:] += 0.06 * np.sin(np.arange(3 * len(atoms)))
    atoms.set_positions(r)
    resA, resB = atoms.get_forces()
    storedForces = [-1.15732425, 13.10743025, -258.04517252]

    for a in range(1, 3):
        ReportTest(("  Simple force test dimension %d" % a),
                   resA[a],
                   storedForces[a],
                   1e-8,
                   silent=Silent)

    print "  Running Verlet dynamics (%s)" % ("Cu", )
    dyn = VelocityVerlet(atoms, 2 * units.fs)
    dyn.run(100)

    etot1 = (atoms.get_potential_energy() + atoms.get_kinetic_energy())
    dyn.run(1000)
    etot2 = (atoms.get_potential_energy() + atoms.get_kinetic_energy())
    ReportTest(("  Energy conservation (%s)" % ("Cu", )),
               etot1,
               etot2,
               1.0,
               silent=Silent)

    epot = atoms.get_potential_energies()
    stress = atoms.get_stresses()

    e = []
    s = []
    j = 0
    for i in range(0, len(atoms), 100):
        e.append(epot[i])
        s.append(stress[i, j])
        j = (j + 1) % 6
    print "  e" + "Cu" + " =", repr(e)
    print "  s" + "Cu" + " =", repr(s)
Beispiel #30
0
    def test_energy(self):
        vac = 8
        dist_min = 1.2

        atoms = Atoms('CC', positions=[[0, 0, 0], [dist_min, 0, 0]])
        atoms.center(vacuum=vac)

        for calc in [Rebo2(), Rebo2Scr()]:
            atoms.calc = calc
            energy = atoms.get_potential_energy()
            forces_ac = atoms.get_forces()
            stress = atoms.get_stress()

            fname = 'structure.traj'
            atoms.write(fname)
            atoms = io.read(fname)

            self.assertTrue(
                np.abs(energy - atoms.get_potential_energy()) < 1e-10)
            self.assertTrue(
                (np.abs(forces_ac - atoms.get_forces()) < 1e-10).all())
            self.assertTrue(
                (np.abs(stress - atoms.get_stress()) < 1e-10).all())
Beispiel #31
0
 def test_forces_dimer(self):
     d = 1.2
     L = 10 
     atomic_configuration = Atoms("HH", 
                                  positions=[(L/2, L/2, L/2), (L/2 + d, L/2, L/2)],
                                  cell=[L, L, L],
                                  pbc=[1, 1, 1]
                                  )
     atomic_configuration.set_array("size", np.array([1.3, 2.22]), dtype=float)
     atomic_configuration.set_masses(masses=np.repeat(1.0, len(atomic_configuration)))
     calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22))
     atomic_configuration.set_calculator(calc)
     f = atomic_configuration.get_forces()
     fn = calc.calculate_numerical_forces(atomic_configuration, d=0.0001)
     self.assertArrayAlmostEqual(f, fn, tol=self.tol)
Beispiel #32
0
 def test_ase(self):
     from ase import Atoms
     from deepmd.calculator import DP
     water = Atoms('OHHOHH',
                   positions=self.coords.reshape((-1, 3)),
                   cell=self.box.reshape((3, 3)),
                   calculator=DP("deeppot.pb"))
     ee = water.get_potential_energy()
     ff = water.get_forces()
     nframes = 1
     np.testing.assert_almost_equal(ff.ravel(), self.expected_f.ravel(),
                                    default_places)
     expected_se = np.sum(self.expected_e.reshape([nframes, -1]), axis=1)
     np.testing.assert_almost_equal(ee.ravel(), expected_se.ravel(),
                                    default_places)
Beispiel #33
0
def twoAtomForce():
  print "\nRunning LJ twoAtomForce"
  elements = [29]
  epsilon  = [0.15]
  sigma    = [2.7]

  atoms=Atoms(positions=[(0.0, 0.0, 0.0),(0.0, 0.0, 2.0)],
              symbols="Cu2")

  atoms.set_calculator(LennardJones(elements, epsilon, sigma, -1.0, False))


  result = atoms.get_potential_energy()

  r = atoms.get_positions()
  r.flat[:] += 0.06 * np.sin(np.arange(3*len(atoms)))
  atoms.set_positions(r)
  resA, resB = atoms.get_forces() ;
  storedForces = [ -1.15732425,   13.10743025, -258.04517252 ]

  for a in range(1,3):
    ReportTest(("  Simple force test dimension %d" % a), resA[a],
               storedForces[a], 1e-8, silent=Silent)


  print "  Running Verlet dynamics (%s)" % ("Cu",)
  dyn = VelocityVerlet(atoms, 2*units.fs)
  dyn.run(100)

  etot1 = (atoms.get_potential_energy() + atoms.get_kinetic_energy())
  dyn.run(1000)
  etot2 = (atoms.get_potential_energy() + atoms.get_kinetic_energy())
  ReportTest(("  Energy conservation (%s)" % ("Cu",)), etot1, etot2, 1.0, silent=Silent)

  epot = atoms.get_potential_energies()
  stress = atoms.get_stresses()

  e = []
  s = []
  j = 0
  for i in range(0, len(atoms), 100):
      e.append(epot[i])
      s.append(stress[i,j])
      j = (j + 1) % 6
  print "  e"+"Cu"+" =", repr(e)
  print "  s"+"Cu"+" =", repr(s)
Beispiel #34
0
def run_gpaw(calc, phonon):
    supercells = phonon.get_supercells_with_displacements()
    # Force calculations by calculator
    set_of_forces = []
    for scell in supercells:
        cell = Atoms(symbols=scell.get_chemical_symbols(),
                     scaled_positions=scell.get_scaled_positions(),
                     cell=scell.get_cell(),
                     pbc=True)
        cell.set_calculator(calc)
        forces = cell.get_forces()
        drift_force = forces.sum(axis=0)
        print(("[Phonopy] Drift force:" + "%11.5f" * 3) % tuple(drift_force))
        # Simple translational invariance
        for force in forces:
            force -= drift_force / forces.shape[0]
        set_of_forces.append(forces)
    return set_of_forces
Beispiel #35
0
from ase import Atoms
from multiasecalc.lammps.reaxff import ReaxFF
from multiasecalc.utils import get_datafile

d = 0.74
#d = 3.0
a = 6.0

atoms_all = Atoms("H3",
                positions = [(0, 0, 0),
                (0, 0, d),
                (0, 0, 2*d)],
                cell = (100*a, 100*a, 100*a))
atoms_all.center()

calc_1 = ReaxFF(specorder = ("C", "H", "O", "N", "S"),
        implementation="C",
        ff_file_path=get_datafile("ffield.reax"))

atoms_all.set_calculator(calc_1)
print(atoms_all.get_forces())
print(atoms_all.get_potential_energy())

Beispiel #36
0
from ase import Atoms
from gpaw import GPAW, restart
from gpaw.xc.sic import SIC
from gpaw.test import equal
a = 6.0
atom = Atoms('H', magmoms=[1.0], cell=(a, a, a))
molecule = Atoms('H2', positions=[(0, 0, 0), (0, 0, 0.737)], cell=(a, a, a))
atom.center()
molecule.center()

calc = GPAW(xc='LDA-PZ-SIC',
            eigensolver='rmm-diis',
            txt='h2.sic.txt',
            setups='hgh')

atom.set_calculator(calc)
e1 = atom.get_potential_energy()

molecule.set_calculator(calc)
e2 = molecule.get_potential_energy()
F_ac = molecule.get_forces()
de = 2 * e1 - e2
#equal(de, 4.5, 0.1)

# Test forces ...

calc.write('H2.gpw', mode='all')
atoms, calc = restart('H2.gpw')
e2b = atoms.get_potential_energy()
equal(e2, e2b, 0.0001)
Beispiel #37
0
#!/usr/bin/env python
from ase import Atoms, Atom
from jasp import *
atoms = Atoms([Atom('H', [0.5960812,  -0.7677068,   0.0000000]),
               Atom('O', [0.0000000,   0.0000000,   0.0000000]),
               Atom('H', [0.5960812,   0.7677068,   0.0000000])],
              cell=(8, 8, 8))
with jasp('molecules/h2o_relax',
          xc='PBE',
          encut=400,
          ismear=0,  # Gaussian smearing
          ibrion=2,
          ediff=1e-8,
          nsw=10,
          atoms=atoms) as calc:
    print('Forces')
    print('===========================')
    print(atoms.get_forces())
Beispiel #38
0
                         npj=1,
                         ppn=8,
                         exe=vasp,
                         mpirun=mpirun,
                         parmode='mpi',
                         xc='LDA',
                         lreal=False, ibrion=13, nsw=1000000,
                         algo='VeryFast', npar=8, 
                         lplane=False, lwave=False, lcharg=False, nsim=1,
                         voskown=1, ismear=0, sigma=0.01, iwavpr=11, isym=0, nelm=150)

sock_calc = SocketCalculator(vasp_client)

bulk.set_calculator(sock_calc)
sock_e = bulk.get_potential_energy()
sock_f = bulk.get_forces()
sock_s = bulk.get_stress()


print 'energy', sock_e
print 'forces', sock_f
print 'stress', sock_s

bulk.rattle(0.01)

sock_e = bulk.get_potential_energy()
sock_f = bulk.get_forces()
sock_s = bulk.get_stress()

print 'energy', sock_e
print 'forces', sock_f
Beispiel #39
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()

    dimer.constraints = FixInternals(
        bonds=[(r, (0, 2)), (r, (1, 2)),
               (r, (3, 5)), (r, (4, 5))],
        angles=[(a, (0, 2, 1)), (a, (3, 5, 4))])
    opt = BFGS(dimer,
               trajectory=calc.name + '.traj', logfile=calc.name + 'd.log')
Beispiel #40
0
from ase import Atoms
from ase.calculators.emt import EMT
from ase.calculators.test import numeric_forces

h2 = Atoms('H2', positions=[(0, 0, 0), (0, 0, 1.1)],
           calculator=EMT())
f1 = numeric_forces(h2, d=0.0001)
f2 = h2.get_forces()
assert abs(f1 - f2).max() < 1e-6
from gpaw import GPAW
import numpy as np

# spin paired H2
d = 0.75
h2 = Atoms('H2', [[0, 0, 0], [0, 0, d]])
h2.center(vacuum=2.)

e = np.array([])
f = np.array([])

for xc in ['LDA', 'PPLDA']:
    calc = GPAW(nbands=-1, xc=xc, convergence={'eigenstates': 1.e-9}, txt=None)
    h2.set_calculator(calc)
    e = np.append(e, h2.get_potential_energy())
    f = np.append(f, h2.get_forces())
    del calc

print(e[0], e[1], np.abs(e[0] - e[1]))
print(f[0], f[1], np.sum(np.abs(f[0] - f[1])))
assert np.abs(e[0] - e[1]) < 1.e-8
assert np.sum(np.abs(f[0] - f[1])) < 1.e-8


# spin polarized O2
d = 1.2
o2 = Atoms('O2', [[0, 0, 0], [0, 0, d]], magmoms=[1., 1.])
o2.center(vacuum=2.)

e = np.array([])
f = np.array([])
Beispiel #42
0
from ase import Atom, Atoms
from ase.calculators.lj import LennardJones
from ase.constraints import FixBondLength

dimer = Atoms([Atom('X', (0, 0, 0)),
               Atom('X', (0, 0, 1))],
              calculator=LennardJones(),
              constraint=FixBondLength(0, 1))
print dimer.get_forces()
print dimer.positions
dimer.positions[:] += 0.1
print dimer.positions
dimer.positions[:, 2] += 5.1
print dimer.positions
dimer.positions[:] = [(1,2,3),(4,5,6)]
print dimer.positions
dimer.set_positions([(1,2,3),(4,5,6.2)])
print dimer.positions

Beispiel #43
0
                   nbands = -5,
                   xc = xc, 
                   width = 0.05,
                   eigensolver = eigensolver,
                   spinpol = True,
                   txt = None,
                   mixer = MixerSum(beta=0.1, nmaxold=5, weight=50.0),
                   convergence = {'energy': 100,
                                  'density': 100,
                                  'eigenstates': 1.0e-9,
                                  'bands': -1})
    atoms.set_calculator(calc_gs)

    E0.append(atoms.get_potential_energy())
    if i==1:
        F0 = atoms.get_forces()

    calc_es = GPAW(h = 0.2, 
                   nbands = -5,
                   xc = xc, 
                   width = 0.05,
                   eigensolver = eigensolver,
                   spinpol = True,
                   txt = None,
                   mixer = MixerSum(beta=0.1, nmaxold=5, weight=50.0),
                   convergence = {'energy': 100,
                                  'density': 100,
                                  'eigenstates': 1.0e-9,
                                  'bands': -1})

    n = 5 # LUMO
Beispiel #44
0
a = 4.    # Size of unit cell (Angstrom)
c = a / 2
d = 0.74  # Experimental bond length
molecule = Atoms('H2',
                 [(c - d / 2, c, c),
                  (c + d / 2, c, c)],
                 cell=(a, a, a),
                 pbc=False)
calc = GPAW(h=0.2, nbands=1, xc='PBE', txt=None)
molecule.set_calculator(calc)
e1 = molecule.get_potential_energy()
niter1 = calc.get_number_of_iterations()
calc.write('H2.gpw')
calc.write('H2a.gpw', mode='all')
molecule.get_forces()
calc.write('H2f.gpw')
calc.write('H2fa.gpw', mode='all')

from time import time
def timer(func, *args, **kwargs):
    t0 = time()
    ret = func(*args, **kwargs)
    return ret, time()-t0

molecule = GPAW('H2.gpw', txt=None).get_atoms()
f1, t1 = timer(molecule.get_forces)
molecule = GPAW('H2a.gpw', txt=None).get_atoms()
f2, t2 = timer(molecule.get_forces)
molecule = GPAW('H2f.gpw', txt=None).get_atoms()
f3, t3 = timer(molecule.get_forces)
Beispiel #45
0
"""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
Beispiel #46
0
try:
    from asap3 import EMT
except ImportError:
    pass
else:
    a = 3.6
    b = a / 2
    cu = Atoms('Cu',
               cell=[(0, b, b), (b, 0, b), (b, b, 0)],
               pbc=1) * (6, 6, 6)
    cu.set_calculator(EMT())
    f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0])
    opt = LBFGS(f)
    t = Trajectory('Cu-fcc.traj', 'w', cu)
    opt.attach(t)
    opt.run(5.0)

    # HCP:
    from ase.build import hcp0001
    cu = hcp0001('Cu', (1, 1, 2), a=a / sqrt(2))
    cu.cell[1, 0] += 0.05
    cu *= (6, 6, 3)
    cu.set_calculator(EMT())
    print(cu.get_forces())
    print(cu.get_stress())
    f = UnitCellFilter(cu)
    opt = MDMin(f, dt=0.01)
    t = Trajectory('Cu-hcp.traj', 'w', cu)
    opt.attach(t)
    opt.run(0.2)
Beispiel #47
0
# <<water-vib>>
# adapted from http://cms.mpi.univie.ac.at/wiki/index.php/H2O_vibration
from ase import Atoms, Atom
from jasp import *
import ase.units
atoms = Atoms([Atom('H', [0.5960812,  -0.7677068,   0.0000000]),
               Atom('O', [0.0000000,   0.0000000,   0.0000000]),
               Atom('H', [0.5960812,   0.7677068,   0.0000000])],
               cell=(8, 8, 8))
atoms.center()
with jasp('molecules/h2o_vib',
          xc='PBE',
          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,   # for vibrations you need precise energies
          nsw=1,        # Set to 1 for vibrational calculation
          atoms=atoms) as calc:
    print 'Forces'
    print '======'
    print atoms.get_forces()
    print
    # vibrational energies are in eV
    energies, modes = calc.get_vibrational_modes()
    print 'energies\n========'
    for i, e in enumerate(energies):
        print '{0:02d}: {1} eV'.format(i, e)
Beispiel #48
0
from ase.units import fs, kB
from ase.calculators.test import TestPotential
from ase.md import Langevin
from ase.io import Trajectory, read
from ase.optimize import QuasiNewton
from ase.utils import seterr

with 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())
    # Langevin should reproduce Verlet if friction is 0.
    md = Langevin(a, 0.5 * fs, 300 * kB, 0.0, logfile='-', loginterval=500)
    traj = Trajectory('4N.traj', 'w', a)
    md.attach(traj, 100)
    e0 = a.get_total_energy()
    md.run(steps=10000)
    del traj
    assert abs(read('4N.traj').get_total_energy() - e0) < 0.0001

    # Try again with nonzero friction.
    md = Langevin(a, 0.5 * fs, 300 * kB, 0.001, logfile='-', loginterval=500)
    traj = Trajectory('4NA.traj', 'w', a)
    md.attach(traj, 100)
    md.run(steps=10000)
def test():

    ###########################################################################
    # Parameters

    atoms = Atoms(symbols='PdOPd2',
                  pbc=np.array([False, False, False], dtype=bool),
                  cell=np.array(
                      [[1.,  0.,  0.],
                       [0.,  1.,  0.],
                          [0.,  0.,  1.]]),
                  positions=np.array(
                      [[0.,  1.,  0.],
                       [1.,  2.,  1.],
                          [-1.,  1.,  2.],
                          [1.,  3.,  2.]]))

    ###########################################################################
    # Parameters

    Gs = {'O': [{'type': 'G2', 'element': 'Pd', 'eta': 0.8},
                {'type': 'G4', 'elements': [
                    'Pd', 'Pd'], 'eta':0.2, 'gamma':0.3, 'zeta':1},
                {'type': 'G4', 'elements': ['O', 'Pd'], 'eta':0.3, 'gamma':0.6,
                 'zeta':0.5}],
          'Pd': [{'type': 'G2', 'element': 'Pd', 'eta': 0.2},
                 {'type': 'G4', 'elements': ['Pd', 'Pd'],
                  'eta':0.9, 'gamma':0.75, 'zeta':1.5},
                 {'type': 'G4', 'elements': ['O', 'Pd'], 'eta':0.4,
                  'gamma':0.3, 'zeta':4}]}

    hiddenlayers = {'O': (2,), 'Pd': (2,)}

    weights = OrderedDict([('O', OrderedDict([(1, np.matrix([[-2.0, 6.0],
                                                             [3.0, -3.0],
                                                             [1.5, -0.9],
                                                             [-2.5, -1.5]])),
                                              (2, np.matrix([[5.5],
                                                             [3.6],
                                                             [1.4]]))])),
                           ('Pd', OrderedDict([(1, np.matrix([[-1.0, 3.0],
                                                              [2.0, 4.2],
                                                              [1.0, -0.7],
                                                              [-3.0, 2.0]])),
                                               (2, np.matrix([[4.0],
                                                              [0.5],
                                                              [3.0]]))]))])

    scalings = OrderedDict([('O', OrderedDict([('intercept', -2.3),
                                               ('slope', 4.5)])),
                            ('Pd', OrderedDict([('intercept', 1.6),
                                                ('slope', 2.5)]))])

    fingerprints_range = {"O": np.array([[0.21396177208585404,
                                          2.258090276328769],
                                         [0.0, 2.1579067008202975],
                                         [0.0, 0.0]]),
                          "Pd": np.array([[0.0, 1.4751761770313006],
                                          [0.0, 0.697686078889583],
                                          [0.0, 0.37848964715610417]])}

    ###########################################################################

    calc = Amp(descriptor=Gaussian(cutoff=6.5,
                                   Gs=Gs,
                                   fortran=False,),
               model=NeuralNetwork(hiddenlayers=hiddenlayers,
                                   weights=weights,
                                   scalings=scalings,
                                   fprange=fingerprints_range,
                                   mode='atom-centered'),
               cores=1)

    atoms.set_calculator(calc)

    e1 = atoms.get_potential_energy(apply_constraint=False)
    e2 = calc.get_potential_energy(atoms)
    f1 = atoms.get_forces(apply_constraint=False)

    atoms[0].x += 0.5

    boolean = atoms.calc.calculation_required(atoms, properties=['energy'])

    e3 = atoms.get_potential_energy(apply_constraint=False)
    e4 = calc.get_potential_energy(atoms)
    f2 = atoms.get_forces(apply_constraint=False)

    assert (e1 == e2 and
            e3 == e4 and
            abs(e1 - e3) > 10. ** (-3.) and
            (boolean is True) and
            (not (f1 == f2).all())), 'Displaced-atom test broken!'
Beispiel #50
0
atoms = Atoms('Na3', positions=[( 0, 0, 0),
                              ( 0, 0, d),
                              ( 0, d*sqrt(3./4.), d/2.)],
                   magmoms=[1.0, 1.0, 1.0],
                   cell=(3.5, 3.5, 4.+2/3.),
                   pbc=True)

# Only a short, non-converged calcuation
conv = {'eigenstates': 1.e-3, 'energy':1e-2, 'density':1e-1}
calc = GPAW(h=0.30, nbands=3,
            setups={'Na': '1'}, 
            convergence=conv)
atoms.set_calculator(calc)
e0 = atoms.get_potential_energy()
niter0 = calc.get_number_of_iterations()
f0 = atoms.get_forces()
m0 = atoms.get_magnetic_moments()
eig00 = calc.get_eigenvalues(spin=0)
eig01 = calc.get_eigenvalues(spin=1)
# Write the restart file(s)
for mode in modes:
    calc.write('tmp.%s' % mode)

del atoms, calc
# Try restarting from all the files
for mode in modes:
    atoms, calc = restart('tmp.%s' % mode)
    # Force new calculation
    calc.scf.converged = False
    e1 = atoms.get_potential_energy()
    f1 = atoms.get_forces()
Beispiel #51
0
for d in bond_lengths:  # possible bond lengths
    co = Atoms([Atom('C', [0, 0, 0]),
                Atom('O', [d, 0, 0])],
               cell=(6, 6, 6))
    with jasp('molecules/co-{0}'.format(d),  # output dir
              xc='PBE',
              encut=450,
              ismear=1,
              sigma=0.01,
              atoms=co) as calc:
        try:
            e = co.get_potential_energy()
            energies.append(e)
            print('d = {0:1.3f} ang'.format(d))
            print('energy = {0:1.5f} eV'.format(e))
            print('forces = (eV/ang)\n {0}'.format(co.get_forces()))
            print('')  # blank line
        except (VaspSubmitted, VaspQueued):
            energies.append(None)
            pass

# fit the data
pars = np.polyfit(bond_lengths, energies, 3)
xfit = np.linspace(1.05, 1.25)
efit = np.polyval(pars, xfit)
# first derivative
dpars = np.polyder(pars)
# find where the minimum is. chose the second one because it is the
# minimum we need.
droots = np.roots(dpars)
# second derivative
Beispiel #52
0
ref = np.array([[-1.26056746e-01, 4.10007559e-01, 2.85719551e-04],
                [4.28062314e-01, 2.56059142e-02, 2.17691110e-04],
                [-3.02019173e-01, -4.35613473e-01, -5.03410632e-04]])

error = np.sqrt(np.sum((forces_num - ref)**2))
print('forces_num')
print(forces_num)
print('diff from reference:')
print(error)

assert(error < tol)


# analytical forces
forces_an = atoms.get_forces()

ref = np.array([[-1.26446863e-01, 4.09628186e-01, -0.00000000e+00],
                [4.27934442e-01, 2.50425467e-02, -5.14220671e-05],
                [-2.99225008e-01, -4.31533987e-01, -5.14220671e-05]])

error = np.sqrt(np.sum((forces_an - ref)**2))
print('forces_an')
print(forces_an)
print('diff from reference:')
print(error)

assert(error < tol)

# optimize geometry
dyn = BFGS(atoms)
Beispiel #53
0
        write(fname2, images, format=format)

    if format in r:
        print('I')
        a1 = read(fname1)
        assert np.all(np.abs(a1.get_positions() -
                             atoms.get_positions()) < 1e-6)
        if format in ['traj', 'cube', 'cfg', 'struct', 'gen', 'extxyz']:
            assert np.all(np.abs(a1.get_cell() - atoms.get_cell()) < 1e-6)
        if format in ['cfg', 'extxyz']:
            assert np.all(np.abs(a1.get_array('extra') -
                                 atoms.get_array('extra')) < 1e-6)
        if format in ['extxyz']:
            assert np.all(a1.get_pbc() == atoms.get_pbc())
            assert np.all(a1.get_potential_energy() == atoms.get_potential_energy())
            assert np.all(a1.get_stress() == atoms.get_stress())            
            assert np.all(abs(a1.get_forces() - atoms.get_forces()) < 1e-6)

        if format not in only_one_image:
            a2 = read(fname2)
            a3 = read(fname2, index=0)
            a4 = read(fname2, index=slice(None))
            if format in ['cif'] and sys.platform in ['win32']:
                # Fails on Windows:
                # https://trac.fysik.dtu.dk/projects/ase/ticket/62
                pass
            else:
                assert len(a4) == 2
    else:
        print()
Beispiel #54
0
# 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')
Beispiel #55
0
from ase.calculators.test import numeric_force
from gpaw import GPAW, Mixer
from gpaw.test import equal

a = 4.0
n = 16
atoms = Atoms([Atom('H', [1.234, 2.345, 3.456])],
                    cell=(a, a, a), pbc=True)
calc = GPAW(nbands=1,
            gpts=(n, n, n),
            txt=None,
            mixer=Mixer(0.25, 3, 1),
            convergence={'energy': 1e-7})
atoms.set_calculator(calc)
e1 = atoms.get_potential_energy()
niter1 = calc.get_number_of_iterations()
f1 = atoms.get_forces()[0]
for i in range(3):
    f2i = numeric_force(atoms, 0, i)
    print f1[i]-f2i
    equal(f1[i], f2i, 0.00025)

energy_tolerance = 0.00006
force_tolerance = 0.0001
niter_tolerance = 0
equal(e1, -0.531042, energy_tolerance)
f1_ref = [-0.291893, -0.305174, -0.35329]
for i in range(3):
    equal(f1[i], f1_ref[i], force_tolerance)
assert 34 <= niter1 <= 35, niter1
Beispiel #56
0
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
Beispiel #57
0
from ase import Atoms
from ase.calculators.emt import EMT

h2 = Atoms('H2', positions=[(0, 0, 0), (0, 0, 1.1)],
           calculator=EMT())
print h2.calc.get_numeric_forces(h2)
print h2.get_forces()

Beispiel #58
0
system = Atoms(symbols='Si2', pbc=True,
               cell=0.5 * a * np.array([(1, 1, 0),
                                        (1, 0, 1),
                                        (0, 1, 1)]),
               scaled_positions=[(0.0, 0.0, 0.0),
                                 (0.23, 0.23, 0.23)])

calc = GPAW(h=0.2,
            mode='lcao',
            basis=basis,
            kpts=(2,2,2),
            convergence={'density':1e-5, 'energy': 1e-6}
            )
system.set_calculator(calc)

F_ac = system.get_forces()

# Previous FD result, generated by disabled code below
F_ac_ref = np.array([[-1.3977335 , -1.39637682, -1.39682766],
                     [ 1.39952439,  1.39949595,  1.39882519]])

err_ac = np.abs(F_ac - F_ac_ref)
err = err_ac.max()

print 'Force'
print F_ac
print
print 'Reference result'
print F_ac_ref
print
print 'Error'
Beispiel #59
0
                        (0.25, 0.25, 0.25),
                        (0.25, 0.75, 0.75),
                        (0.75, 0.25, 0.75),
                        (0.75, 0.75, 0.25)],
             pbc=True)
bulk.set_cell((a, a, a), scale_atoms=True)
n = 20
calc = GPAW(gpts=(n, n, n),
            nbands=8*3,
            occupations=FermiDirac(width=0.01),
            poissonsolver=PoissonSolver(nn='M', relax='J'),
            kpts=(2, 2, 2),
            convergence={'energy': 1e-7}
            )
bulk.set_calculator(calc)
f1 = bulk.get_forces()[0, 2]
e1 = bulk.get_potential_energy()
niter1 = calc.get_number_of_iterations()

f2 = numeric_force(bulk, 0, 2)
print f1,f2,f1-f2
equal(f1, f2, 0.005)

# Volume per atom:
vol = a**3 / 8
de = calc.get_electrostatic_corrections() / vol
print de
assert abs(de[0] - -2.190) < 0.001

print e1, f1, niter1
energy_tolerance = 0.00025
Beispiel #60
0
from ase import Atoms, Atom
from jasp import *
import numpy as np
np.set_printoptions(precision=3, suppress=True)
co = Atoms([Atom('C', [0, 0, 0]),
            Atom('O', [1.2, 0, 0])],
           cell=(6., 6., 6.))
with jasp('molecules/simple-co',  # output dir
          xc='PBE',  # the exchange-correlation functional
          nbands=6,    # number of bands
          encut=350,    # planewave cutoff
          ismear=1,    # Methfessel-Paxton smearing
          sigma=0.01,  # very small smearing factor for a molecule
          atoms=co) as calc:
    print('energy = {0} eV'.format(co.get_potential_energy()))
    print(co.get_forces())