Esempio n. 1
0
 def convert_adsorbate(cls, adsorbate):
     """Converts the adsorbate to an Atoms object"""
     if isinstance(adsorbate, Atoms):
         ads = adsorbate
     elif isinstance(adsorbate, Atom):
         ads = Atoms([adsorbate])
     else:
         # Hope it is a useful string or something like that
         if adsorbate == 'CO':
             # CO otherwise comes out as OC - very inconvenient
             ads = molecule(adsorbate, symbols=adsorbate)
         else:
             ads = molecule(adsorbate)
     ads.translate(-ads[0].position)
     return ads
Esempio n. 2
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable('$ASE_CP2K_COMMAND not defined')

    # Basically, the entire CP2K input is passed in explicitly.
    # Disable ASE's input generation by setting everything to None.
    # ASE should only add the CELL and the COORD section.
    calc = CP2K(basis_set=None,
                basis_set_file=None,
                max_scf=None,
                cutoff=None,
                force_eval_method=None,
                potential_file=None,
                poisson_solver=None,
                pseudo_potential=None,
                stress_tensor=False,
                xc=None,
                label='test_H2_inp', inp=inp)
    h2 = molecule('H2', calculator=calc)
    h2.center(vacuum=2.0)
    energy = h2.get_potential_energy()
    energy_ref = -30.6989595886
    diff = abs((energy - energy_ref) / energy_ref)
    assert diff < 1e-10
    print('passed test "H2_None"')
Esempio n. 3
0
def h2dft(name):
    Calculator = get_calculator(name)
    par = required.get(name, {})
    calc = Calculator(label=name, xc='LDA', **par)
    h2 = molecule('H2', calculator=calc)
    h2.center(vacuum=2.0)
    e2 = h2.get_potential_energy()
    calc.set(xc='PBE')
    e2pbe = h2.get_potential_energy()
    h1 = h2.copy()
    del h1[1]
    h1.set_initial_magnetic_moments([1])
    h1.calc = calc
    e1pbe = h1.get_potential_energy()
    calc.set(xc='LDA')
    e1 = h1.get_potential_energy()
    try:
        m1 = h1.get_magnetic_moment()
    except NotImplementedError:
        pass
    else:
        print(m1)
    print(2 * e1 - e2)
    print(2 * e1pbe - e2pbe)
    print(e1, e2, e1pbe, e2pbe)
    calc = Calculator(name)
    print(calc.parameters, calc.results, calc.atoms)
    assert not calc.calculation_required(h1, ['energy'])
    h1 = calc.get_atoms()
    print(h1.get_potential_energy())
    label = 'dir/' + name + '-h1'
    calc = Calculator(label=label, atoms=h1, xc='LDA', **par)
    print(h1.get_potential_energy())
    print(Calculator.read_atoms(label).get_potential_energy())
Esempio n. 4
0
def main_gpaw():
    from gpaw import GPAW
    from ase.build import molecule
    system = molecule('H2')
    system.center(vacuum=1.5)
    system.pbc = 1
    calc = GPAW(h=0.3, mode='lcao', txt=None)
    system.set_calculator(calc)
    system.get_potential_energy()
    check_interface(calc)
Esempio n. 5
0
def main_octopus():
    from octopus import Octopus
    from ase.build import molecule
    system = molecule('H2')
    system.center(vacuum=1.5)
    system.pbc = 1
    calc = Octopus()
    system.set_calculator(calc)
    system.get_potential_energy()
    check_interface(calc)
Esempio n. 6
0
def build_molecule(args):
    try:
        # Known molecule or atom?
        atoms = molecule(args.name)
    except NotImplementedError:
        symbols = string2symbols(args.name)
        if len(symbols) == 1:
            Z = atomic_numbers[symbols[0]]
            magmom = ground_state_magnetic_moments[Z]
            atoms = Atoms(args.name, magmoms=[magmom])
        elif len(symbols) == 2:
            # Dimer
            if args.bond_length is None:
                b = (covalent_radii[atomic_numbers[symbols[0]]] +
                     covalent_radii[atomic_numbers[symbols[1]]])
            else:
                b = args.bond_length
            atoms = Atoms(args.name, positions=[(0, 0, 0),
                                                (b, 0, 0)])
        else:
            raise ValueError('Unknown molecule: ' + args.name)
    else:
        if len(atoms) == 2 and args.bond_length is not None:
            atoms.set_distance(0, 1, args.bond_length)

    if args.unit_cell is None:
        if args.vacuum:
            atoms.center(vacuum=args.vacuum)
        else:
            atoms.center(about=[0, 0, 0])
    else:
        a = [float(x) for x in args.unit_cell.split(',')]
        if len(a) == 1:
            cell = [a[0], a[0], a[0]]
        elif len(a) == 3:
            cell = a
        else:
            a, b, c, alpha, beta, gamma = a
            degree = np.pi / 180.0
            cosa = np.cos(alpha * degree)
            cosb = np.cos(beta * degree)
            sinb = np.sin(beta * degree)
            cosg = np.cos(gamma * degree)
            sing = np.sin(gamma * degree)
            cell = [[a, 0, 0],
                    [b * cosg, b * sing, 0],
                    [c * cosb, c * (cosa - cosb * cosg) / sing,
                     c * np.sqrt(
                        sinb**2 - ((cosa - cosb * cosg) / sing)**2)]]
        atoms.cell = cell
        atoms.center()

    atoms.pbc = args.periodic

    return atoms
Esempio n. 7
0
def h2(name, par):
    h2 = molecule('H2', pbc=par.pop('pbc', False))
    h2.center(vacuum=2.0)
    h2.calc = get_calculator(name)(**par)
    e = h2.get_potential_energy()
    f = h2.get_forces()
    assert not h2.calc.calculation_required(h2, ['energy', 'forces'])
    write('h2.traj', h2)
    h2 = read('h2.traj')
    assert abs(e - h2.get_potential_energy()) < 1e-12
    assert abs(f - h2.get_forces()).max() < 1e-12
Esempio n. 8
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable('$ASE_CP2K_COMMAND not defined')

    calc = CP2K()
    h2 = molecule('H2', calculator=calc)
    h2.center(vacuum=2.0)
    h2.get_potential_energy()
    calc.write('test_restart')  # write a restart
    calc2 = CP2K(restart='test_restart')  # load a restart
    assert not calc2.calculation_required(h2, ['energy'])
    print('passed test "restart"')
Esempio n. 9
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable("$ASE_CP2K_COMMAND not defined")

    calc = CP2K(xc="XC_GGA_X_PBE XC_GGA_C_PBE", pseudo_potential="GTH-PBE", label="test_H2_libxc")
    h2 = molecule("H2", calculator=calc)
    h2.center(vacuum=2.0)
    energy = h2.get_potential_energy()
    energy_ref = -31.591716529642
    diff = abs((energy - energy_ref) / energy_ref)
    assert diff < 1e-10
    print('passed test "H2_libxc"')
Esempio n. 10
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable('$ASE_CP2K_COMMAND not defined')

    calc = CP2K(xc='PBE', label='test_H2_PBE')
    h2 = molecule('H2', calculator=calc)
    h2.center(vacuum=2.0)
    energy = h2.get_potential_energy()
    energy_ref = -31.5917284949
    diff = abs((energy - energy_ref) / energy_ref)
    assert diff < 1e-10
    print('passed test "H2_PBE"')
Esempio n. 11
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable('$ASE_CP2K_COMMAND not defined')

    calc = CP2K(label='test_O2', uks=True, cutoff=150 * units.Rydberg,
                basis_set="SZV-MOLOPT-SR-GTH")
    o2 = molecule('O2', calculator=calc)
    o2.center(vacuum=2.0)
    energy = o2.get_potential_energy()
    energy_ref = -861.057011375
    diff = abs((energy - energy_ref) / energy_ref)
    assert diff < 1e-10
    print('passed test "O2"')
Esempio n. 12
0
    def test_multiple_elements(self):
        a = molecule('HCOOH')
        a.center(vacuum=5.0)
        io.write('HCOOH.cfg', a)
        i = neighbour_list("i", a, 1.85)
        self.assertArrayAlmostEqual(np.bincount(i), [2,3,1,1,1])

        cutoffs = {(1, 6): 1.2}
        i = neighbour_list("i", a, cutoffs)
        self.assertArrayAlmostEqual(np.bincount(i), [0,1,0,0,1])

        cutoffs = {(6, 8): 1.4}
        i = neighbour_list("i", a, cutoffs)
        self.assertArrayAlmostEqual(np.bincount(i), [1,2,1])

        cutoffs = {('H', 'C'): 1.2, (6, 8): 1.4}
        i = neighbour_list("i", a, cutoffs)
        self.assertArrayAlmostEqual(np.bincount(i), [1,3,1,0,1])
Esempio n. 13
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable('$ASE_CP2K_COMMAND not defined')

    inp = """&FORCE_EVAL
               &DFT
                 &QS
                   LS_SCF ON
                 &END QS
               &END DFT
             &END FORCE_EVAL"""
    calc = CP2K(label='test_H2_LS', inp=inp)
    h2 = molecule('H2', calculator=calc)
    h2.center(vacuum=2.0)
    energy = h2.get_potential_energy()
    energy_ref = -30.6989581747
    diff = abs((energy - energy_ref) / energy_ref)
    assert diff < 5e-7
    print('passed test "H2_LS"')
Esempio n. 14
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable('$ASE_CP2K_COMMAND not defined')

    calc = CP2K(label='test_H2_GOPT')
    atoms = molecule('H2', calculator=calc)
    atoms.center(vacuum=2.0)

    # Run Geo-Opt
    gopt = BFGS(atoms, logfile=None)
    gopt.run(fmax=1e-6)

    # check distance
    dist = atoms.get_distance(0, 1)
    dist_ref = 0.7245595
    assert (dist - dist_ref) / dist_ref < 1e-7

    # check energy
    energy_ref = -30.7025616943
    energy = atoms.get_potential_energy()
    assert (energy - energy_ref) / energy_ref < 1e-10
    print('passed test "H2_GEO_OPT"')
Esempio n. 15
0
def check_db(c, db, test=None):
    if test is None:
        print("%10s %10s %10s ( %10s )" \
            % ( "bond", "value", "reference", "error" ))
        print("%10s %10s %10s ( %10s )" \
            % ( "----", "-----", "---------", "-----" ))
    for mol, values in db.items():
        #if mol == 'H2O':
        if 1:
            a = molecule(mol)
            a.center(vacuum=10.0)
            a.set_pbc(False)
            a.set_initial_charges(np.zeros(len(a)))

            a.set_calculator(c)
            FIRE(a, logfile=None).run(fmax=0.001)

            for name, ( ( i1, i2 ), refvalue ) in values.items():
                value = a.get_distance(i1, i2)
                if test is None:
                    print('%10s %10.3f %10.3f ( %10.3f )' % \
                        ( name, value, refvalue, abs(value-refvalue) ))
                else:
                    test.assertTrue(abs(value-refvalue) < 0.01)
Esempio n. 16
0
from ase.build import molecule
from ase.calculators.onetep import Onetep
from os.path import isfile, dirname, abspath, join

mol = molecule('H2O')
mol.center(8)
calc = Onetep(label='water')
# Tests conducted with the JTH PAW data set.
# http://www.abinit.org/downloads/PAW2
prefix = dirname(abspath(__file__))
h_path = join(prefix, 'H.abinit')
o_path = join(prefix, 'O.abinit')
if not (isfile(h_path) and isfile(o_path)):
    raise Exception("""You must supply PAW data sets for
        hydrogen and oxygen to run this test.
        Please see http://www.abinit.org/downloads/PAW2
        for suitable data. ONETEP takes PAW data sets in the
        abinit format. I need H.abinit and O.abinit""")
calc.set_pseudos([('H', h_path), ('O', o_path)])
calc.set(paw=True, xc='PBE', cutoff_energy='400 eV')
mol.set_calculator(calc)

energy = mol.get_total_energy()
ref_energy = -470.852068717
assert abs(energy - ref_energy) < 1e-6
Esempio n. 17
0
from ase.calculators.emt import EMT
from ase import Atoms
from ase.build import molecule
a1 = Atoms('Au', calculator=EMT())
e1 = a1.get_potential_energy()
a2 = molecule('C6H6', calculator=EMT())
e2 = a2.get_potential_energy()
a1.translate((0, 0, 50))
a3 = a1 + a2
a3.calc = EMT()
e3 = a3.get_potential_energy()
print(e1, e2, e3, e3 - e1 - e2)
assert abs(e3 - e1 - e2) < 1e-13
Esempio n. 18
0
def atoms():
    return molecule('H2')
Esempio n. 19
0
#!/usr/bin/env python
from ase.build import molecule
from xcp2k import CP2K
from ase.io import read, write
from ase.optimize import BFGS
from ase.vibrations import Vibrations

import os


atoms = molecule('CO')
atoms.center(vacuum=2.0)

atoms.pbc=[True, True, True]

calc = CP2K(label = 'molecules/co',
           cpu= 4,
           xc='pbe')
atoms.set_calculator(calc)
e = atoms.get_potential_energy()
print('energy: {0:1.4f} '.format(e))
pos = atoms.get_positions()
bondlength = sum((pos[1] - pos[0])**2)**0.5
print('bond length = {0} A'.format(bondlength))
Esempio n. 20
0
def settings(gui):
    gui.new_atoms(molecule('H2O'))
    s = gui.settings()
    s.scale.value = 1.9
    s.scale_radii()
Esempio n. 21
0
"""

Check the unit cell is handled correctly

"""

from ase.calculators.vasp import Vasp
from ase.build import molecule
from ase.test import must_raise

# Molecules come with no unit cell

atoms = molecule('CH4')
calc = Vasp()

with must_raise(ValueError):
    atoms.set_calculator(calc)
    atoms.get_total_energy()
Esempio n. 22
0
# fails with On entry to ZGEMV parameter number 8 had an illegal value

from ase.build import molecule
from gpaw import GPAW
from gpaw.wavefunctions.pw import PW

m = molecule('H')
m.center(vacuum=2.0)
m.set_calculator(GPAW(mode=PW(), eigensolver='cg'))
m.get_potential_energy()
Esempio n. 23
0
from __future__ import print_function
from ase.build import molecule
from gpaw import GPAW
from gpaw.poisson import PoissonSolver
from gpaw.atom.basis import BasisMaker
from gpaw.test import equal

# Tests basis set super position error correction

# Compares a single hydrogen atom to a system of one hydrogen atom
# and one ghost hydrogen atom.  The systems should have identical properties,
# i.e. the ghost orbital should have a coefficient of 0.

b = BasisMaker('H').generate(1, 0, energysplit=0.005)

system = molecule('H2')
system.center(vacuum=6.0)


def prepare(setups):
    calc = GPAW(basis={'H': b},
                mode='lcao',
                setups=setups,
                h=0.2,
                poissonsolver=PoissonSolver(nn='M', relax='GS', eps=1e-5),
                spinpol=False,
                nbands=1)
    system.set_calculator(calc)
    return calc

Esempio n. 24
0
def open_and_save(gui):
    mol = molecule('H2O')
    for i in range(3):
        mol.write('h2o.json')
    gui.open(filename='h2o.json')
    save_dialog(gui, 'h2o.cif@-1')
Esempio n. 25
0
import numpy as np
from ase import Atoms
from ase.visualize import view
from ase.build import molecule
from blase.tools import get_bondpairs, write_blender

a = 5.64  # Lattice constant for NaCl
cell = [a / np.sqrt(2), a / np.sqrt(2), a]
atoms = Atoms(symbols='Na2Cl2',
              pbc=True,
              cell=cell,
              scaled_positions=[(.0, .0, .0), (.5, .5, .5), (.5, .5, .0),
                                (.0, .0, .5)]) * (3, 4, 2) + molecule('C6H6')

# Move molecule to 3.5Ang from surface, and translate one unit cell in xy
atoms.positions[-12:, 2] += atoms.positions[:-12, 2].max() + 3.5
atoms.positions[-12:, :2] += cell[:2]
atoms.cell[0][0] += 10
# Mark a single unit cell
# atoms.cell = cell
# view(atoms)

# View used to start ag, and find desired viewing angle
#view(atoms)
# rot = '35x,63y,36z'  # found using ag: 'view -> rotate'

atoms.rotate(90, 'y')
# view(atoms)
bondatoms = get_bondpairs(atoms,
                          cutoff=1.2,
                          rmbonds=[['Na', 'Na'], ['Cl', 'Cl']])
Esempio n. 26
0
def rotate(gui):
    gui.window['toggle-show-bonds'] = True
    gui.new_atoms(molecule('H2O'))
    gui.rotate_window()
Esempio n. 27
0
def settings(gui):
    gui.new_atoms(molecule('H2O'))
    s = gui.settings()
    s.scale.value = 1.9
    s.scale_radii()
Esempio n. 28
0
# creates: NaCl_C6H6.png

import numpy as np

from ase import Atoms
from ase.io import write
from ase.build import molecule

a = 5.64  # Lattice constant for NaCl
cell = [a / np.sqrt(2), a / np.sqrt(2), a]
atoms = Atoms(symbols='Na2Cl2', pbc=True, cell=cell,
              scaled_positions=[(.0, .0, .0),
                                (.5, .5, .5),
                                (.5, .5, .0),
                                (.0, .0, .5)]) * (3, 4, 2) + molecule('C6H6')

# Move molecule to 3.5Ang from surface, and translate one unit cell in xy
atoms.positions[-12:, 2] += atoms.positions[:-12, 2].max() + 3.5
atoms.positions[-12:, :2] += cell[:2]

# Mark a single unit cell
atoms.cell = cell

# View used to start ag, and find desired viewing angle
#view(atoms)
rot = '35x,63y,36z'  # found using ag: 'view -> rotate'

# Common kwargs for eps, png, pov
kwargs = {
    'rotation'      : rot, # text string with rotation (default='' )
    'radii'         : .85, # float, or a list with one float per atom
Esempio n. 29
0
    def test_locations_k3(self):
        """Tests that the function used to query combination locations for k=2
        in the output works.
        """

        CO2 = molecule("CO2")
        H2O = molecule("H2O")
        descriptors = [
            copy.deepcopy(default_desc_k3),
            copy.deepcopy(default_desc_k2_k3),
        ]

        for desc in descriptors:
            desc.periodic = False
            desc.species = ["H", "O", "C"]
            co2_out = desc.create(CO2, positions=[1])[0, :]
            h2o_out = desc.create(H2O, positions=[1])[0, :]

            loc_xhh = desc.get_location(("X", "H", "H"))
            loc_xho = desc.get_location(("X", "H", "O"))
            loc_xhc = desc.get_location(("X", "H", "C"))
            loc_xoh = desc.get_location(("X", "O", "H"))
            loc_xoo = desc.get_location(("X", "O", "O"))
            loc_xoc = desc.get_location(("X", "O", "C"))
            loc_xch = desc.get_location(("X", "C", "H"))
            loc_xco = desc.get_location(("X", "C", "O"))
            loc_xcc = desc.get_location(("X", "C", "C"))
            loc_hxh = desc.get_location(("H", "X", "H"))
            loc_hxo = desc.get_location(("H", "X", "O"))
            loc_hxc = desc.get_location(("H", "X", "C"))
            loc_cxo = desc.get_location(("C", "X", "O"))
            loc_oxo = desc.get_location(("O", "X", "O"))
            loc_cxc = desc.get_location(("C", "X", "C"))

            # X-H-H
            self.assertTrue(co2_out[loc_xhh].sum() == 0)
            self.assertTrue(h2o_out[loc_xhh].sum() == 0)

            # X-H-O
            self.assertTrue(co2_out[loc_xho].sum() == 0)
            self.assertTrue(h2o_out[loc_xho].sum() != 0)

            # X-H-C
            self.assertTrue(co2_out[loc_xhc].sum() == 0)
            self.assertTrue(h2o_out[loc_xhc].sum() == 0)

            # X-O-H
            self.assertTrue(co2_out[loc_xoh].sum() == 0)
            self.assertTrue(h2o_out[loc_xoh].sum() != 0)

            # X-O-O
            self.assertTrue(co2_out[loc_xoo].sum() == 0)
            self.assertTrue(h2o_out[loc_xoo].sum() == 0)

            # X-O-C
            self.assertTrue(co2_out[loc_xoc].sum() != 0)
            self.assertTrue(h2o_out[loc_xoc].sum() == 0)

            # X-C-H
            self.assertTrue(co2_out[loc_xch].sum() == 0)
            self.assertTrue(h2o_out[loc_xch].sum() == 0)

            # X-C-O
            self.assertTrue(co2_out[loc_xco].sum() != 0)
            self.assertTrue(h2o_out[loc_xco].sum() == 0)

            # X-C-C
            self.assertTrue(co2_out[loc_xcc].sum() == 0)
            self.assertTrue(h2o_out[loc_xcc].sum() == 0)

            # H-X-H
            self.assertTrue(co2_out[loc_hxh].sum() == 0)
            self.assertTrue(h2o_out[loc_hxh].sum() == 0)

            # H-X-O
            self.assertTrue(co2_out[loc_hxo].sum() == 0)
            self.assertTrue(h2o_out[loc_hxo].sum() != 0)

            # H-X-C
            self.assertTrue(co2_out[loc_hxc].sum() == 0)
            self.assertTrue(h2o_out[loc_hxc].sum() == 0)

            # C-X-O
            self.assertTrue(co2_out[loc_cxo].sum() != 0)
            self.assertTrue(h2o_out[loc_cxo].sum() == 0)

            # O-X-O
            self.assertTrue(co2_out[loc_oxo].sum() == 0)
            self.assertTrue(h2o_out[loc_oxo].sum() == 0)

            # C-X-C
            self.assertTrue(co2_out[loc_cxc].sum() == 0)
            self.assertTrue(h2o_out[loc_cxc].sum() == 0)
Esempio n. 30
0
from ase.calculators.dftb import Dftb
from ase.optimize import QuasiNewton
from ase.io import write

from ase.build import molecule
test = molecule('H2O')
test.set_calculator(Dftb(label='h2o',
                         atoms=test,
                         Hamiltonian_MaxAngularMomentum_='',
                         Hamiltonian_MaxAngularMomentum_O='"p"',
                         Hamiltonian_MaxAngularMomentum_H='"s"',
                         ))

dyn = QuasiNewton(test, trajectory='test.traj')
dyn.run(fmax=0.01)
write('test.final.xyz', test)
Esempio n. 31
0
# fun collision of:  2 H2 + O2 -> 2 H2O
import os
from ase.io import read, write
from ase.io.dftb import read_dftb_velocities, write_dftb_velocities
from ase.calculators.dftb import Dftb
from ase.build import molecule

o2 = molecule('O2')
h2_1 = molecule('H2')
h2_2 = molecule('H2')
o2.translate([0, 0.01, 0])
h2_1.translate([0, 0, 3])
h2_1.euler_rotate(center='COP', theta=90)
h2_2.translate([0, 0, -3])
h2_2.euler_rotate(center='COP', theta=90)
o2.set_velocities(([0, 0, 0], [0, 0, 0]))
h2_1.set_velocities(([0, 0, -3.00], [0, 0, -3.000]))
h2_2.set_velocities(([0, 0, 3.000], [0, 0, 3.000]))
atoms = o2 + h2_1 + h2_2

# 1fs = 41.3 au
# 1000K = 0.0031668 au
calculator_NVE = Dftb(atoms=atoms,
                      label='h2o',
                      Hamiltonian_MaxAngularMomentum_='',
                      Hamiltonian_MaxAngularMomentum_O='p',
                      Hamiltonian_MaxAngularMomentum_H='s',
                      Driver_='VelocityVerlet',
                      Driver_MDRestartFrequency=10,
                      Driver_Velocities_='',
                      Driver_Velocities_empty='<<+ "velocities.txt"',
Esempio n. 32
0
    cu_bulk.set_calculator(calc)

    e = cu_bulk.get_potential_energy()
    energies.append(e)
    volumes.append(cu_bulk.get_volume())

eos = EquationOfState(volumes, energies)
v0, e0, B = eos.fit()
aref = 3.6
vref = bulk("Cu", "fcc", a=aref).get_volume()

copper_lattice_constant = (v0 / vref)**(1 / 3) * aref

slab = fcc100("Cu", a=copper_lattice_constant, size=(2, 2, 3))
ads = molecule("C")
add_adsorbate(slab, ads, 3, offset=(1, 1))
cons = FixAtoms(indices=[atom.index for atom in slab if (atom.tag == 3)])
slab.set_constraint(cons)
slab.center(vacuum=13.0, axis=2)
slab.set_pbc(True)
slab.wrap(pbc=[True] * 3)
slab.set_calculator(copy.copy(parent_calc))
slab.set_initial_magnetic_moments()

images = [slab]

Gs = {
    "default": {
        "G2": {
            "etas": np.logspace(np.log10(0.05), np.log10(5.0), num=4),
import sys

from ase.build import molecule, fcc111, add_adsorbate
from ase.optimize import QuasiNewton
from ase.constraints import FixAtoms
from ase.calculators.emt import EMT
from ase.vibrations import Vibrations

sys.path.append("..")

from __init__ import AnharmonicModes

slab = fcc111('Au', size=(2, 2, 2), vacuum=4.0)
H = molecule('H')
add_adsorbate(slab, H, 3.0, 'ontop')

constraint = FixAtoms(mask=[a.symbol == 'Au' for a in slab])
slab.set_constraint(constraint)

slab.set_calculator(EMT())

QuasiNewton(slab).run(fmax=0.001)

vib = Vibrations(slab, indices=[8])
vib.run()
vib.summary()
vib.clean()

AM = AnharmonicModes(
    vibrations_object=vib,
    settings={
Esempio n. 34
0
from ase.calculators.octopus import Octopus
from ase.build import molecule
from ase.optimize import QuasiNewton

# Ethanol molecule with somewhat randomized initial positions:
system = molecule('CH3CH2OH')
system.rattle(stdev=0.1, seed=42)
system.center(vacuum=3.0)

calc = Octopus(label='ethanol', Spacing=0.25, BoxShape='parallelepiped')
system.set_calculator(calc)

opt = QuasiNewton(system, logfile='opt.log', trajectory='opt.traj')
opt.run(fmax=0.05)
import sys
sys.path.append("..")

from ase.build import molecule, fcc111, add_adsorbate
from ase.optimize import QuasiNewton
from ase.constraints import FixAtoms
from ase.calculators.emt import EMT
from ase.vibrations import Vibrations

from __init__ import AnharmonicModes

slab = fcc111('Al', size=(2, 2, 2), vacuum=3.0)
CH3 = molecule('CH3')
add_adsorbate(slab, CH3, 2.5, 'ontop')

constraint = FixAtoms(mask=[a.symbol == 'Al' for a in slab])
slab.set_constraint(constraint)
slab.set_calculator(EMT())

dyn = QuasiNewton(slab, logfile='/dev/null')
dyn.run(fmax=0.05)

vib = Vibrations(slab, indices=[8, 9, 10, 11])
vib.run()
vib.summary(log='/dev/null')
vib.clean()

AM = AnharmonicModes(vibrations_object=vib)
rot_mode = AM.define_rotation(
    basepos=[0., 0., -1.],
    branch=[9, 10, 11],
Esempio n. 36
0
def rotate(gui):
    gui.new_atoms(molecule('H2O'))
    gui.rotate_window()
from ase import Atoms
from ase.units import Bohr
import numpy as np
from qeManager.pwscf import *
from ase.build import molecule

atoms = molecule("NH3")
atoms.set_pbc([True, True, True])
cell = np.array([16.0, 16.0, 16.0]) * Bohr
atoms.set_cell(cell)
atoms.center()

# Create CONTROL namelist of PWSCF input
ctrl_NL = ControlNameList()  # using default parameters
ctrl_NL.pseudo_dir = "/home/efefer/pseudo"  # modify pseudo_dir directly
ctrl_NL.write_all()  # write all parameters, including defaults to stdout

# also do the same for SYSTEM and ELECTRONS

sys_NL = SystemNameList(atoms)

#sys_NL.occupations = "smearing"
#sys_NL.smearing = "mv"
#sys_NL.degauss = 0.001

sys_NL.ecutwfc = 60.0
sys_NL.ecutrho = 240.0
sys_NL.write_all()

elec_NL = ElectronsNameList()
elec_NL.mixing_beta = 0.1
Esempio n. 38
0
#setup the gpaw calculation
from ase.build import molecule
struc = molecule('C6H6')
from ase.io import read, write
from gpaw import GPAW
from ase.units import Bohr
from ase.units import Hartree
#from ase.optimize import FIRE #Quasi Newton + friction
from ase.optimize.bfgslinesearch import BFGSLineSearch  #Quasi Newton

import os.path
traj_file = 'benzene.traj'

if not os.path.isfile(traj_file):
    struc.set_cell([15, 15, 15])
    struc.set_pbc([0, 0, 0])
    struc.center()
    calc = GPAW(xc='PBE',
                h=0.2,
                charge=0,
                spinpol=True,
                convergence={'energy': 0.001})

    struc.set_calculator(calc)
    #opt   = FIRE(struc, trajectory='benzene.traj', logfile='fire.log')
    dyn = BFGSLineSearch(struc,
                         trajectory=traj_file,
                         restart='bfgs_ls.pckl',
                         logfile='BFGSLinSearch.log')
    dyn.run(fmax=0.05)
Esempio n. 39
0
        default='esp.csv', help="Electrostatic potential and x,y,z coordinates"
                " as four-valued lines of .8 digits precision mantissa"
                " notation, default 'esp.csv'")
parser.add_argument('outfile_rho_cube', nargs='?', metavar='outfile_rho.cube',
        default='rho.cube', help="All-electron density in GAUSSIAN-native .cube"
        " format, default 'rho.cube'")
parser.add_argument('outfile_rho_pseudo_cube', nargs='?',
        metavar='outfile_rho_pseudo.cube', default='rho_pseudo.cube',
        help="All-electron density in GAUSSIAN-native .cube format, default"
        "'rho_pseudo.cube'")

args = parser.parse_args()

charge = args.charge

struc = molecule('H2O')
struc.set_pbc([0,0,0])
struc.set_cell([10,10,10])
struc.center()

calc  = GPAW(xc='PBE', h=0.2, charge=charge,
             spinpol=True, convergence={'energy': 0.001})
struc.set_calculator(calc)

# ESP from non-optimized H2O structure

Epot  = struc.get_potential_energy()

# https://wiki.fysik.dtu.dk/gpaw/devel/electrostatic_potential.html tells us, the
# get_electrostatic_corrections() method will return an array of integrated 
# corrections with the unit
Esempio n. 40
0
from matplotlib.animation import writers
from ase.test.testsuite import NotAvailable
from ase.build import bulk, molecule, fcc111
from ase.io.animation import write_animation
import warnings

if 'html' not in writers.list():
    raise NotAvailable('matplotlib html writer not present')

images = [molecule('H2O'), bulk('Cu'), fcc111('Au', size=(1, 1, 1))]

# gif and mp4 writers may not be available.  Easiest solution is to only
# test this using the html writer because it always exists whenever
# matplotlib exists:
with warnings.catch_warnings():
    try:
        from matplotlib import MatplotlibDeprecationWarning
    except ImportError:
        pass
    else:
        warnings.simplefilter('ignore', MatplotlibDeprecationWarning)
    write_animation('things.html', images, writer='html')
Esempio n. 41
0
from ase.build import molecule
from gpaw import GPAW

atoms = molecule('C6H6')
atoms.center(vacuum=3.5)

calc = GPAW(h=.21, xc='PBE', txt='benzene.txt', nbands=18)
atoms.set_calculator(calc)
atoms.get_potential_energy()

calc.set(fixdensity=True, txt='benzene-harris.txt',
         nbands=40, eigensolver='cg', convergence={'bands': 35})
atoms.get_potential_energy()

calc.write('benzene.gpw', mode='all')
Esempio n. 42
0
# Check that atoms object mismatches are detected properly across CPUs.

from ase.build import molecule
from gpaw.mpi import world, synchronize_atoms

system = molecule('H2O')
synchronize_atoms(system, world)

if world.rank == 1:
    system.positions[1, 1] += 1e-8  # fail (above tolerance)
if world.rank == 2:
    system.cell[0, 0] += 1e-15  # fail (zero tolerance)
if world.rank == 3:
    system.positions[1, 1] += 1e-10  # pass (below tolerance)

expected_err_ranks = {1: [], 2: [1]}.get(world.size, [1, 2])

try:
    synchronize_atoms(system, world, tolerance=1e-9)
except ValueError as e:
    assert (expected_err_ranks == e.args[1]).all()
else:
    assert world.size == 1
Esempio n. 43
0
    def test_find_connectivity(self):
        atoms = molecule('C2H6')
        bonds_ref = [(0, 1), (0, 2), (0, 3), (0, 4), (1, 5), (1, 6), (1, 7)]

        bonds = find_connectivity(atoms)
        self.assertListEqual(bonds, bonds_ref)
Esempio n. 44
0
def open_and_save(gui):
    mol = molecule('H2O')
    for i in range(3):
        mol.write('h2o.json')
    gui.open(filename='h2o.json')
    save_dialog(gui, 'h2o.cif@-1')
Esempio n. 45
0
from __future__ import print_function
from ase.build import molecule
from gpaw import GPAW, PW
from gpaw.test import equal
from gpaw.xc.rpa import RPACorrelation
from gpaw.xc.exx import EXX

ecut = 25

N2 = molecule('N2')
N2.center(vacuum=2.0)

calc = GPAW(mode=PW(force_complex_dtype=True),
            xc='PBE',
            parallel={'domain': 1},
            eigensolver='rmm-diis')
N2.set_calculator(calc)
E_n2_pbe = N2.get_potential_energy()

calc.diagonalize_full_hamiltonian(nbands=104, scalapack=True)
calc.write('N2.gpw', mode='all')

exx = EXX('N2.gpw')
exx.calculate()
E_n2_hf = exx.get_total_energy()

rpa = RPACorrelation('N2.gpw', nfrequencies=8)
E_n2_rpa = rpa.calculate(ecut=[ecut])

N = molecule('N')
N.set_cell(N2.cell)
Esempio n. 46
0
"""Demostrates how global similarity kernels can be built from local atomic
environments.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import (bytes, str, open, super, range, zip, round, input, int,
                      pow, object)

from dscribe.descriptors import SOAP
from dscribe.kernels import AverageKernel

from ase.build import molecule

# We will compare two similar molecules
a = molecule("H2O")
b = molecule("H2O2")

# First we will have to create the features for atomic environments. Lets
# use SOAP.
desc = SOAP(species=[1, 6, 7, 8],
            rcut=5.0,
            nmax=2,
            lmax=2,
            sigma=0.2,
            periodic=False,
            crossover=True,
            sparse=False)
a_features = desc.create(a)
b_features = desc.create(b)

# Calculates the similarity with an average kernel and a linear metric. The
# result will be a full similarity matrix.
Esempio n. 47
0
 def execute(self, context):
     #print(molecule_str)
     blpanel = context.scene.blpanel
     atoms = molecule(blpanel.atoms_str)
     import_blase(atoms, name = blpanel.atoms_name, model_type = blpanel.model_type_add)
     return {'FINISHED'}
Esempio n. 48
0
def run_dftb3_test(test=None, tol=0.05):
    mio_database_folder = os.getenv('MIO')
    if mio_database_folder is None:
        raise RuntimeError('Please use environment variable MIO to specify path to mio Slater-Koster tables.')
    dftb3_database_folder = os.getenv('DFTB3')
    if dftb3_database_folder is None:
        raise RuntimeError('Please use environment variable DFTB3 to specify path to 3ob Slater-Koster tables.')

    dftb2_calc = Atomistica(
        [ native.TightBinding(
        database_folder = mio_database_folder,
        SolverLAPACK = dict(electronic_T=0.001),
        SCC = dict(dq_crit = 1e-6,
                   mixing = 0.05, # 0.2
                   andersen_memory = 15, # 3
                   maximum_iterations = 100,
                   log = True)
        ),
          native.DirectCoulomb(),
          native.SlaterCharges(cutoff=10.0) ],
        avgn = 1000
        )

    dftb2_XH_calc = Atomistica(
        [ native.TightBinding(
        database_folder = mio_database_folder,
        SolverLAPACK = dict(electronic_T=0.001),
        SCC = dict(dq_crit = 1e-6,
                   mixing = 0.05, # 0.2
                   andersen_memory = 15, # 3
                   maximum_iterations = 100,
                   log = True)
        ),
          native.DirectCoulomb(),
          native.SlaterCharges(cutoff=10.0, damp_gamma=True, zeta = 3.70) ],
        avgn = 1000
        )

    dftb3_calc = Atomistica(
        [ native.TightBinding(
        database_folder = mio_database_folder,
        SolverLAPACK = dict(electronic_T=0.001),
        SCC = dict(dq_crit = 1e-6,
                   mixing = 0.05, # 0.2
                   andersen_memory = 15, # 3
                   maximum_iterations = 100,
                   log = True)
        ),
          native.DirectCoulomb(),
          native.SlaterCharges(cutoff=10.0, dftb3=True,  
                               HubbardDerivatives=dict(H=-0.1857, O=-0.1575)) ],
        avgn = 1000
        )

    dftb3_XH_calc = Atomistica(
        [ native.TightBinding(
        database_folder = mio_database_folder,
        SolverLAPACK = dict(electronic_T=0.001),
        SCC = dict(dq_crit = 1e-6,
                   mixing = 0.05, # 0.2
                   andersen_memory = 15, # 3
                   maximum_iterations = 100,
                   log = True)
        ),
          native.DirectCoulomb(),
          native.SlaterCharges(cutoff=10.0, dftb3=True, damp_gamma=True, zeta = 4.05, 
                               HubbardDerivatives=dict(H=-0.1857, O=-0.1575)) ],
        avgn = 1000
        )

    dftb3_XH_3ob_calc = Atomistica(
        [ native.TightBinding(
        database_folder = dftb3_database_folder,
        SolverLAPACK = dict(electronic_T=0.001),
        SCC = dict(dq_crit = 1e-6,
                   mixing = 0.05, # 0.2
                   andersen_memory = 15, # 3
                   maximum_iterations = 100,
                   log = True)
        ),
          native.DirectCoulomb(),
          native.SlaterCharges(cutoff=10.0, dftb3=True, damp_gamma=True, zeta = 4.00,
                               HubbardDerivatives=dict(H=-0.1857, O=-0.1575)) ],
        avgn = 1000
        )

    if test is None:
        print('    nH2O|    G3B3|    DFTB2 (MIO)  | DFTB2+XH (MIO)  |    DFTB3 (MIO)  | DFTB3+XH (MIO)  | DFTB3+XH (3OB)  |')
        print('        |        |     me    ref.  |     me    ref.  |     me    ref.  |     me    ref.  |     me    ref.  |')
        print('        |        |-----------------|-----------------|-----------------|-----------------|-----------------|')

    for name, data in table5_data.items():
        e0_DFTB2        = 0.0
        e0_DFTB3        = 0.0
        e0_DFTB2_XH     = 0.0
        e0_DFTB3_XH     = 0.0
        e0_DFTB3_3ob_XH = 0.0
        for structure in data['reference_structures']:
            if os.path.exists(structure):
                a = read(structure)
            else:
                a = molecule(structure)

            a.center(vacuum=10.0)
            a.set_calculator(dftb2_calc)
            FIRE(a, logfile=None).run(fmax=0.001)
            e0_DFTB2 += a.get_potential_energy()

            a.set_calculator(dftb2_XH_calc)
            FIRE(a, logfile=None).run(fmax=0.001)
            e0_DFTB2_XH += a.get_potential_energy()

            a.set_calculator(dftb3_calc)
            FIRE(a, logfile=None).run(fmax=0.001)
            e0_DFTB3 += a.get_potential_energy()

            a.set_calculator(dftb3_XH_calc)
            FIRE(a, logfile=None).run(fmax=0.001)
            e0_DFTB3_XH += a.get_potential_energy()

            a.set_calculator(dftb3_XH_3ob_calc)
            FIRE(a, logfile=None).run(fmax=0.001)
            e0_DFTB3_3ob_XH += a.get_potential_energy()

        eref_G3B3 = data['G3B3']
        eref_DFTB2 = data['DFTB2']
        eref_DFTB2_XH = data['DFTB2+XH']
        eref_DFTB3 = data['DFTB3']
        eref_DFTB3_XH = data['DFTB3+XH']
        eref_DFTB3_3ob_XH = data['DFTB3+XH_3ob']

        a = read(data['structure'])
        a.center(vacuum=10.0)
        a.set_calculator(dftb2_calc)
        FIRE(a, logfile=None).run(fmax=0.001)
        e_DFTB2 = a.get_potential_energy()

        e_DFTB2 = (e_DFTB2 - e0_DFTB2)/(ase.units.kcal/ase.units.mol)

        a.set_calculator(dftb2_XH_calc)
        FIRE(a, logfile=None).run(fmax=0.001)
        e_DFTB2_XH = a.get_potential_energy()

        e_DFTB2_XH = (e_DFTB2_XH - e0_DFTB2_XH)/(ase.units.kcal/ase.units.mol)

        a.set_calculator(dftb3_calc)
        FIRE(a, logfile=None).run(fmax=0.001)
        e_DFTB3 = a.get_potential_energy()

        e_DFTB3 = (e_DFTB3 - e0_DFTB3)/(ase.units.kcal/ase.units.mol)

        a.set_calculator(dftb3_XH_calc)
        FIRE(a, logfile=None).run(fmax=0.001)
        e_DFTB3_XH = a.get_potential_energy()

        e_DFTB3_XH = (e_DFTB3_XH - e0_DFTB3_XH)/(ase.units.kcal/ase.units.mol)

        a.set_calculator(dftb3_XH_3ob_calc)
        FIRE(a, logfile=None).run(fmax=0.001)
        e_DFTB3_3ob_XH = a.get_potential_energy()

        e_DFTB3_3ob_XH = (e_DFTB3_3ob_XH - e0_DFTB3_3ob_XH)/(ase.units.kcal/ase.units.mol)

        success_DFTB2 = abs(e_DFTB2 - eref_G3B3 - eref_DFTB2) < tol
        success_DFTB2_XH = abs(e_DFTB2_XH - eref_G3B3 - eref_DFTB2_XH) < tol
        success_DFTB3 = abs(e_DFTB3 - eref_G3B3 - eref_DFTB3) < tol
        success_DFTB3_XH = abs(e_DFTB3_XH - eref_G3B3 - eref_DFTB3_XH) < tol
        success_DFTB3_3ob_XH = abs(e_DFTB3_3ob_XH - eref_G3B3 - eref_DFTB3_3ob_XH) < tol

        success_str = {True: ' ', False: 'X'}

        if test is None:
            print('{0:>8}| {1:>7.3f}|{2:>7.3f} {3:>7.3f} {4}|{5:>7.3f} {6:>7.3f} {7}|{8:>7.3f} {9:>7.3f} {10}|{11:>7.3f} {12:>7.3f} {13}|{14:>7.3f} {15:>7.3f} {16}|'
                .format(name, eref_G3B3, e_DFTB2 - eref_G3B3, eref_DFTB2, success_str[success_DFTB2],
                                         e_DFTB2_XH - eref_G3B3, eref_DFTB2_XH, success_str[success_DFTB2_XH],
                                         e_DFTB3 - eref_G3B3, eref_DFTB3, success_str[success_DFTB3],
                                         e_DFTB3_XH - eref_G3B3, eref_DFTB3_XH, success_str[success_DFTB3_XH],
                                         e_DFTB3_3ob_XH - eref_G3B3, eref_DFTB3_3ob_XH, success_str[success_DFTB3_3ob_XH]))
        else:
            test.assertTrue(success_DFTB2)
            test.assertTrue(success_DFTB2_XH)
            test.assertTrue(success_DFTB3)
            test.assertTrue(success_DFTB3_XH)
            test.assertTrue(success_DFTB3_3ob_XH)
Esempio n. 49
0
    def test_parallel_sparse(self):
        """Tests creating sparse output parallelly."""
        # Test indices
        samples = [molecule("CO"), molecule("N2O")]
        desc = copy.deepcopy(default_desc_k2)
        desc.species = ["C", "O", "N"]
        desc.sparse = True
        n_features = desc.get_number_of_features()

        # Multiple systems, serial job, fixed size
        output = desc.create(
            system=samples,
            positions=[[0, 1], [0, 1]],
            n_jobs=1,
        ).todense()
        assumed = np.empty((2, 2, n_features))
        assumed[0, 0] = desc.create(samples[0], [0]).todense()
        assumed[0, 1] = desc.create(samples[0], [1]).todense()
        assumed[1, 0] = desc.create(samples[1], [0]).todense()
        assumed[1, 1] = desc.create(samples[1], [1]).todense()
        self.assertTrue(np.allclose(output, assumed))

        # Multiple systems, parallel job, fixed size
        output = desc.create(
            system=samples,
            positions=[[0, 1], [0, 1]],
            n_jobs=2,
        ).todense()
        assumed = np.empty((2, 2, n_features))
        assumed[0, 0] = desc.create(samples[0], [0]).todense()
        assumed[0, 1] = desc.create(samples[0], [1]).todense()
        assumed[1, 0] = desc.create(samples[1], [0]).todense()
        assumed[1, 1] = desc.create(samples[1], [1]).todense()
        self.assertTrue(np.allclose(output, assumed))

        # Test with cartesian positions. In this case virtual positions have to
        # be enabled.
        output = desc.create(
            system=samples,
            positions=[[[0, 0, 0]], [[1, 2, 0]]],
            n_jobs=2,
        ).todense()
        assumed = np.empty((2, 1, n_features))
        assumed[0, 0] = desc.create(samples[0], [[0, 0, 0]]).todense()
        assumed[1, 0] = desc.create(samples[1], [[1, 2, 0]]).todense()
        self.assertTrue(np.allclose(output, assumed))

        # Multiple systems, parallel job, indices, variable size
        output = desc.create(
            system=samples,
            positions=[[0], [0, 1]],
            n_jobs=2,
        )
        self.assertTrue(
            np.allclose(output[0][0].todense(),
                        desc.create(samples[0], [0]).todense()))
        self.assertTrue(
            np.allclose(output[1][0].todense(),
                        desc.create(samples[1], [0]).todense()))
        self.assertTrue(
            np.allclose(output[1][1].todense(),
                        desc.create(samples[1], [1]).todense()))
Esempio n. 50
0
def water():
    return molecule('H2O')
Esempio n. 51
0
from ase.build import molecule
from ase.symbols import Symbols

atoms = molecule('CH3CH2OH')
print(atoms.symbols)
atoms.symbols[0] = 'X'
atoms.symbols[2:4] = 'Pu'
atoms.numbers[6:8] = 79

assert atoms.numbers[0] == 0
assert (atoms.numbers[2:4] == 94).all()
assert sum(atoms.symbols == 'Au') == 2
assert (atoms.symbols[6:8] == 'Au').all()
assert (atoms.symbols[:3] == 'XCPu').all()

print(atoms)
print(atoms.numbers)

assert atoms.get_chemical_symbols()
string = str(atoms.symbols)
symbols = Symbols.fromsymbols(string)
assert (symbols == atoms.symbols).all()
Esempio n. 52
0
def test_cif_roundtrip_nonperiodic():
    atoms = molecule('H2O')
    atoms1 = roundtrip(atoms)
    assert not compare_atoms(atoms, atoms1, tol=1e-5)
Esempio n. 53
0
import sys

from ase.build import molecule
from ase.optimize import BFGS
from ase.calculators.nwchem import NWChem
from ase.calculators.socketio import SocketIOCalculator

atoms = molecule('H2O')
atoms.rattle(stdev=0.1)

unixsocket = 'ase_nwchem'

nwchem = NWChem(theory='scf',
                task='optimize',
                driver={'socket': {
                    'unix': unixsocket
                }})

opt = BFGS(atoms, trajectory='opt.traj', logfile='opt.log')

with SocketIOCalculator(nwchem, log=sys.stdout, unixsocket=unixsocket) as calc:
    atoms.calc = calc
    opt.run(fmax=0.05)
Esempio n. 54
0
mbtr = MBTR(atomic_numbers=atomic_numbers,
            k=2,
            periodic=False,
            grid={"k2": {
                "min": 0,
                "max": 1,
                "n": n,
                "sigma": 0.1
            }},
            weighting=None)

# Creating an atomic system as an ase.Atoms-object
from ase.build import molecule
import ase.data

water = molecule("H2O")

# Create MBTR output for the system
mbtr_water = mbtr.create(water)

print(mbtr_water)
print(mbtr_water.shape)

from ase.build import bulk
nacl = bulk("NaCl", "rocksalt", a=5.64)

# Optionally we can preserve the tensorial nature of the data by specifying
# "Flatten" as False. In this case the output will be a list of
# multidimensional numpy arrays for each k-term. This form is easier to
# visualize as done in the following.
import matplotlib.pyplot as plt
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 20 13:54:16 2016

@author: cl-iop
"""
from ase.build import molecule, mx2
from ase.collection import g2, s22
from ase.visualize import view
import os
import shutil
from pyramids.io.output import writeSiesta

for name in g2.names:
  atom = molecule(name)
  atom.cell *= 10 
  if os.path.exists(name): 
    shutil.rmtree(name)
  os.mkdir(name)
  os.chdir(name)
  for element in set(atom.get_chemical_symbols()):
    os.popen('siestapot_LDA.sh '+element)
  writeSiesta('structure.fdf',atom)
  os.chdir('..')  

  
#for name in s22.names:
#  #atom = molecule(name)
#  #atom.cell *= 8 
#  print name
#atom = molecule('trans-butane')
Esempio n. 56
0

@pytest.mark.parametrize('atoms', [
    SimpleCubic(latticeconstant=2, size=(3, 1, 1), symbol='Cu', pbc=(1, 0, 0)),
    SimpleCubic(latticeconstant=2, size=(4, 1, 1), symbol='Cu', pbc=(1, 0, 0)),
    SimpleCubic(latticeconstant=2, size=(7, 1, 1), symbol='Cu', pbc=(1, 0, 0)),
    SimpleCubic(latticeconstant=2, size=(1, 3, 1), symbol='Cu', pbc=(0, 1, 0)),
    SimpleCubic(latticeconstant=2, size=(1, 4, 1), symbol='Cu', pbc=(0, 1, 0)),
    SimpleCubic(latticeconstant=2, size=(1, 7, 1), symbol='Cu', pbc=(0, 1, 0)),
    SimpleCubic(latticeconstant=2, size=(1, 1, 3), symbol='Cu', pbc=(0, 0, 1)),
    SimpleCubic(latticeconstant=2, size=(1, 1, 4), symbol='Cu', pbc=(0, 0, 1)),
    SimpleCubic(latticeconstant=2, size=(1, 1, 7), symbol='Cu', pbc=(0, 0, 1)),
])
def test_ase_pbc2(atoms):
    adj = AtomicAdjacency(shape='tent1', length_scale=1.0, zoom=1)
    graph_pbc = Graph.from_ase(atoms, use_pbc=True, adjacency=adj)
    graph_nopbc = Graph.from_ase(atoms, use_pbc=False, adjacency=adj)
    assert(len(graph_pbc.edges) > len(graph_nopbc.edges))


@pytest.mark.parametrize('atoms', [
    molecule('H2'),
    molecule('CH4'),
    molecule('CH3COOH'),
    SimpleCubic(latticeconstant=1, size=(3, 3, 1), symbol='Cu', pbc=(1, 1, 0)),
])
def test_ase(atoms):
    g = Graph.from_ase(atoms)
    assert(len(g.nodes) == len(atoms))
    assert(len(g.edges) > 0)
Esempio n. 57
0
def test_ase_one():
    atoms = molecule('H2')
    graph = Graph.from_ase(atoms)
    assert(len(graph.nodes) == 2)
    assert(len(graph.edges) == 1)
Esempio n. 58
0
from ase.build import molecule
from ase import optimize
from ase.vibrations.infrared import Infrared

from gpaw.cluster import Cluster
from gpaw import GPAW, FermiDirac

h = 0.22

atoms = Cluster(molecule('H2'))
atoms.minimal_box(3.5, h=h)

# relax the molecule
calc = GPAW(h=h, occupations=FermiDirac(width=0.1))
atoms.calc = calc
dyn = optimize.FIRE(atoms)
dyn.run(fmax=0.05)
atoms.write('relaxed.traj')

# finite displacement for vibrations
atoms.calc.set(symmetry={'point_group': False})
ir = Infrared(atoms)
ir.run()
Esempio n. 59
0
def test_film_operators(seed):
    from ase.ga.startgenerator import StartGenerator
    from ase.ga.cutandsplicepairing import CutAndSplicePairing
    from ase.ga.standardmutations import StrainMutation
    from ase.ga.utilities import (closest_distances_generator, atoms_too_close,
                                  CellBounds)
    import numpy as np
    from ase import Atoms
    from ase.build import molecule

    # set up the random number generator
    rng = np.random.RandomState(seed)

    slab = Atoms('', cell=(0, 0, 15), pbc=[True, True, False])

    cation, anion = 'Mg', molecule('OH')
    d_oh = anion.get_distance(0, 1)
    blocks = [(cation, 4), (anion, 8)]
    n_top = 4 + 8 * len(anion)

    use_tags = True
    num_vcv = 2
    box_volume = 8. * n_top

    blmin = closest_distances_generator(atom_numbers=[1, 8, 12],
                                        ratio_of_covalent_radii=0.6)

    cellbounds = CellBounds(
        bounds={
            'phi': [0.1 * 180., 0.9 * 180.],
            'chi': [0.1 * 180., 0.9 * 180.],
            'psi': [0.1 * 180., 0.9 * 180.],
            'a': [2, 8],
            'b': [2, 8]
        })

    box_to_place_in = [[None, None, 3.], [None, None, [0., 0., 5.]]]

    sg = StartGenerator(slab,
                        blocks,
                        blmin,
                        box_volume=box_volume,
                        splits={(2, 1): 1},
                        box_to_place_in=box_to_place_in,
                        number_of_variable_cell_vectors=num_vcv,
                        cellbounds=cellbounds,
                        test_too_far=True,
                        test_dist_to_slab=False,
                        rng=rng)

    parents = []
    for i in range(2):
        a = None
        while a is None:
            a = sg.get_new_candidate()

        a.info['confid'] = i
        parents.append(a)

        assert len(a) == n_top
        assert len(np.unique(a.get_tags())) == 4 + 8
        assert np.allclose(a.get_pbc(), slab.get_pbc())

        p = a.get_positions()
        assert np.min(p[:, 2]) > 3. - 0.5 * d_oh
        assert np.max(p[:, 2]) < 3. + 5. + 0.5 * d_oh
        assert not atoms_too_close(a, blmin, use_tags=use_tags)

        c = a.get_cell()
        assert np.allclose(c[2], slab.get_cell()[2])
        assert cellbounds.is_within_bounds(c)

        v = a.get_volume() * 5. / 15.
        assert abs(v - box_volume) < 1e-5

    # Test cut-and-splice pairing and strain mutation
    pairing = CutAndSplicePairing(slab,
                                  n_top,
                                  blmin,
                                  number_of_variable_cell_vectors=num_vcv,
                                  p1=1.,
                                  p2=0.,
                                  minfrac=0.15,
                                  cellbounds=cellbounds,
                                  use_tags=use_tags,
                                  rng=rng)

    strainmut = StrainMutation(blmin,
                               cellbounds=cellbounds,
                               number_of_variable_cell_vectors=num_vcv,
                               use_tags=use_tags,
                               rng=rng)
    strainmut.update_scaling_volume(parents)

    for operator in [pairing, strainmut]:
        child = None
        while child is None:
            child, desc = operator.get_new_individual(parents)

        assert not atoms_too_close(child, blmin, use_tags=use_tags)
        cell = child.get_cell()
        assert cellbounds.is_within_bounds(cell)
        assert np.allclose(cell[2], slab.get_cell()[2])
Esempio n. 60
0
# fun collision of:  2 H2 + O2 -> 2 H2O
import os

from ase.calculators.dftb import Dftb
from ase.build import molecule
from ase.md.verlet import VelocityVerlet
from ase.md import MDLogger
from ase.units import fs
from ase.io.dftb import read_dftb_velocities, write_dftb_velocities
from ase.io import read, write

o2 = molecule('O2')
h2_1 = molecule('H2')
h2_2 = molecule('H2')
o2.translate([0, 0.01, 0])
h2_1.translate([0, 0, 3])
h2_1.rotate_euler(center='COP', theta=3.1415 / 2)
h2_2.translate([0, 0, -3])
h2_2.rotate_euler(center='COP', theta=3.1415 / 2)
o2.set_velocities(([0, 0, 0], [0, 0, 0]))
h2_1.set_velocities(([0, 0, -3.00], [0, 0, -3.000]))
h2_2.set_velocities(([0, 0, 3.000], [0, 0, 3.000]))
test = o2 + h2_1 + h2_2

# 1fs = 41.3 au
# 1000K = 0.0031668 au
calculator_NVE = Dftb(label='h2o',
                      atoms=test,
                      run_manyDftb_steps=True,
                      Hamiltonian_MaxAngularMomentum_='',
                      Hamiltonian_MaxAngularMomentum_O='"p"',