def test_lattice_lindep():
    from ase.lattice.cubic import FaceCenteredCubic
    from ase.lattice.hexagonal import HexagonalClosedPacked
    from ase.test import must_raise

    with must_raise(ValueError):
        # The Miller indices of the surfaces are linearly dependent
        atoms = FaceCenteredCubic(symbol='Cu',
                                  miller=[[1, 1, 0], [1, 1, 0], [0, 0, 1]])

    # This one should be OK:
    atoms = FaceCenteredCubic(symbol='Cu',
                              miller=[[1, 1, 0], [0, 1, 0], [0, 0, 1]])
    print(atoms.get_cell())

    with must_raise(ValueError):
        # The directions spanning the unit cell are linearly dependent
        atoms = FaceCenteredCubic(symbol='Cu',
                                  directions=[[1, 1, 0], [1, 1, 0], [0, 0, 1]])

    with must_raise(ValueError):
        # The directions spanning the unit cell are linearly dependent
        atoms = FaceCenteredCubic(symbol='Cu',
                                  directions=[[1, 1, 0], [1, 0, 0], [0, 1, 0]])

    # This one should be OK:
    atoms = FaceCenteredCubic(symbol='Cu',
                              directions=[[1, 1, 0], [0, 1, 0], [0, 0, 1]])
    print(atoms.get_cell())

    with must_raise((ValueError, NotImplementedError)):
        # The Miller indices of the surfaces are linearly dependent
        atoms = HexagonalClosedPacked(symbol='Mg',
                                      miller=[[1, -1, 0, 0], [1, 0, -1, 0],
                                              [0, 1, -1, 0]])

    # This one should be OK
    #
    # It is not!  The miller argument is broken in hexagonal crystals!
    #
    # atoms = HexagonalClosedPacked(symbol='Mg',
    #                               miller=[[1, -1, 0, 0],
    #                                       [1, 0, -1, 0],
    #                                       [0, 0, 0, 1]])
    # print(atoms.get_cell())

    with must_raise(ValueError):
        # The directions spanning the unit cell are linearly dependent
        atoms = HexagonalClosedPacked(symbol='Mg',
                                      directions=[[1, -1, 0, 0], [1, 0, -1, 0],
                                                  [0, 1, -1, 0]])

    # This one should be OK
    atoms = HexagonalClosedPacked(symbol='Mg',
                                  directions=[[1, -1, 0, 0], [1, 0, -1, 0],
                                              [0, 0, 0, 1]])
    print(atoms.get_cell())
def test_readwrite_errors():
    from io import StringIO
    from ase.io import read, write
    from ase.build import bulk
    from ase.test import must_raise
    from ase.io.formats import UnknownFileTypeError

    atoms = bulk('Au')
    fd = StringIO()

    with must_raise(UnknownFileTypeError):
        write(fd, atoms, format='hello')

    with must_raise(UnknownFileTypeError):
        read(fd, format='hello')
Esempio n. 3
0
def test_add_candidates():
    from ase.test import must_raise
    from ase.build import fcc111
    from ase.ga.data import PrepareDB
    from ase.ga.data import DataConnection
    from ase.ga.offspring_creator import OffspringCreator
    from ase.ga import set_raw_score

    import os

    db_file = 'gadb.db'
    if os.path.isfile(db_file):
        os.remove(db_file)

    db = PrepareDB(db_file)

    slab1 = fcc111('Ag', size=(2, 2, 2))
    db.add_unrelaxed_candidate(slab1)

    slab2 = fcc111('Cu', size=(2, 2, 2))
    set_raw_score(slab2, 4)
    db.add_relaxed_candidate(slab2)
    assert slab2.info['confid'] == 3

    db = DataConnection(db_file)
    assert db.get_number_of_unrelaxed_candidates() == 1

    slab3 = db.get_an_unrelaxed_candidate()
    old_confid = slab3.info['confid']
    slab3[0].symbol = 'Au'
    db.add_unrelaxed_candidate(slab3, 'mutated: Parent {0}'.format(old_confid))
    new_confid = slab3.info['confid']
    # confid should update when using add_unrelaxed_candidate
    assert old_confid != new_confid
    slab3[1].symbol = 'Au'
    db.add_unrelaxed_step(slab3, 'mutated: Parent {0}'.format(new_confid))
    # confid should not change when using add_unrelaxed_step
    assert slab3.info['confid'] == new_confid

    with must_raise(AssertionError):
        db.add_relaxed_step(slab3)
    set_raw_score(slab3, 3)
    db.add_relaxed_step(slab3)

    slab4 = OffspringCreator.initialize_individual(slab1,
                                                   fcc111('Au', size=(2, 2, 2)))
    set_raw_score(slab4, 67)
    db.add_relaxed_candidate(slab4)
    assert slab4.info['confid'] == 7

    more_slabs = []
    for m in ['Ni', 'Pd', 'Pt']:
        slab = fcc111(m, size=(2, 2, 2))
        slab = OffspringCreator.initialize_individual(slab1, slab)
        set_raw_score(slab, sum(slab.get_masses()))
        more_slabs.append(slab)
    db.add_more_relaxed_candidates(more_slabs)
    assert more_slabs[1].info['confid'] == 9

    os.remove(db_file)
def test_vasp_charge():
    """
    Run VASP tests to ensure that determining number of electrons from
    user-supplied charge works correctly. This is conditional on the existence
    of the VASP_COMMAND or VASP_SCRIPT environment variables.

    """

    from ase.build import bulk
    from ase.calculators.vasp import Vasp
    from ase.test import must_raise
    from ase.test.vasp import installed

    assert installed()

    system = bulk('Al', 'fcc', a=4.5, cubic=True)

    # Dummy calculation to let VASP determine default number of electrons
    calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False)
    calc.calculate(system)
    default_nelect_from_vasp = calc.get_number_of_electrons()
    assert default_nelect_from_vasp == 12

    # Make sure that no nelect was written into INCAR yet (as it wasn't necessary)
    calc = Vasp()
    calc.read_incar()
    assert calc.float_params['nelect'] is None

    # Compare VASP's output nelect from before minus charge to default nelect
    # determined by us minus charge
    charge = -2
    calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False,
                charge=charge)
    calc.initialize(system)
    calc.write_input(system)
    calc.read_incar()
    assert calc.float_params['nelect'] == default_nelect_from_vasp - charge

    # Test that conflicts between explicitly given nelect and charge are detected
    with must_raise(ValueError):
        calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False,
                    nelect=default_nelect_from_vasp-charge+1,
                    charge=charge)
        calc.calculate(system)

    # Test that nothing is written if charge is 0 and nelect not given
    calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False,
                charge=0)
    calc.initialize(system)
    calc.write_input(system)
    calc.read_incar()
    assert calc.float_params['nelect'] is None

    # Test that explicitly given nelect still works as expected
    calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False,
                nelect=15)
    calc.calculate(system)
    assert calc.get_number_of_electrons() == 15
Esempio n. 5
0
def test_lock():
    """Test timeout on Lock.acquire()."""
    from ase.utils import Lock
    from ase.test import must_raise

    lock = Lock('lockfile', timeout=0.3)
    with lock:
        with must_raise(TimeoutError):
            with lock:
                ...
Esempio n. 6
0
def test_delete():
    db = connect(full_db_name())

    h2o = molecule('H2O')
    uid = db.write(h2o, type='molecule')

    # Make sure that we can get the value
    db.get(id=uid)
    db.delete([uid])

    with must_raise(KeyError):
        db.get(id=uid)
Esempio n. 7
0
def test_vasp_cell():
    """

    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(RuntimeError):
        atoms.write('POSCAR')

    with must_raise(ValueError):
        atoms.calc = calc
        atoms.get_total_energy()
Esempio n. 8
0
def test_vasp_input():
    """

    Check VASP input handling

    """

    from ase.calculators.vasp.create_input import _args_without_comment
    from ase.calculators.vasp.create_input import _to_vasp_bool, _from_vasp_bool

    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(RuntimeError):
        atoms.write('POSCAR')

    with must_raise(ValueError):
        atoms.set_calculator(calc)
        atoms.get_total_energy()

    # Comment splitting logic

    clean_args = _args_without_comment(['a', 'b', '#', 'c'])
    assert len(clean_args) == 2
    clean_args = _args_without_comment(['a', 'b', '!', 'c', '#', 'd'])
    assert len(clean_args) == 2
    clean_args = _args_without_comment(['#', 'a', 'b', '!', 'c', '#', 'd'])
    assert len(clean_args) == 0

    # Boolean handling: input

    for s in ('T', '.true.'):
        assert (_from_vasp_bool(s) is True)
    for s in ('f', '.False.'):
        assert (_from_vasp_bool(s) is False)
    with must_raise(ValueError):
        _from_vasp_bool('yes')
    with must_raise(AssertionError):
        _from_vasp_bool(True)

    # Boolean handling: output

    for x in ('T', '.true.', True):
        assert (_to_vasp_bool(x) == '.TRUE.')
    for x in ('f', '.FALSE.', False):
        assert (_to_vasp_bool(x) == '.FALSE.')

    with must_raise(ValueError):
        _to_vasp_bool('yes')
    with must_raise(AssertionError):
        _from_vasp_bool(1)
Esempio n. 9
0
def test_vasp2_cell():
    """

    Check the unit cell is handled correctly

    """

    from ase.test.vasp import installed2 as installed
    from ase.calculators.vasp import Vasp2 as Vasp
    from ase.build import molecule
    from ase.test import must_raise
    assert installed()

    # 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. 10
0
t = Trajectory(fname, 'a', co)
t.close()
os.remove(fname)

t = Trajectory('empty.traj', 'w')
t.close()
t = Trajectory('empty.traj', 'r')
assert len(t) == 0

t = Trajectory('fake.traj', 'w')
t.write(Atoms('H'), energy=-42.0, forces=[[1, 2, 3]])

t = Trajectory('only-energy.traj', 'w', properties=['energy'])
a = read('fake.traj')
t.write(a)
b = read('only-energy.traj')
e = b.get_potential_energy()
assert e + 42 == 0
with must_raise(PropertyNotImplementedError):
    f = b.get_forces()

# Make sure constraints play well with momenta:
a = Atoms('H2',
          positions=[(0, 0, 0), (0, 0, 1)],
          momenta=[(1, 0, 0), (0, 0, 0)])
a.constraints = [FixBondLength(0, 1)]
t = Trajectory('constraint.traj', 'w', a)
t.write()
b = read('constraint.traj')
assert not (b.get_momenta() - a.get_momenta()).any()
Esempio n. 11
0
"""Test timeout on Lock.acquire()."""
from ase.utils import Lock
from ase.test import must_raise

lock = Lock('lockfile', timeout=0.3)
with lock:
    with must_raise(TimeoutError):
        with lock:
            ...
Esempio n. 12
0
    print(f1)
    
    c.delete([d.id for d in c.select(C=1)])
    chi = np.array([1 + 0.5j, 0.5])
    id = c.write(ch4, data={'1-butyne': 'bla-bla', 'chi': chi})

    row = c.get(id)
    print(row.data['1-butyne'], row.data.chi)
    assert (row.data.chi == chi).all()
    
    assert len(c.get_atoms(C=1).constraints) == 2

    f2 = c.get(C=1).forces
    assert abs(f2.sum(0)).max() < 1e-14
    f3 = c.get_atoms(C=1).get_forces()
    assert abs(f1 - f3).max() < 1e-14
    a = read(name + '@id=' + str(id))[0]
    f4 = a.get_forces()
    assert abs(f1 - f4).max() < 1e-14

    with must_raise(ValueError):
        c.update(id, abc={'a': 42})

    c.update(id, grr='hmm')
    row = c.get(C=1)
    assert row.id == id
    assert (row.data.chi == chi).all()

    with must_raise(ValueError):
        c.write(ch4, foo=['bar', 2])
Esempio n. 13
0
    def test_insert_in_external_tables(db_name):
        atoms = Atoms()
        db = connect(db_name)

        # Now a table called insert_tab with schema datatype REAL should
        # be created
        uid = db.write(
            atoms,
            external_tables={"insert_tab": {
                "rate": 1.0,
                "rate1": -2.0
            }})

        db.delete([uid])

        # Hack: retrieve the connection
        con = db._connect()
        cur = con.cursor()

        sql = "SELECT * FROM insert_tab WHERE ID=?"
        cur.execute(sql, (uid, ))

        entries = [x for x in cur.fetchall()]
        if db.connection is None:
            con.close()
        assert not entries

        # Make sure that there are now entries in the
        # external table with current uid

        # Try to insert something that should not pass
        # i.e. string value into the same table
        with must_raise(ValueError):
            db.write(atoms,
                     external_tables={"insert_tab": {
                         "rate": "something"
                     }})

        # Try to insert Numpy floats
        db.write(atoms,
                 external_tables={"insert_tab": {
                     "rate": np.float32(1.0)
                 }})
        db.write(atoms,
                 external_tables={"insert_tab": {
                     "rate": np.float64(1.0)
                 }})

        # Make sure that we cannot insert a Numpy integer types into
        # a float array
        with must_raise(ValueError):
            db.write(atoms,
                     external_tables={"insert_tab": {
                         "rate": np.int32(1.0)
                     }})

        with must_raise(ValueError):
            db.write(atoms,
                     external_tables={"insert_tab": {
                         "rate": np.int64(1.0)
                     }})

        # Create a new table should have INTEGER types
        db.write(atoms, external_tables={"integer_tab": {"rate": 1}})

        # Make sure we can insert Numpy integers
        db.write(atoms, external_tables={"integer_tab": {"rate": np.int32(1)}})
        db.write(atoms, external_tables={"integer_tab": {"rate": np.int64(1)}})

        # Make sure that we cannot insert float
        with must_raise(ValueError):
            db.write(atoms,
                     external_tables={"integer_tab": {
                         "rate": np.float32(1)
                     }})

        with must_raise(ValueError):
            db.write(atoms,
                     external_tables={"integer_tab": {
                         "rate": np.float64(1)
                     }})

        # Make sure that ValueError is raised with mixed datatypes
        with must_raise(ValueError):
            db.write(
                atoms,
                external_tables={"integer_tab": {
                    "rate": 1,
                    "rate2": 2.0
                }})

        # Test that we cannot insert anything into a reserved table name
        from ase.db.sqlite import all_tables
        for tab_name in all_tables:
            with must_raise(ValueError):
                db.write(atoms, external_tables={tab_name: {"value": 1}})
Esempio n. 14
0
def test_trajectory():
    from ase.test import must_raise

    import os
    from ase import Atom, Atoms
    from ase.io import Trajectory, read
    from ase.constraints import FixBondLength
    from ase.calculators.calculator import PropertyNotImplementedError

    co = Atoms([Atom('C', (0, 0, 0)),
                Atom('O', (0, 0, 1.2))])
    traj = Trajectory('1.traj', 'w', co)

    written = []

    for i in range(5):
        co.positions[:, 2] += 0.1
        traj.write()
        written.append(co.copy())

    traj = Trajectory('1.traj', 'a')
    co = read('1.traj')
    print(co.positions)
    co.positions[:] += 1
    traj.write(co)
    written.append(co.copy())

    for a in Trajectory('1.traj'):
        print(1, a.positions[-1, 2])
    co.positions[:] += 1
    t = Trajectory('1.traj', 'a')
    t.write(co)
    written.append(co.copy())
    assert len(t) == 7

    co[0].number = 1
    t.write(co)
    written.append(co.copy())

    co[0].number = 6
    co.pbc = True
    t.write(co)
    written.append(co.copy())

    co.pbc = False
    o = co.pop(1)
    t.write(co)
    written.append(co.copy())

    co.append(o)
    t.write(co)
    written.append(co.copy())

    imgs = read('1.traj', index=':')
    assert len(imgs) == len(written)
    for img1, img2 in zip(imgs, written):
        assert img1 == img2

    # Verify slicing works.
    read_traj = Trajectory('1.traj', 'r')
    sliced_traj = read_traj[3:8]
    assert len(sliced_traj) == 5
    sliced_again = sliced_traj[1:-1]
    assert len(sliced_again) == 3
    assert sliced_traj[1] == sliced_again[0]

    # append to a nonexisting file:
    fname = '2.traj'
    if os.path.isfile(fname):
        os.remove(fname)
    t = Trajectory(fname, 'a', co)
    t.close()
    os.remove(fname)

    t = Trajectory('empty.traj', 'w')
    t.close()
    t = Trajectory('empty.traj', 'r')
    assert len(t) == 0

    t = Trajectory('fake.traj', 'w')
    t.write(Atoms('H'), energy=-42.0, forces=[[1, 2, 3]])

    t = Trajectory('only-energy.traj', 'w', properties=['energy'])
    a = read('fake.traj')
    t.write(a)
    b = read('only-energy.traj')
    e = b.get_potential_energy()
    assert e + 42 == 0
    with must_raise(PropertyNotImplementedError):
        b.get_forces()

    # Make sure constraints play well with momenta:
    a = Atoms('H2',
              positions=[(0, 0, 0), (0, 0, 1)],
              momenta=[(1, 0, 0), (0, 0, 0)])
    a.constraints = [FixBondLength(0, 1)]
    t = Trajectory('constraint.traj', 'w', a)
    t.write()
    b = read('constraint.traj')
    assert not (b.get_momenta() - a.get_momenta()).any()
Esempio n. 15
0
"""Make sure we can't read old traj file, but we can convert them."""
import ase.io as aio
from ase import Atoms
from ase.io.pickletrajectory import PickleTrajectory
from ase.io.trajectory import convert
from ase.test import must_raise


t = PickleTrajectory('hmm.traj', 'w', _warn=False)
a = Atoms('H')
t.write(a)
t.close()

with must_raise(DeprecationWarning):
    aio.read('hmm.traj')
    
convert('hmm.traj')
aio.read('hmm.traj')
Esempio n. 16
0
from io import StringIO
from ase.io import read, write
from ase.build import bulk
from ase.test import must_raise
from ase.io.formats import UnknownFileTypeError

atoms = bulk('Au')
fd = StringIO()

with must_raise(UnknownFileTypeError):
    write(fd, atoms, format='hello')

with must_raise(UnknownFileTypeError):
    read(fd, format='hello')
Esempio n. 17
0
def test_vasp_net_charge():
    """
    Run VASP tests to ensure that determining number of electrons from
    user-supplied net charge (via the deprecated net_charge parameter) works
    correctly. This is conditional on the existence of the VASP_COMMAND or
    VASP_SCRIPT environment variables.

    This is mainly a slightly reduced duplicate of the vasp_charge test, but with
    flipped signs and with checks that ensure FutureWarning is emitted.

    Should be removed along with the net_charge parameter itself at some point.
    """

    from ase.build import bulk
    from ase.calculators.vasp import Vasp
    from ase.test import must_raise, must_warn
    from ase.test.vasp import installed

    assert installed()

    system = bulk('Al', 'fcc', a=4.5, cubic=True)

    # Dummy calculation to let VASP determine default number of electrons
    calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False)
    calc.calculate(system)
    default_nelect_from_vasp = calc.get_number_of_electrons()
    assert default_nelect_from_vasp == 12

    # Compare VASP's output nelect from before + net charge to default nelect
    # determined by us + net charge
    with must_warn(FutureWarning):
        net_charge = -2
        calc = Vasp(xc='LDA',
                    nsw=-1,
                    ibrion=-1,
                    nelm=1,
                    lwave=False,
                    lcharg=False,
                    net_charge=net_charge)
        calc.initialize(system)
        calc.write_input(system)
        calc.read_incar()
    assert calc.float_params['nelect'] == default_nelect_from_vasp + net_charge

    # Test that conflicts between explicitly given nelect and net charge are
    # detected
    with must_raise(ValueError):
        with must_warn(FutureWarning):
            calc = Vasp(xc='LDA',
                        nsw=-1,
                        ibrion=-1,
                        nelm=1,
                        lwave=False,
                        lcharg=False,
                        nelect=default_nelect_from_vasp + net_charge + 1,
                        net_charge=net_charge)
            calc.calculate(system)

    # Test that conflicts between charge and net_charge are detected
    with must_raise(ValueError):
        with must_warn(FutureWarning):
            calc = Vasp(xc='LDA',
                        nsw=-1,
                        ibrion=-1,
                        nelm=1,
                        lwave=False,
                        lcharg=False,
                        charge=-net_charge - 1,
                        net_charge=net_charge)
            calc.calculate(system)

    # Test that nothing is written if net charge is 0 and nelect not given
    with must_warn(FutureWarning):
        calc = Vasp(xc='LDA',
                    nsw=-1,
                    ibrion=-1,
                    nelm=1,
                    lwave=False,
                    lcharg=False,
                    net_charge=0)
        calc.initialize(system)
        calc.write_input(system)
        calc.read_incar()
    assert calc.float_params['nelect'] is None
Esempio n. 18
0
File: db2.py Progetto: uu1477/MyAse
    row = c.get(id)
    print(row.data['1-butyne'], row.data.chi)
    assert (row.data.chi == chi).all()
    
    assert len(c.get_atoms(C=1).constraints) == 2

    f2 = c.get(C=1).forces
    assert abs(f2.sum(0)).max() < 1e-14
    f3 = c.get_atoms(C=1).get_forces()
    assert abs(f1 - f3).max() < 1e-14
    a = read(name + '@id=' + str(id))[0]
    f4 = a.get_forces()
    assert abs(f1 - f4).max() < 1e-14

    with must_raise(ValueError):
        c.update(id, abc={'a': 42})

    c.update(id, grr='hmm')
    row = c.get(C=1)
    assert row.id == id
    assert (row.data.chi == chi).all()

    with must_raise(ValueError):
        c.write(ch4, foo=['bar', 2])
        
    with must_raise(ValueError):
        c.write(Atoms(), pi='3.14')

    # Make sure deleting a single sey works:
    id = c.write(Atoms(), key=7)
Esempio n. 19
0
from ase.lattice.cubic import FaceCenteredCubic
from ase.lattice.hexagonal import HexagonalClosedPacked
from ase.test import must_raise

with must_raise(ValueError):
    # The Miller indices of the surfaces are linearly dependent
    atoms = FaceCenteredCubic(symbol='Cu',
                              miller=[[1, 1, 0], [1, 1, 0], [0, 0, 1]])

# This one should be OK:
atoms = FaceCenteredCubic(symbol='Cu',
                          miller=[[1, 1, 0], [0, 1, 0], [0, 0, 1]])
print(atoms.get_cell())

with must_raise(ValueError):
    # The directions spanning the unit cell are linearly dependent
    atoms = FaceCenteredCubic(symbol='Cu',
                              directions=[[1, 1, 0], [1, 1, 0], [0, 0, 1]])

with must_raise(ValueError):
    # The directions spanning the unit cell are linearly dependent
    atoms = FaceCenteredCubic(symbol='Cu',
                              directions=[[1, 1, 0], [1, 0, 0], [0, 1, 0]])

# This one should be OK:
atoms = FaceCenteredCubic(symbol='Cu',
                          directions=[[1, 1, 0], [0, 1, 0], [0, 0, 1]])
print(atoms.get_cell())

with must_raise((ValueError, NotImplementedError)):
    # The Miller indices of the surfaces are linearly dependent
Esempio n. 20
0
File: db2.py Progetto: nateharms/ase
    row = c.get(id)
    print(row.data['1-butyne'], row.data.chi)
    assert (row.data.chi == chi).all()

    assert len(c.get_atoms(C=1).constraints) == 2

    f2 = c.get(C=1).forces
    assert abs(f2.sum(0)).max() < 1e-14
    f3 = c.get_atoms(C=1).get_forces()
    assert abs(f1 - f3).max() < 1e-14
    a = read(name + '@id=' + str(id))[0]
    f4 = a.get_forces()
    assert abs(f1 - f4).max() < 1e-14

    with must_raise(ValueError):
        c.update(id, abc={'a': 42})

    c.update(id, grr='hmm')
    row = c.get(C=1)
    assert row.id == id
    assert (row.data.chi == chi).all()
    print(row)

    for row in c.select(include_data=False):
        with must_raise(AttributeError):
            row.data

    with must_raise(ValueError):
        c.write(ch4, foo=['bar', 2])  # not int, bool, float or str
Esempio n. 21
0
t = Trajectory(fname, 'a', co)
t.close()
os.remove(fname)

t = Trajectory('empty.traj', 'w')
t.close()
t = Trajectory('empty.traj', 'r')
assert len(t) == 0

t = Trajectory('fake.traj', 'w')
t.write(Atoms('H'), energy=-42.0, forces=[[1, 2, 3]])

t = Trajectory('only-energy.traj', 'w', properties=['energy'])
a = read('fake.traj')
t.write(a)
b = read('only-energy.traj')
e = b.get_potential_energy()
assert e + 42 == 0
with must_raise(PropertyNotImplementedError):
    f = b.get_forces()

# Make sure constraints play well with momenta:
a = Atoms('H2',
          positions=[(0, 0, 0), (0, 0, 1)],
          momenta=[(1, 0, 0), (0, 0, 0)])
a.constraints = [FixBondLength(0, 1)]
t = Trajectory('constraint.traj', 'w', a)
t.write()
b = read('constraint.traj')
assert not (b.get_momenta() - a.get_momenta()).any()
Esempio n. 22
0
"""

from ase.calculators.vasp.create_input import _args_without_comment
from ase.calculators.vasp.create_input import _to_vasp_bool, _from_vasp_bool

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(RuntimeError):
    atoms.write('POSCAR')

with must_raise(ValueError):
    atoms.set_calculator(calc)
    atoms.get_total_energy()

# Comment splitting logic

clean_args = _args_without_comment(['a', 'b', '#', 'c'])
assert len(clean_args) == 2
clean_args = _args_without_comment(['a', 'b', '!', 'c', '#', 'd'])
assert len(clean_args) == 2
clean_args = _args_without_comment(['#', 'a', 'b', '!', 'c', '#', 'd'])
assert len(clean_args) == 0
Esempio n. 23
0
traj = Trajectory('1.traj', 'a')
co = read('1.traj')
print(co.positions)
co.positions[:] += 1
traj.write(co)

for a in Trajectory('1.traj'):
    print(1, a.positions[-1, 2])
co.positions[:] += 1
t = Trajectory('1.traj', 'a')
t.write(co)
assert len(t) == 7

co[0].number = 1
with must_raise(ValueError):
    t.write(co)

co[0].number = 6
co.pbc = True
with must_raise(ValueError):
    t.write(co)

co.pbc = False
o = co.pop(1)
with must_raise(ValueError):
    t.write(co)

co.append(o)
t.write(co)
Esempio n. 24
0
def test_db2(name):
    if name == 'postgresql':
        pytest.importorskip('psycopg2')
        if os.environ.get('POSTGRES_DB'):  # gitlab-ci
            name = 'postgresql://*****:*****@postgres:5432/testase'
        else:
            name = os.environ.get('ASE_TEST_POSTGRES_URL')
            if name is None:
                return
    elif name == 'mysql':
        pytest.importorskip('pymysql')
        if os.environ.get('CI_PROJECT_DIR'):  # gitlab-ci
            name = 'mysql://*****:*****@mysql:3306/testase_mysql'
        else:
            name = os.environ.get('MYSQL_DB_URL')

        if name is None:
            return
    elif name == 'mariadb':
        pytest.importorskip('pymysql')
        if os.environ.get('CI_PROJECT_DIR'):  # gitlab-ci
            name = 'mariadb://*****:*****@mariadb:3306/testase_mysql'
        else:
            name = os.environ.get('MYSQL_DB_URL')

        if name is None:
            return

    c = connect(name)
    print(name, c)

    if 'postgres' in name or 'mysql' in name or 'mariadb' in name:
        c.delete([row.id for row in c.select()])

    id = c.reserve(abc=7)
    c.delete([d.id for d in c.select(abc=7)])
    id = c.reserve(abc=7)
    assert c[id].abc == 7

    a = c.get_atoms(id)
    c.write(Atoms())
    ch4 = molecule('CH4', calculator=EMT())
    ch4.constraints = [FixAtoms(indices=[1]), FixBondLength(0, 2)]
    f1 = ch4.get_forces()
    print(f1)

    c.delete([d.id for d in c.select(C=1)])
    chi = np.array([1 + 0.5j, 0.5])
    id = c.write(ch4, data={'1-butyne': 'bla-bla', 'chi': chi})

    row = c.get(id)
    print(row.data['1-butyne'], row.data.chi)
    assert (row.data.chi == chi).all(), (row.data.chi, chi)
    print(row)

    assert len(c.get_atoms(C=1).constraints) == 2

    f2 = c.get(C=1).forces
    assert abs(f2.sum(0)).max() < 1e-14
    f3 = c.get_atoms(C=1).get_forces()
    assert abs(f1 - f3).max() < 1e-14

    a = read(name, index='id={}'.format(id))[0]
    f4 = a.get_forces()
    assert abs(f1 - f4).max() < 1e-14

    with must_raise(ValueError):
        c.update(id, abc={'a': 42})

    c.update(id, grr='hmm')
    row = c.get(C=1)
    assert row.id == id
    assert (row.data.chi == chi).all()

    for row in c.select(include_data=False):
        assert len(row.data) == 0

    with must_raise(ValueError):
        c.write(ch4, foo=['bar', 2])  # not int, bool, float or str

    with must_raise(ValueError):
        c.write(Atoms(), pi='3.14')  # number as a string

    with must_raise(ValueError):
        c.write(Atoms(), fmax=0.0)  # reserved word

    with must_raise(ValueError):
        c.write(Atoms(), S=42)  # chemical symbol as key

    id = c.write(Atoms(),
                 b=np.bool_(True),
                 i=np.int64(42),
                 n=np.nan,
                 x=np.inf,
                 s='NaN2',
                 A=42)
    row = c[id]
    assert isinstance(row.b, bool)
    assert isinstance(row.i, int)
    assert np.isnan(row.n)
    assert np.isinf(row.x)

    # Make sure deleting a single key works:
    id = c.write(Atoms(), key=7)
    c.update(id, delete_keys=['key'])
    assert 'key' not in c[id]

    e = [row.get('energy') for row in c.select(sort='energy')]
    assert len(e) == 5 and abs(e[0] - 1.991) < 0.0005

    # Test the offset keyword
    ids = [row.get('id') for row in c.select()]
    offset = 2
    assert next(c.select(offset=offset)).id == ids[offset]
Esempio n. 25
0
db = DataConnection(db_file)
assert db.get_number_of_unrelaxed_candidates() == 1

slab3 = db.get_an_unrelaxed_candidate()
old_confid = slab3.info['confid']
slab3[0].symbol = 'Au'
db.add_unrelaxed_candidate(slab3, 'mutated: Parent {0}'.format(old_confid))
new_confid = slab3.info['confid']
# confid should update when using add_unrelaxed_candidate
assert old_confid != new_confid
slab3[1].symbol = 'Au'
db.add_unrelaxed_step(slab3, 'mutated: Parent {0}'.format(new_confid))
# confid should not change when using add_unrelaxed_step
assert slab3.info['confid'] == new_confid

with must_raise(AssertionError):
    db.add_relaxed_step(slab3)
set_raw_score(slab3, 3)
db.add_relaxed_step(slab3)

slab4 = OffspringCreator.initialize_individual(slab1,
                                               fcc111('Au', size=(2, 2, 2)))
set_raw_score(slab4, 67)
db.add_relaxed_candidate(slab4)
assert slab4.info['confid'] == 7

more_slabs = []
for m in ['Ni', 'Pd', 'Pt']:
    slab = fcc111(m, size=(2, 2, 2))
    slab = OffspringCreator.initialize_individual(slab1, slab)
    set_raw_score(slab, sum(slab.get_masses()))
Esempio n. 26
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(RuntimeError):
    atoms.write('POSCAR')

with must_raise(ValueError):
    atoms.set_calculator(calc)
    atoms.get_total_energy()