Exemplo n.º 1
0
def test(tmpdir, path):
    from numpy import abs
    from pylada.crystal import Structure
    from pylada.vasp import Vasp
    from pylada.vasp.relax import epitaxial
    from pylada import default_comm

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.55, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")

    vasp = Vasp()
    vasp.kpoints = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
    vasp.prec = "accurate"
    vasp.ediff = 1e-5
    vasp.encut = 1.4
    vasp.ismear = "fermi"
    vasp.sigma = 0.01
    vasp.relaxation = "volume"
    vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)
    result = epitaxial(vasp,
                       structure,
                       outdir=str(tmpdir),
                       epiconv=1e-5,
                       comm=default_comm)
    assert result.success
    assert abs(result.stress[2, 2]) < 1.0
Exemplo n.º 2
0
def test_system():
  from pylada.crystal.cppwrappers import Structure
  from pylada.vasp import Vasp
  a = Vasp()
  b = Structure()

  assert a.system is None
  assert a._input['system'].keyword == 'system'
  assert a._input['system'].output_map(vasp=a, structure=b) is None

  a.system = 'system'
  assert a.system == 'system'
  assert 'system' in a._input['system'].output_map(vasp=a, structure=b)
  assert a._input['system'].output_map(vasp=a, structure=b)['system'] == 'system'

  b.name = 'hello'
  assert 'system' in a._input['system'].output_map(vasp=a, structure=b)
  assert a._input['system'].output_map(vasp=a, structure=b)['system'] == 'system: hello'

  a.system = None
  assert a.system is None
  assert 'system' in a._input['system'].output_map(vasp=a, structure=b)
  assert a._input['system'].output_map(vasp=a, structure=b)['system'] == 'hello'

  a.system = None
  assert a.system is None
  assert 'system' in a._input['system'].output_map(vasp=a, structure=b)
  assert a._input['system'].output_map(vasp=a, structure=b)['system'] == 'hello'
Exemplo n.º 3
0
def test(path):
    from os import makedirs
    from os.path import exists
    from shutil import rmtree
    from tempfile import mkdtemp
    from pylada.crystal import Structure
    from pylada.vasp import Vasp
    from pylada import default_comm

    structure = Structure([[0, 0.5, 0.5],[0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
                         .add_atom(0,0,0, "Si")\
                         .add_atom(0.25,0.25,0.25, "Si")

    vasp = Vasp()
    vasp.kpoints = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
    vasp.prec = "accurate"
    vasp.ediff = 1e-5
    vasp.encut = 1
    vasp.ismear = "fermi"
    vasp.sigma = 0.01
    vasp.relaxation = "volume"
    vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)
    directory = mkdtemp()
    if directory == '/tmp/test' or directory == '/tmp/test/':
        if exists(directory): rmtree(directory)
        makedirs(directory)
    try:
        result = vasp(structure, outdir=directory, comm=default_comm)
        assert result.success
    finally:
        if directory != '/tmp/test' and directory != '/tmp/test/':
            rmtree(directory)
Exemplo n.º 4
0
def test_system():
    from pylada.crystal import Structure
    from pylada.vasp import Vasp
    a = Vasp()
    b = Structure()

    assert a.system is None
    assert a._input['system'].keyword == 'system'
    assert a._input['system'].output_map(vasp=a, structure=b) is None

    a.system = 'system'
    assert a.system == 'system'
    assert 'system' in a._input['system'].output_map(vasp=a, structure=b)
    assert a._input['system'].output_map(vasp=a,
                                         structure=b)['system'] == 'system'

    b.name = 'hello'
    assert 'system' in a._input['system'].output_map(vasp=a, structure=b)
    assert a._input['system'].output_map(
        vasp=a, structure=b)['system'] == 'system: hello'

    a.system = None
    assert a.system is None
    assert 'system' in a._input['system'].output_map(vasp=a, structure=b)
    assert a._input['system'].output_map(vasp=a,
                                         structure=b)['system'] == 'hello'

    a.system = None
    assert a.system is None
    assert 'system' in a._input['system'].output_map(vasp=a, structure=b)
    assert a._input['system'].output_map(vasp=a,
                                         structure=b)['system'] == 'hello'
Exemplo n.º 5
0
def test_alias():
    from pylada.vasp import Vasp
    from pylada.error import ValueError
    a = Vasp()

    assert a.ismear is None
    assert a._input['ismear'].keyword == 'ismear'
    assert a._input['ismear'].output_map() is None
    map = a._input['ismear'].aliases
    assert len(map) != 0
    for i, items in map.items():
        for item in items:
            a.ismear = item
            assert a.ismear == items[0]
            assert 'ismear' in a._input['ismear'].output_map()
            assert a._input['ismear'].output_map()['ismear'] == str(i)
            a.ismear = i
            assert a.ismear == items[0]
        a.ismear = str(i)
        assert a.ismear == items[0]

    try:
        a.lmaxmix = 'a'
    except ValueError:
        pass
    else:
        raise Exception()
Exemplo n.º 6
0
def test(path):
  from shutil import rmtree
  from tempfile import mkdtemp
  from pylada.crystal import Structure
  from pylada.vasp import Vasp
  from epirelax import epitaxial
  from pylada import default_comm

  structure = Structure([[0, 0.5, 0.5],[0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.55, name='has a name')\
                       .add_atom(0,0,0, "Si")\
                       .add_atom(0.25,0.25,0.25, "Si")

  vasp = Vasp()
  vasp.kpoints    = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
  vasp.prec       = "accurate"
  vasp.ediff      = 1e-5
  vasp.encut      = 1.4
  vasp.ismear     = "fermi"
  vasp.sigma      = 0.01
  vasp.relaxation = "volume"
  vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)
  directory = mkdtemp()
  try: 
    result = epitaxial(vasp, structure, outdir=directory, epiconv=1e-4, comm=default_comm)
    assert result.success
  finally: 
    rmtree(directory)
    pass
Exemplo n.º 7
0
def vasp(Specie):
    from pylada.vasp import Vasp
    from pylada.vasp.specie import U, nlep
    vasp = Vasp()
    vasp.species = {'A': Specie([]), 'B': Specie([]), 'X': Specie([])}
    for key in list(vasp._input.keys()):
        if key not in ['ldau']:
            del vasp._input[key]
    return vasp
def vasp(Specie):
    from pylada.vasp import Vasp
    from pylada.vasp.specie import U, nlep
    vasp = Vasp()
    vasp.species = {'A': Specie([]), 'B': Specie([]), 'X': Specie([])}
    for key in list(vasp._input.keys()):
        if key not in ['ldau']:
            del vasp._input[key]
    return vasp
Exemplo n.º 9
0
def test(path):
  from os import makedirs
  from os.path import exists
  from shutil import rmtree
  from tempfile import mkdtemp
  from pylada.crystal import Structure
  from pylada.vasp import Vasp
  from pylada import default_comm

  structure = Structure([[0, 0.5, 0.5],[0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
                       .add_atom(0,0,0, "Si")\
                       .add_atom(0.25,0.25,0.25, "Si")

  vasp = Vasp()
  vasp.kpoints    = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
  vasp.prec       = "accurate"
  vasp.ediff      = 1e-5
  vasp.encut      = 1
  vasp.ismear     = "fermi"
  vasp.sigma      = 0.01
  vasp.relaxation = "volume"
  vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)
  directory = mkdtemp()
  if directory == '/tmp/test' or directory == '/tmp/test/':
    if exists(directory): rmtree(directory)
    makedirs(directory)
  try: 
    result = vasp(structure, outdir=directory, comm=default_comm)
    assert result.success
  finally: 
    if directory != '/tmp/test' and directory != '/tmp/test/':
      rmtree(directory)
Exemplo n.º 10
0
def test(tmpdir, path):
    from numpy import abs
    from pylada.crystal import Structure
    from pylada.vasp import Vasp
    from pylada.vasp.emass import effective_mass, EMass
    from pylada import default_comm

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.55, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")

    vasp = Vasp()
    vasp.kpoints = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
    vasp.prec = "accurate"
    vasp.ediff = 25e-5
    vasp.encut = 1.4
    vasp.ismear = "fermi"
    vasp.sigma = 0.01
    vasp.relaxation = "volume"
    vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)
    emass = EMass(copy=vasp)
    assert abs(emass.encut - 1.4) < 1e-8
    assert abs(emass.ediff - 25e-5) < 1e-10
    result = effective_mass(vasp, structure, outdir=str(tmpdir), comm=default_comm,
                            emassparams={'ediff': 1e-8})
    result.emass
    assert result.success
    result = emass(structure, outdir=str(tmpdir), comm=default_comm,
                   emassparams={'ediff': 1e-8})
    assert result.success
Exemplo n.º 11
0
def test(tmpdir, path):
    from numpy import all, abs
    from quantities import kbar, eV, angstrom
    from pylada.crystal import Structure
    from pylada.vasp import Vasp
    from pylada.vasp.relax import Relax
    from pylada import default_comm

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")

    vasp = Vasp()
    vasp.kpoints = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
    vasp.prec = "accurate"
    vasp.ediff = 1e-5
    vasp.encut = 1
    vasp.ismear = "fermi"
    vasp.sigma = 0.01
    vasp.relaxation = "volume"
    vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)

    functional = Relax(copy=vasp)
    assert abs(functional.ediff - 1e-5) < 1e-8
    assert functional.prec == 'Accurate'
    result = functional(structure, outdir=str(tmpdir), comm=default_comm,
                        relaxation="volume ionic cellshape")
    assert result.success

    assert result.stress.units == kbar and all(abs(result.stress) < 1e0)
    assert result.forces.units == eV / angstrom and all(abs(result.forces) < 1e-1)
    assert result.total_energy.units == eV and all(
        abs(result.total_energy + 10.668652 * eV) < 1e-2)
def vasp():
    from os.path import join, dirname
    from pylada.vasp import Vasp
    vasp = Vasp()
    vasp.kpoints = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
    vasp.precision = "accurate"
    vasp.ediff = 1e-5
    vasp.encut = 1
    vasp.ismear = "metal"
    vasp.sigma = 0.06
    vasp.relaxation = "volume"
    vasp.add_specie = "Si", join(dirname(__file__), 'pseudos', 'Si')
    return vasp
Exemplo n.º 13
0
def test_choice():
    from pickle import loads, dumps
    from pylada.vasp import Vasp
    a = Vasp()

    assert a.ispin is None
    assert a._input['ispin'].keyword == 'ispin'
    assert a._input['ispin'].output_map() is None
    a.ispin = 1
    assert a.ispin == 1
    assert 'ispin' in a._input['ispin'].output_map()
    assert a._input['ispin'].output_map()['ispin'] == '1'
    a.ispin = 2
    assert a.ispin == 2
    assert 'ispin' in a._input['ispin'].output_map()
    assert a._input['ispin'].output_map()['ispin'] == '2'
    a.ispin = None
    assert a.ispin is None
    assert a._input['ispin'].keyword == 'ispin'
    assert a._input['ispin'].output_map() is None

    try:
        a.ispin = 5
    except:
        pass
    else:
        raise RuntimeError()

    a.ispin = '1'
    assert a.ispin == 1
    a.ispin = '2'
    assert a.ispin == 2

    try:
        a.ispin = '3'
    except:
        pass
    else:
        raise RuntimeError()

    a.ispin = None
    o = a._input['ispin']
    d = {'ChoiceKeyword': o.__class__}
    assert repr(eval(repr(o), d)) == repr(o)
    assert eval(repr(o), d).output_map() is None
    assert repr(loads(dumps(o))) == repr(o)
    a.ispin = 2
    o = a._input['ispin']
    assert repr(eval(repr(o), d)) == repr(o)
    assert eval(repr(o), d).output_map()['ispin'] == '2'
    assert repr(loads(dumps(o))) == repr(o)
Exemplo n.º 14
0
def test_nelect():
    from os.path import dirname
    from pickle import loads, dumps
    from pylada.vasp import Vasp
    from pylada.crystal import Structure

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]],
                          scale=5.43, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")
    a = Vasp()
    a.add_specie = "Si", "{0}/pseudos/Si".format(dirname(__file__))
    assert a.extraelectron is None
    assert a._input['extraelectron'].output_map() is None
    assert a._input['nelect'].output_map() is None
    a.extraelectron = 0
    assert a.extraelectron == 0
    assert a.nelect is None
    assert a._input['extraelectron'].output_map() is None
    assert a._input['nelect'].output_map() is None
    a.extraelectron = 1
    assert a.extraelectron == 1
    assert a.nelect is None
    assert 'nelect' in a._input['extraelectron'].output_map(
        vasp=a, structure=structure)
    assert abs(
        float(a._input['extraelectron'].output_map(vasp=a, structure=structure)
              ['nelect']) - 9.0) < 1e-8
    assert a._input['nelect'].output_map() is None
    a.nelect = 1
    a.extraelectron = -1
    assert a.extraelectron == -1
    assert a.nelect is None
    assert 'nelect' in a._input['extraelectron'].output_map(
        vasp=a, structure=structure)
    assert abs(
        float(a._input['extraelectron'].output_map(vasp=a, structure=structure)
              ['nelect']) - 7.0) < 1e-8
    assert a._input['nelect'].output_map() is None
    o = a._input['extraelectron']
    d = {'ExtraElectron': o.__class__}
    assert repr(eval(repr(o), d)) == repr(o)
    assert abs(
        float(
            eval(repr(o), d).output_map(vasp=a, structure=structure)['nelect'])
        - 7.0) < 1e-8
    assert repr(loads(dumps(o))) == repr(o)

    a.nelect = 8
    assert a.nelect == 8
    assert a.extraelectron is None
    assert 'nelect' in a._input['nelect'].output_map()
    assert abs(float(a._input['nelect'].output_map()['nelect']) - 8.0) < 1e-8
    assert a._input['extraelectron'].output_map() is None
    o = a._input['nelect']
    d = {'NElect': o.__class__}
    assert repr(eval(repr(o), d)) == repr(o)
    assert abs(float(eval(repr(o), d).output_map()['nelect']) - 8.0) < 1e-8
    assert repr(loads(dumps(o))) == repr(o)
Exemplo n.º 15
0
def test(path):
    from shutil import rmtree
    from os.path import exists
    from os import makedirs
    from tempfile import mkdtemp
    from numpy import abs
    from pylada.crystal import Structure
    from pylada.vasp import Vasp
    from pylada.vasp.emass import effective_mass, EMass
    from pylada import default_comm



    structure = Structure([[0, 0.5, 0.5],[0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.55, name='has a name')\
                         .add_atom(0,0,0, "Si")\
                         .add_atom(0.25,0.25,0.25, "Si")

    vasp = Vasp()
    vasp.kpoints = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
    vasp.prec = "accurate"
    vasp.ediff = 25e-5
    vasp.encut = 1.4
    vasp.ismear = "fermi"
    vasp.sigma = 0.01
    vasp.relaxation = "volume"
    vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)
    emass = EMass(copy=vasp)
    assert abs(emass.encut - 1.4) < 1e-8
    assert abs(emass.ediff - 25e-5) < 1e-10
    directory = "/tmp/test"  #mkdtemp()
    if exists(directory) and directory == '/tmp/test': rmtree(directory)
    if not exists(directory): makedirs(directory)
    try:
        result = effective_mass(vasp,
                                structure,
                                outdir=directory,
                                comm=default_comm,
                                emassparams={'ediff': 1e-8})
        result.emass
        assert result.success
        result = emass(structure,
                       outdir=directory,
                       comm=default_comm,
                       emassparams={'ediff': 1e-8})
        assert result.success
    finally:
        if directory != '/tmp/test': rmtree(directory)
        pass
Exemplo n.º 16
0
def vasp():
    from pylada.vasp import Vasp
    vasp = Vasp()
    for key in list(vasp._input.keys()):
        if key not in ['isif', 'nsw', 'ibrion', 'relaxation']:
            del vasp._input[key]
    return vasp
Exemplo n.º 17
0
def vasp():
    from os.path import join, dirname
    from pylada.vasp import Vasp
    vasp = Vasp()
    vasp.kpoints = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
    vasp.precision = "accurate"
    vasp.ediff = 1e-5
    vasp.encut = 1
    vasp.ismear = "metal"
    vasp.sigma = 0.06
    vasp.relaxation = "volume"
    vasp.add_specie = "Si", join(dirname(__file__), 'pseudos', 'Si')
    return vasp
Exemplo n.º 18
0
def test(path):
  from glob import glob
  from os.path import join
  from shutil import rmtree
  from tempfile import mkdtemp
  from numpy import all, abs
  from quantities import kbar, eV, angstrom
  from pylada.crystal import Structure
  from pylada.vasp import Vasp
  from pylada.vasp.relax import Relax
  from pylada import default_comm
    
  structure = Structure([[0, 0.5, 0.5],[0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
                       .add_atom(0,0,0, "Si")\
                       .add_atom(0.25,0.25,0.25, "Si")

  vasp = Vasp()
  vasp.kpoints    = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
  vasp.prec       = "accurate"
  vasp.ediff      = 1e-5
  vasp.encut      = 1
  vasp.ismear     = "fermi"
  vasp.sigma      = 0.01
  vasp.relaxation = "volume"
  vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)
  directory = mkdtemp()
  try: 
    functional = Relax(copy=vasp)
    assert abs(functional.ediff - 1e-5) < 1e-8
    assert functional.prec == 'Accurate'
    result = functional(structure, outdir=directory, comm=default_comm,
                        relaxation="volume ionic cellshape")
    assert result.success
    def sortme(a): return int(a.split('/')[-1])
    dirs = sorted(glob(join(join(directory, '*'), '[0-9]')), key=sortme)
  # for previous, current in zip(dirs, dirs[1:]):
  #   assert len(check_output(['diff', join(previous, 'CONTCAR'), join(current, 'POSCAR')])) == 0
  # assert len(check_output(['diff', join(current, 'CONTCAR'), join(directory, 'POSCAR')])) == 0
    assert result.stress.units == kbar and all(abs(result.stress) < 1e0)
    assert result.forces.units == eV/angstrom and all(abs(result.forces) < 1e-1)
    assert result.total_energy.units == eV and all(abs(result.total_energy + 10.668652*eV) < 1e-2)

  finally: 
    if directory != '/tmp/test/relax': rmtree(directory)
    pass
def test_alias():
    from pylada.vasp import Vasp
    from pylada.error import ValueError
    a = Vasp()

    assert a.ismear is None
    assert a._input['ismear'].keyword == 'ismear'
    assert a._input['ismear'].output_map() is None
    map = a._input['ismear'].aliases
    assert len(map) != 0
    for i, items in map.items():
        for item in items:
            a.ismear = item
            assert a.ismear == items[0]
            assert 'ismear' in a._input['ismear'].output_map()
            assert a._input['ismear'].output_map()['ismear'] == str(i)
            a.ismear = i
            assert a.ismear == items[0]
        a.ismear = str(i)
        assert a.ismear == items[0]

    try:
        a.lmaxmix = 'a'
    except ValueError:
        pass
    else:
        raise Exception()
Exemplo n.º 20
0
def test_nelect():
    from os.path import dirname
    from pickle import loads, dumps
    from pylada.vasp import Vasp
    from pylada.crystal import Structure

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]],
                          scale=5.43, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")
    a = Vasp()
    a.add_specie = "Si", "{0}/pseudos/Si".format(dirname(__file__))
    assert a.extraelectron is None
    assert a._input['extraelectron'].output_map() is None
    assert a._input['nelect'].output_map() is None
    a.extraelectron = 0
    assert a.extraelectron == 0
    assert a.nelect is None
    assert a._input['extraelectron'].output_map() is None
    assert a._input['nelect'].output_map() is None
    a.extraelectron = 1
    assert a.extraelectron == 1
    assert a.nelect is None
    assert 'nelect' in a._input['extraelectron'].output_map(vasp=a, structure=structure)
    assert abs(float(a._input['extraelectron'].output_map(
        vasp=a, structure=structure)['nelect']) - 9.0) < 1e-8
    assert a._input['nelect'].output_map() is None
    a.nelect = 1
    a.extraelectron = -1
    assert a.extraelectron == -1
    assert a.nelect is None
    assert 'nelect' in a._input['extraelectron'].output_map(vasp=a, structure=structure)
    assert abs(float(a._input['extraelectron'].output_map(
        vasp=a, structure=structure)['nelect']) - 7.0) < 1e-8
    assert a._input['nelect'].output_map() is None
    o = a._input['extraelectron']
    d = {'ExtraElectron': o.__class__}
    assert repr(eval(repr(o), d)) == repr(o)
    assert abs(float(eval(repr(o), d).output_map(
        vasp=a, structure=structure)['nelect']) - 7.0) < 1e-8
    assert repr(loads(dumps(o))) == repr(o)

    a.nelect = 8
    assert a.nelect == 8
    assert a.extraelectron is None
    assert 'nelect' in a._input['nelect'].output_map()
    assert abs(float(a._input['nelect'].output_map()['nelect']) - 8.0) < 1e-8
    assert a._input['extraelectron'].output_map() is None
    o = a._input['nelect']
    d = {'NElect': o.__class__}
    assert repr(eval(repr(o), d)) == repr(o)
    assert abs(float(eval(repr(o), d).output_map()['nelect']) - 8.0) < 1e-8
    assert repr(loads(dumps(o))) == repr(o)
Exemplo n.º 21
0
def test(path):
  from shutil import rmtree
  from os.path import exists
  from os import makedirs
  from tempfile import mkdtemp
  from numpy import abs
  from pylada.crystal import Structure
  from pylada.vasp import Vasp
  from pylada.vasp.emass import effective_mass, EMass
  from pylada import default_comm

    
    
  structure = Structure([[0, 0.5, 0.5],[0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.55, name='has a name')\
                       .add_atom(0,0,0, "Si")\
                       .add_atom(0.25,0.25,0.25, "Si")

  vasp = Vasp()
  vasp.kpoints    = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
  vasp.prec       = "accurate"
  vasp.ediff      = 25e-5
  vasp.encut      = 1.4
  vasp.ismear     = "fermi"
  vasp.sigma      = 0.01
  vasp.relaxation = "volume"
  vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)
  emass = EMass(copy=vasp)
  assert abs(emass.encut - 1.4) < 1e-8
  assert abs(emass.ediff - 25e-5) < 1e-10
  directory = "/tmp/test" #mkdtemp()
  if exists(directory) and directory == '/tmp/test': rmtree(directory)
  if not exists(directory): makedirs(directory)
  try: 
    result = effective_mass(vasp, structure, outdir=directory, comm=default_comm,
                            emassparams={'ediff': 1e-8})
    result.emass
    assert result.success
    result = emass(structure, outdir=directory, comm=default_comm,
                   emassparams={'ediff': 1e-8})
    assert result.success
  finally: 
    if directory != '/tmp/test': rmtree(directory)
    pass
Exemplo n.º 22
0
def test(tmpdir, path):
    from pylada.crystal import Structure
    from pylada.vasp import Vasp
    from pylada import default_comm

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")

    vasp = Vasp()
    vasp.kpoints = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
    vasp.prec = "accurate"
    vasp.ediff = 1e-5
    vasp.encut = 1
    vasp.ismear = "fermi"
    vasp.sigma = 0.01
    vasp.relaxation = "volume"
    vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)
    result = vasp(structure, outdir=str(tmpdir), comm=default_comm)
    assert result.success
Exemplo n.º 23
0
def test(tmpdir, path):
    from numpy import all, abs
    from quantities import kbar, eV, angstrom
    from pylada.crystal import Structure
    from pylada.vasp import Vasp
    from pylada.vasp.relax import Relax
    from pylada import default_comm

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")

    vasp = Vasp()
    vasp.kpoints = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
    vasp.prec = "accurate"
    vasp.ediff = 1e-5
    vasp.encut = 1
    vasp.ismear = "fermi"
    vasp.sigma = 0.01
    vasp.relaxation = "volume"
    vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)

    functional = Relax(copy=vasp)
    assert abs(functional.ediff - 1e-5) < 1e-8
    assert functional.prec == 'Accurate'
    result = functional(structure,
                        outdir=str(tmpdir),
                        comm=default_comm,
                        relaxation="volume ionic cellshape")
    assert result.success

    assert result.stress.units == kbar and all(abs(result.stress) < 1e0)
    assert result.forces.units == eV / angstrom and all(
        abs(result.forces) < 1e-1)
    assert result.total_energy.units == eV and all(
        abs(result.total_energy + 10.668652 * eV) < 1e-2)
Exemplo n.º 24
0
    def __call__(self, structure, outdir=None, **kwargs ):

        from copy import deepcopy
        from os import getcwd
        from os.path import join
        from pylada.misc import RelativePath
        from pylada.error import ExternalRunFailed
        from pylada.vasp.extract import Extract
        from pylada.vasp import Vasp
        from pylada.vasp.relax import Relax

        # make this function stateless.
        structure_ = structure.copy()
        outdir = getcwd() if outdir is None else RelativePath(outdir).path

        ############ Calc 1 ###############
        name  = self.names[0]

        ## functional for Calc 1
        relax = Relax(copy=deepcopy(self.vasp))
        relax.relaxation = "volume ionic cellshape"
        relax.maxiter = 10
        relax.keep_steps = True
        relax.first_trial = { "kpoints": "\n0\nAuto\n10", "encut": 0.9 }
        ## end of the functional
        
        params = deepcopy(kwargs)
        fulldir = join(outdir, name)
        
        ## if this calculation has not been done run it
        output = relax(structure_, outdir=fulldir, **params)
        if not output.success: 
            raise ExternalRunFailed("VASP calculation did not succeed.") 

        ############ Calc 2 ###############  
        name  = self.names[1]

        ## functional for Calc 2
        wfn = Vasp(copy=deepcopy(self.vasp))
        wfn.isym    = 1
        wfn.ismear  = -5
        wfn.nbands=24*len(structure_)
        wfn.kpoints="\n0\nGamma\n4 4 4\n0. 0. 0.\n"
        ## end of the functional
        
        params = deepcopy(kwargs)
        fulldir = join(outdir, name)
        
        ## if this calculation has not been done, run it
        output = wfn(structure_, outdir=fulldir, restart=output, **params)
        if not output.success: 
            raise ExternalRunFailed("VASP calculation did not succeed.") 

        return self.Extract(fulldir)
def test_bool():
    from pickle import loads, dumps
    from pylada.vasp import Vasp
    a = Vasp()

    assert a._input['addgrid'].keyword == 'addgrid'
    assert a._input['addgrid'].output_map() is None
    assert a.addgrid is None
    a.addgrid = False
    assert a.addgrid is False
    assert 'addgrid' in a._input['addgrid'].output_map()
    assert a._input['addgrid'].output_map()['addgrid'] == '.FALSE.'
    a.addgrid = True
    assert a.addgrid is True
    assert 'addgrid' in a._input['addgrid'].output_map()
    assert a._input['addgrid'].output_map()['addgrid'] == '.TRUE.'
    a.addgrid = None
    assert a._input['addgrid'].keyword == 'addgrid'
    assert a._input['addgrid'].output_map() is None
    a.addgrid = 0
    assert a.addgrid is False

    a.addgrid = False
    o = a._input['addgrid']
    d = {'BoolKeyword': o.__class__}
    assert repr(eval(repr(o), d)) == repr(o)
    assert eval(repr(o), d).output_map()['addgrid'] == '.FALSE.'
    assert repr(loads(dumps(o))) == repr(o)
    a.addgrid = True
    o = a._input['addgrid']
    assert repr(eval(repr(o), d)) == repr(o)
    assert eval(repr(o), d).output_map()['addgrid'] == '.TRUE.'
    assert repr(loads(dumps(o))) == repr(o)
    a.addgrid = None
    o = a._input['addgrid']
    assert repr(eval(repr(o), d)) == repr(o)
    assert eval(repr(o), d).output_map() is None
    assert repr(loads(dumps(o))) == repr(o)
Exemplo n.º 26
0
def test():
    from collections import namedtuple
    from pickle import loads, dumps
    from pylada.vasp import Vasp

    Restart = namedtuple('Restart', ['success', 'lmaxmix', 'lvhar'])
    a = Vasp()
    o = a._input['lsorbit']
    d = {'LSorbit': o.__class__}
    assert a.lsorbit is None
    assert a.nonscf == False
    assert a._input['lsorbit'].keyword == 'lsorbit'
    assert a._input['nonscf'].keyword is None
    assert o.output_map(vasp=a) is None
    assert eval(repr(o), d).output_map(vasp=a) is None
    assert eval(repr(o), d).value is None
    assert loads(dumps(o)).value is None

    a.lsorbit = True
    assert a.nonscf
    assert a.lsorbit
    try:
        a._input['lsorbit'].output_map(vasp=a)
    except ValueError:
        pass
    else:
        raise Exception()
    a.restart = Restart(False, 7, False)
    try:
        a._input['lsorbit'].output_map(vasp=a)
    except ValueError:
        pass
    else:
        raise Exception()
    a.restart = Restart(True, 7, False)
    assert 'lsorbit' in o.output_map(vasp=a)
    assert o.output_map(vasp=a)['lsorbit'] == '.TRUE.'
    assert a.lmaxmix == 7
    a.lmaxmix = 5
    a.restart = Restart(True, 6, False)
    assert 'lsorbit' in o.output_map(vasp=a)
    assert o.output_map(vasp=a)['lsorbit'] == '.TRUE.'
    assert a.lmaxmix == 6
    assert loads(dumps(o)).value is True
    assert eval(repr(o), d).value is True
Exemplo n.º 27
0
def test_bool():
  from pickle import loads, dumps
  from pylada.vasp import Vasp
  a = Vasp()

  assert a._input['addgrid'].keyword == 'addgrid'
  assert a._input['addgrid'].output_map() is None
  assert a.addgrid is None
  a.addgrid = False
  assert a.addgrid is False
  assert 'addgrid' in a._input['addgrid'].output_map()
  assert a._input['addgrid'].output_map()['addgrid'] == '.FALSE.'
  a.addgrid = True
  assert a.addgrid is True
  assert 'addgrid' in a._input['addgrid'].output_map()
  assert a._input['addgrid'].output_map()['addgrid'] == '.TRUE.'
  a.addgrid = None
  assert a._input['addgrid'].keyword == 'addgrid'
  assert a._input['addgrid'].output_map() is None
  a.addgrid = 0
  assert a.addgrid is False

  a.addgrid = False
  o = a._input['addgrid']
  d = {'BoolKeyword': o.__class__}
  assert repr(eval(repr(o), d)) == repr(o)
  assert eval(repr(o), d).output_map()['addgrid'] == '.FALSE.'
  assert repr(loads(dumps(o))) == repr(o)
  a.addgrid = True
  o = a._input['addgrid']
  assert repr(eval(repr(o), d)) == repr(o)
  assert eval(repr(o), d).output_map()['addgrid'] == '.TRUE.'
  assert repr(loads(dumps(o))) == repr(o)
  a.addgrid = None
  o = a._input['addgrid']
  assert repr(eval(repr(o), d)) == repr(o)
  assert eval(repr(o), d).output_map() is None
  assert repr(loads(dumps(o))) == repr(o)
Exemplo n.º 28
0
def test_lsorbit():
    from collections import namedtuple
    from pickle import loads, dumps
    from pylada.vasp import Vasp

    Restart = namedtuple('Restart', ['success', 'lmaxmix', 'lvhar'])
    a = Vasp()
    o = a._input['lsorbit']
    d = {'LSorbit': o.__class__}
    assert a.lsorbit is None
    assert a.nonscf == False
    assert a._input['lsorbit'].keyword == 'lsorbit'
    assert a._input['nonscf'].keyword is None
    assert o.output_map(vasp=a) is None
    assert eval(repr(o), d).output_map(vasp=a) is None
    assert eval(repr(o), d).value is None
    assert loads(dumps(o)).value is None

    a.lsorbit = True
    assert a.nonscf
    assert a.lsorbit
    try:
        a._input['lsorbit'].output_map(vasp=a)
    except ValueError:
        pass
    else:
        raise Exception()
    a.restart = Restart(False, 7, False)
    try:
        a._input['lsorbit'].output_map(vasp=a)
    except ValueError:
        pass
    else:
        raise Exception()
    a.restart = Restart(True, 7, False)
    assert 'lsorbit' in o.output_map(vasp=a)
    assert o.output_map(vasp=a)['lsorbit'] == '.TRUE.'
    assert a.lmaxmix == 7
    a.lmaxmix = 5
    a.restart = Restart(True, 6, False)
    assert 'lsorbit' in o.output_map(vasp=a)
    assert o.output_map(vasp=a)['lsorbit'] == '.TRUE.'
    assert a.lmaxmix == 6
    assert loads(dumps(o)).value is True
    assert eval(repr(o), d).value is True
Exemplo n.º 29
0
def test_copy_files():
    from tempfile import mkdtemp
    from shutil import rmtree
    from os import makedirs
    from os.path import exists, join
    from pylada.vasp import Vasp

    directory = mkdtemp()
    if exists(directory):
        rmtree(directory)
    makedirs(directory)
    makedirs(join(directory, 'indir'))
    with open(join(directory, 'indir', 'infile'), 'w') as file:
        file.write('hello')
    with open(join(directory, 'indir', 'this'), 'w') as file:
        file.write('hello')
    with open(join(directory, 'indir', 'that'), 'w') as file:
        file.write('hello')
    try:
        vasp = Vasp()
        # Shouldn't copy yet
        vasp._copy_additional_files(outdir=join(directory, 'outdir'))
        assert not exists(join(directory, 'outdir', 'infile'))
        assert not exists(join(directory, 'outdir', 'this'))
        assert not exists(join(directory, 'outdir', 'that'))
        # Now should copy
        vasp.files = join(directory, 'indir', 'infile')
        vasp._copy_additional_files(outdir=join(directory, 'outdir'))
        assert exists(join(directory, 'outdir', 'infile'))
        assert not exists(join(directory, 'outdir', 'this'))
        assert not exists(join(directory, 'outdir', 'that'))
        # Do it again, should be fine
        vasp._copy_additional_files(outdir=join(directory, 'outdir'))
        assert exists(join(directory, 'outdir', 'infile'))
        # Copy mutliple files
        vasp.files = [
            join(directory, 'indir', u) for u in ['infile', 'this', 'that']
        ]
        vasp._copy_additional_files(outdir=join(directory, 'outdir'))
        assert exists(join(directory, 'outdir', 'infile'))
        assert exists(join(directory, 'outdir', 'this'))
        assert exists(join(directory, 'outdir', 'that'))

    finally:
        if directory != '/tmp/test':
            rmtree(directory)
Exemplo n.º 30
0
def test():
    from collections import namedtuple
    from pickle import loads, dumps
    from numpy import all, abs, array
    from pylada.crystal import Structure
    from pylada.vasp import Vasp
    from pylada.vasp.specie import U, nlep
    import pylada

    u = 0.25
    x, y = u, 0.25 - u
    structure = Structure([[0,0.5,0.5],[0.5,0,0.5],[0.5,0.5,0]]) \
                         .add_atom(5.000000e-01, 5.000000e-01, 5.000000e-01, "A") \
                         .add_atom(5.000000e-01, 2.500000e-01, 2.500000e-01, "A") \
                         .add_atom(2.500000e-01, 5.000000e-01, 2.500000e-01, "A") \
                         .add_atom(2.500000e-01, 2.500000e-01, 5.000000e-01, "A") \
                         .add_atom(8.750000e-01, 8.750000e-01, 8.750000e-01, "B") \
                         .add_atom(1.250000e-01, 1.250000e-01, 1.250000e-01, "B") \
                         .add_atom(     x,     x,     x, "X") \
                         .add_atom(     x,     y,     y, "X") \
                         .add_atom(     y,     x,     y, "X") \
                         .add_atom(     y,     y,     x, "X") \
                         .add_atom(    -x,    -x,    -x, "X") \
                         .add_atom(    -x,    -y,    -y, "X") \
                         .add_atom(    -y,    -x,    -y, "X") \
                         .add_atom(    -y,    -y,    -x, "X")
    a = Vasp()
    Specie = namedtuple('Specie', ['U'])
    a.species = {'A': Specie([]), 'B': Specie([]), 'X': Specie([])}
    pylada.vasp_has_nlep = False

    o = a._input['ldau']
    d = {'LDAU': o.__class__}
    assert a.ldau == True
    assert o.output_map(vasp=a, structure=structure) is None
    assert eval(repr(o), d)._value == True
    assert eval(repr(o), d).keyword == 'LDAU'
    assert loads(dumps(o)).keyword == 'LDAU'
    assert loads(dumps(o))._value

    # now disables U.
    a.species = {'A': Specie([U(2, 0, 0.5)]), 'B': Specie([]), 'X': Specie([])}
    a.ldau = False
    assert a.ldau == False
    print o
    assert o.output_map(vasp=a) is None
    # now prints U
    a.ldau = True
    map = o.output_map(vasp=a, structure=structure)
    assert map['LDAU'] == '.TRUE.'
    assert map['LDAUTYPE'] == '2'
    assert all(abs(array(map['LDUJ'].split(), dtype='float64')) < 1e-8)
    assert all(
        abs(array(map['LDUU'].split(), dtype='float64') - [0.5, 0, 0]) < 1e-8)
    assert all(
        abs(array(map['LDUL'].split(), dtype='float64') - [0, -1, -1]) < 1e-8)
    a.species = {
        'A': Specie([U(2, 0, 0.5)]),
        'B': Specie([U(2, 1, 0.6)]),
        'X': Specie([])
    }
    map = o.output_map(vasp=a, structure=structure)
    assert map['LDAU'] == '.TRUE.'
    assert map['LDAUTYPE'] == '2'
    assert all(abs(array(map['LDUJ'].split(), dtype='float64')) < 1e-8)
    assert all(
        abs(array(map['LDUU'].split(), dtype='float64') -
            [0.5, 0, 0.6]) < 1e-8)
    assert all(
        abs(array(map['LDUL'].split(), dtype='float64') - [0, -1, 1]) < 1e-8)

    # now tries NLEP
    pylada.vasp_has_nlep = True
    a.species = {
        'A': Specie([U(2, 0, 0.5)]),
        'B': Specie([U(2, 0, -0.5), nlep(2, 1, -1.0)]),
        'X': Specie([])
    }
    a.ldau = False
    assert a.ldau == False
    assert o.output_map(vasp=a) is None
    a.ldau = True
    map = o.output_map(vasp=a, structure=structure)
    assert map['LDAU'] == '.TRUE.'
    assert map['LDAUTYPE'] == '2'
    assert all(
        abs(array(map['LDUL1'].split(), dtype='float64') - [0, -1, 0]) < 1e-8)
    assert all(
        abs(array(map['LDUU1'].split(), dtype='float64') -
            [0.5, 0, -0.5]) < 1e-8)
    assert all(
        abs(array(map['LDUJ1'].split(), dtype='float64') - [0, 0, 0]) < 1e-8)
    assert all(
        abs(array(map['LDUO1'].split(), dtype='float64') - [1, 1, 1]) < 1e-8)
    assert all(
        abs(array(map['LDUL2'].split(), dtype='float64') - [-1, -1, 1]) < 1e-8)
    assert all(
        abs(array(map['LDUU2'].split(), dtype='float64') -
            [0, 0, -1.0]) < 1e-8)
    assert all(
        abs(array(map['LDUJ2'].split(), dtype='float64') - [0, 0, 0]) < 1e-8)
    assert all(
        abs(array(map['LDUO2'].split(), dtype='float64') - [1, 1, 2]) < 1e-8)

    a.species = {
        'A': Specie([U(2, 0, 0.5)]),
        'B': Specie([U(2, 0, -0.5), nlep(2, 2, -1.0, -3.0)]),
        'X': Specie([])
    }
    a.ldau = True
    map = o.output_map(vasp=a, structure=structure)
    assert map['LDAU'] == '.TRUE.'
    assert map['LDAUTYPE'] == '2'
    assert all(
        abs(array(map['LDUL1'].split(), dtype='float64') - [0, -1, 0]) < 1e-8)
    assert all(
        abs(array(map['LDUU1'].split(), dtype='float64') -
            [0.5, 0, -0.5]) < 1e-8)
    assert all(
        abs(array(map['LDUJ1'].split(), dtype='float64') - [0, 0, 0]) < 1e-8)
    assert all(
        abs(array(map['LDUO1'].split(), dtype='float64') - [1, 1, 1]) < 1e-8)
    assert all(
        abs(array(map['LDUL2'].split(), dtype='float64') - [-1, -1, 2]) < 1e-8)
    assert all(
        abs(array(map['LDUU2'].split(), dtype='float64') -
            [0, 0, -1.0]) < 1e-8)
    assert all(
        abs(array(map['LDUJ2'].split(), dtype='float64') -
            [0, 0, -3.0]) < 1e-8)
    assert all(
        abs(array(map['LDUO2'].split(), dtype='float64') - [1, 1, 3]) < 1e-8)
Exemplo n.º 31
0
def test():
  from pickle import loads, dumps
  from pylada.vasp import Vasp
  from pylada.error import ValueError
 
  a = Vasp()

  for key in a._input.keys():
    if key not in ['isif', 'nsw', 'ibrion', 'relaxation']: 
      del a._input[key]
  assert a.relaxation == 'static'
  assert len(a.output_map(vasp=a)) == 1
  assert a.output_map(vasp=a)['ibrion'] == str(-1)

  a.relaxation = 'cellshape'
  assert a.relaxation == 'cellshape'
  assert a.isif == 5
  assert a.nsw == 50
  assert a.ibrion == 2
  assert len(a.output_map(vasp=a)) == 3
  assert a.output_map(vasp=a)['ibrion'] == str(2)
  assert a.output_map(vasp=a)['isif'] == str(5)
  assert a.output_map(vasp=a)['nsw'] == str(50)
  a = loads(dumps(a))
  assert len(a.output_map(vasp=a)) == 3
  assert a.output_map(vasp=a)['ibrion'] == str(2)
  assert a.output_map(vasp=a)['isif'] == str(5)
  assert a.output_map(vasp=a)['nsw'] == str(50)

  a.relaxation = 'cellshape volume'
  a.nsw = 25
  assert a.relaxation == 'cellshape volume'
  assert a.isif == 6
  assert a.nsw == 25
  assert a.ibrion == 2
  assert len(a.output_map(vasp=a)) == 3
  assert a.output_map(vasp=a)['ibrion'] == str(2)
  assert a.output_map(vasp=a)['isif'] == str(6)
  assert a.output_map(vasp=a)['nsw'] == str(25)

  a.relaxation = 'ions'
  assert a.relaxation == 'ionic'
  assert a.isif == 2
  a.relaxation = 'ionic'
  assert a.relaxation == 'ionic'
  assert a.isif == 2

  a.relaxation = 'cellshape, volume ions'
  print a.relaxation
  assert a.relaxation == 'cellshape ionic volume'
  assert a.isif == 3

  a.relaxation = 'cellshape, ionic'
  assert a.relaxation == 'cellshape ionic'
  assert a.isif == 4

  a.relaxation = 'volume'
  assert a.relaxation == 'volume'
  assert a.isif == 7

  a.relaxation = 'static'
  assert a.ibrion == -1
  assert a.nsw == 0
  assert a.isif == 2

  try: a.relaxation = 'ions, volume'
  except ValueError: pass
  else: raise Exception
Exemplo n.º 32
0
def test_magmom():
  from pickle import loads, dumps
  from pylada.crystal.cppwrappers import Structure
  from pylada.vasp import Vasp

  u = 0.25
  x, y = u, 0.25-u
  structure = Structure([[0,0.5,0.5],[0.5,0,0.5],[0.5,0.5,0]]) \
                       .add_atom(5.000000e-01, 5.000000e-01, 5.000000e-01, "Mg") \
                       .add_atom(5.000000e-01, 2.500000e-01, 2.500000e-01, "Mg") \
                       .add_atom(2.500000e-01, 5.000000e-01, 2.500000e-01, "Mg") \
                       .add_atom(2.500000e-01, 2.500000e-01, 5.000000e-01, "Mg") \
                       .add_atom(8.750000e-01, 8.750000e-01, 8.750000e-01, "Al") \
                       .add_atom(1.250000e-01, 1.250000e-01, 1.250000e-01, "Al") \
                       .add_atom(     x,     x,     x, "O") \
                       .add_atom(     x,     y,     y, "O") \
                       .add_atom(     y,     x,     y, "O") \
                       .add_atom(     y,     y,     x, "O") \
                       .add_atom(    -x,    -x,    -x, "O") \
                       .add_atom(    -x,    -y,    -y, "O") \
                       .add_atom(    -y,    -x,    -y, "O") \
                       .add_atom(    -y,    -y,    -x, "O") 
  
  for atom in structure:
    if atom.type == 'Mg': atom.magmom = -1e0

  vasp = Vasp()
  vasp.magmom = None
  assert vasp.magmom is None
  assert vasp._input['magmom'].keyword == 'MAGMOM'
  assert vasp._input['magmom'].output_map(vasp=vasp, structure=structure) is None

  # ispin == 1
  vasp.magmom = True
  vasp.ispin = 1
  assert vasp._input['magmom'].output_map(vasp=vasp, structure=structure) is None
  # ispins == 2, magmom == False
  vasp.ispin = 2
  vasp.magmom = None
  assert vasp._input['magmom'].output_map(vasp=vasp, structure=structure) is None
  vasp.magmom = False
  assert vasp._input['magmom'].output_map(vasp=vasp, structure=structure) is None
  # now for real print
  vasp.magmom = True
  assert 'MAGMOM' in vasp._input['magmom'].output_map(vasp=vasp, structure=structure)
  assert vasp._input['magmom'].output_map(vasp=vasp, structure=structure)['MAGMOM'] == '4*-1.00 2*0.00 8*0.00'
  # now print a string directly.
  vasp.magmom = 'hello'
  assert vasp.magmom == 'hello'
  assert 'MAGMOM' in vasp._input['magmom'].output_map(vasp=vasp, structure=structure)
  assert vasp._input['magmom'].output_map(vasp=vasp, structure=structure)['MAGMOM'] == 'hello'

  # check repr
  assert repr(vasp._input['magmom']) == "Magmom(value='hello')"
  # check pickling
  assert repr(loads(dumps(vasp._input['magmom']))) == "Magmom(value='hello')"

  # more tests.
  for atom, mag in zip(structure, [1, -1, 1, 1]):
    if atom.type == 'Mg': atom.magmom = mag
  for atom, mag in zip(structure, [0.5, 0.5]):
    if atom.type == 'Al': atom.magmom = mag

  vasp.magmom = True
  assert 'MAGMOM' in vasp._input['magmom'].output_map(vasp=vasp, structure=structure)
  assert vasp._input['magmom'].output_map(vasp=vasp, structure=structure)['MAGMOM'] == '1.00 -1.00 2*1.00 2*0.00 8*0.00'
Exemplo n.º 33
0
    def __call__(self, structure, outdir=None, vasp=None, **kwargs):

        from copy import deepcopy
        from os import getcwd
        from os.path import join
        from pylada.misc import RelativePath
        from pylada.error import ExternalRunFailed
        from pylada.vasp.extract import Extract, MassExtract
        from pylada.vasp import Vasp
        from pylada.vasp.relax import Relax

        # make this function stateless.
        structure_ = structure.copy()
        outdir = getcwd() if outdir is None else RelativePath(outdir).path

        ############ Calc 1 ###############
        name = self.names[0]

        ## functional for Calc 1
        relax = Relax(copy=vasp)
        relax.relaxation = "volume ionic cellshape"
        relax.maxiter = 10
        relax.keep_steps = True
        relax.first_trial = {"kpoints": "\n0\nAuto\n10", "encut": 0.9}
        ## end of the functional

        params = deepcopy(kwargs)
        fulldir = join(outdir, name)

        ## if this calculation has not been done run it
        output = relax(structure_, outdir=fulldir, restart=None, **params)
        if not output.success:
            raise ExternalRunFailed("VASP calculation did not succeed.")

        ############ Calc 2 ###############
        name = self.names[1]

        ## functional for Calc 2
        final = Vasp(copy=vasp)
        final.nbands = 24 * len(structure_)
        final.kpoints = "\n0\nGamma\n2 2 2\n0. 0. 0.\n"
        final.loptics = True
        final.relaxation = "static"
        ## end of the functional

        params = deepcopy(kwargs)
        fulldir = join(outdir, name)

        ## if this calculation has not been done, run it
        output = final(structure_, outdir=fulldir, restart=output, **params)
        if not output.success:
            raise ExternalRunFailed("VASP calculation did not succeed.")

        ############## GW Loop ########################
        for name in self.names[2:]:

            gw = Vasp(copy=vasp)

            gw.kpoints = "\n0\nGamma\n2 2 2\n0. 0. 0.\n"
            gw.nbands = 24 * len(structure_)
            gw.lcharg = True

            gw.add_keyword('nelm', 1)
            gw.add_keyword('algo', 'gw')
            gw.add_keyword('LMAXFOCKAE', 4)
            gw.add_keyword('nomega', 64)
            gw.add_keyword('precfock', 'fast')
            gw.add_keyword('encutgw', 50)
            gw.add_keyword('encutlf', 50)
            gw.add_keyword('lrpa', False)
            gw.add_keyword('nkred', 2)

            params = deepcopy(kwargs)
            fulldir = join(outdir, name)

            ## if this calculation has not been done, run it
            output = gw(structure_, outdir=fulldir, restart=output, **params)
            if not output.success:
                raise ExternalRunFailed("VASP calculation did not succeed.")
        #########################

        return self.Extract(fulldir)
def test_typed():
    from pylada.vasp import Vasp
    from pylada.error import ValueError
    a = Vasp()

    assert a.nbands is None
    assert a._input['nbands'].keyword == 'nbands'
    assert a._input['nbands'].output_map() is None

    a.nbands = 50
    assert a.nbands == 50
    assert 'nbands' in a._input['nbands'].output_map()
    assert a._input['nbands'].output_map()['nbands'] == str(a.nbands)
    a.nbands = '51'
    assert a.nbands == 51
    assert 'nbands' in a._input['nbands'].output_map()
    assert a._input['nbands'].output_map()['nbands'] == str(a.nbands)
    a.nbands = None
    assert a.nbands is None
    assert a._input['nbands'].output_map() is None

    try:
        a.nbands = 'a'
    except ValueError:
        pass
    else:
        raise Exception()

    assert a.smearings is None
    assert a._input['smearings'].keyword == 'smearings'
    assert a._input['smearings'].output_map() is None
    a.smearings = [1.5, 1.0, 0.5]
    assert len(a.smearings) == 3
    assert all(abs(i - v) < 1e-8 for i, v in zip(a.smearings, [1.5, 1.0, 0.5]))
    assert 'smearings' in a._input['smearings'].output_map()
    assert all(
        abs(float(i) - v) < 1e-8 for i, v in zip(
            a._input['smearings'].output_map()['smearings'].split(),
            [1.5, 1.0, 0.5]))
    a.smearings = ['1.2', '0.2']
    assert len(a.smearings) == 2
    assert all(abs(i - v) < 1e-8 for i, v in zip(a.smearings, [1.2, 0.2]))
    assert 'smearings' in a._input['smearings'].output_map()
    assert all(
        abs(float(i) - v) < 1e-8 for i, v in zip(
            a._input['smearings'].output_map()['smearings'].split(),
            [1.2, 0.2]))
    a.smearings = '1.3 0.3'
    assert len(a.smearings) == 2
    assert all(abs(i - v) < 1e-8 for i, v in zip(a.smearings, [1.3, 0.3]))
    assert 'smearings' in a._input['smearings'].output_map()
    assert all(
        abs(float(i) - v) < 1e-8 for i, v in zip(
            a._input['smearings'].output_map()['smearings'].split(),
            [1.3, 0.3]))
    a.smearings = '1.3, 0.3'
    assert len(a.smearings) == 2
    assert all(abs(i - v) < 1e-8 for i, v in zip(a.smearings, [1.3, 0.3]))
    a.smearings = '1.3; 0.3'
    assert len(a.smearings) == 2
    assert all(abs(i - v) < 1e-8 for i, v in zip(a.smearings, [1.3, 0.3]))
    a.smearings = None
    assert a.smearings is None
    assert a._input['smearings'].output_map() is None

    try:
        a.smearings = 5.5
    except ValueError:
        pass
    else:
        raise Exception()
    try:
        a.smearings = [5.5, 'a']
    except ValueError:
        pass
    else:
        raise Exception()
Exemplo n.º 35
0
def test_ediffg():
  from pickle import loads, dumps
  from pylada.vasp import Vasp
  from pylada.crystal import Structure
  a = Vasp()

  u = 0.25
  x, y = u, 0.25-u
  structure = Structure([[0,0.5,0.5],[0.5,0,0.5],[0.5,0.5,0]]) \
                       .add_atom(5.000000e-01, 5.000000e-01, 5.000000e-01, "Mg") \
                       .add_atom(5.000000e-01, 2.500000e-01, 2.500000e-01, "Mg") \
                       .add_atom(2.500000e-01, 5.000000e-01, 2.500000e-01, "Mg") \
                       .add_atom(2.500000e-01, 2.500000e-01, 5.000000e-01, "Mg") \
                       .add_atom(8.750000e-01, 8.750000e-01, 8.750000e-01, "Al") \
                       .add_atom(1.250000e-01, 1.250000e-01, 1.250000e-01, "Al") \
                       .add_atom(     x,     x,     x, "O") \
                       .add_atom(     x,     y,     y, "O") \
                       .add_atom(     y,     x,     y, "O") \
                       .add_atom(     y,     y,     x, "O") \
                       .add_atom(    -x,    -x,    -x, "O") \
                       .add_atom(    -x,    -y,    -y, "O") \
                       .add_atom(    -y,    -x,    -y, "O") \
                       .add_atom(    -y,    -y,    -x, "O") 
  
  N = float(len(structure))

  o = a._input['ediffg']
  d = {'Ediffg': o.__class__}
  assert a.ediffg is None
  assert a.ediffg_per_atom is None
  assert o.output_map() is None
  assert eval(repr(o), d).output_map() is None
  assert eval(repr(o), d).keyword == 'ediffg'
  assert loads(dumps(o)).output_map() is None
  a.ediffg_per_atom = 1e-5
  a.ediffg = 2e-4
  assert abs(a.ediffg - 2e-4) < 1e-8
  assert a.ediffg_per_atom is None
  assert abs(float(o.output_map(structure=structure)['ediffg']) - a.ediffg) < a.ediffg * 1e-2
  assert abs(float(eval(repr(o), d).output_map(structure=structure)['ediffg']) - a.ediffg) < a.ediffg * 1e-2
  assert abs(float(loads(dumps(o)).output_map(structure=structure)['ediffg']) - a.ediffg) < a.ediffg * 1e-2
  a.ediffg_per_atom = 1e-5
  a.ediffg = -2e-4
  assert abs(a.ediffg + 2e-4) < 1e-8
  assert a.ediffg_per_atom is None
  assert abs(float(o.output_map(structure=structure)['ediffg']) - a.ediffg) < -a.ediffg * 1e-2
  assert abs(float(eval(repr(o), d).output_map(structure=structure)['ediffg']) - a.ediffg) < -a.ediffg * 1e-2
  assert abs(float(loads(dumps(o)).output_map(structure=structure)['ediffg']) - a.ediffg) < -a.ediffg * 1e-2


  a.ediffg = 2e-4
  a.ediffg_per_atom = 2e-4
  o = a._input['ediffg_per_atom']
  d = {'EdiffgPerAtom': o.__class__}
  assert a.ediffg is None
  assert abs(a.ediffg_per_atom - 2e-4) < 1e-8
  assert abs(float(o.output_map(structure=structure)['ediffg']) - 2e-4*N) < 2e-4 * 1e-2
  assert abs(float(eval(repr(o), d).output_map(structure=structure)['ediffg']) - 2e-4*N) < 2e-4 * 1e-2
  assert abs(float(loads(dumps(o)).output_map(structure=structure)['ediffg']) - 2e-4*N) < 2e-4 * 1e-2
  a.ediffg = 2e-4
  a.ediffg_per_atom = -2e-4
  assert a.ediffg is None
  assert abs(a.ediffg_per_atom + 2e-4) < 1e-8
  assert abs(float(o.output_map(structure=structure)['ediffg']) + 2e-4) < 2e-4 * 1e-2
  assert abs(float(eval(repr(o), d).output_map(structure=structure)['ediffg']) + 2e-4) < 2e-4 * 1e-2
  assert abs(float(loads(dumps(o)).output_map(structure=structure)['ediffg']) + 2e-4) < 2e-4 * 1e-2
  a.ediffg_per_atom = None
  assert a.ediffg is None
  assert a.ediffg_per_atom is None
  assert o.output_map() is None
  assert eval(repr(o), d).output_map() is None
  assert eval(repr(o), d).keyword == 'ediffg'
  assert loads(dumps(o)).output_map() is None

  a.ediffg = 1e-4
  a.ediffg_per_atom = None
  assert abs(a.ediffg-1e-4) < 1e-8
  assert a.ediffg_per_atom is None
  a.ediffg_per_atom = 1e-4
  a.ediffg = None
  assert abs(a.ediffg_per_atom-1e-4) < 1e-8
  assert a.ediffg is None
Exemplo n.º 36
0
def test_typed():
  from pylada.vasp import Vasp
  from pylada.error import ValueError
  a = Vasp()

  assert a.nbands is None
  assert a._input['nbands'].keyword == 'nbands'
  assert a._input['nbands'].output_map() is None

  a.nbands = 50
  assert a.nbands == 50
  assert 'nbands' in a._input['nbands'].output_map()
  assert a._input['nbands'].output_map()['nbands'] == str(a.nbands)
  a.nbands = '51'
  assert a.nbands == 51
  assert 'nbands' in a._input['nbands'].output_map()
  assert a._input['nbands'].output_map()['nbands'] == str(a.nbands)
  a.nbands = None
  assert a.nbands is None
  assert a._input['nbands'].output_map() is None

  try: a.nbands = 'a'
  except ValueError: pass
  else: raise Exception()

  assert a.smearings is None
  assert a._input['smearings'].keyword == 'smearings'
  assert a._input['smearings'].output_map() is None
  a.smearings = [1.5, 1.0, 0.5]
  assert len(a.smearings) == 3
  assert all(abs(i-v) < 1e-8 for i, v in zip(a.smearings, [1.5, 1.0, 0.5]))
  assert 'smearings' in a._input['smearings'].output_map()
  assert all(abs(float(i)-v) < 1e-8 for i, v in zip(a._input['smearings'].output_map()['smearings'].split(), [1.5, 1.0, 0.5]))
  a.smearings = ['1.2', '0.2']
  assert len(a.smearings) == 2
  assert all(abs(i-v) < 1e-8 for i, v in zip(a.smearings, [1.2, 0.2]))
  assert 'smearings' in a._input['smearings'].output_map()
  assert all(abs(float(i)-v) < 1e-8 for i, v in zip(a._input['smearings'].output_map()['smearings'].split(), [1.2, 0.2]))
  a.smearings = '1.3 0.3'
  assert len(a.smearings) == 2
  assert all(abs(i-v) < 1e-8 for i, v in zip(a.smearings, [1.3, 0.3]))
  assert 'smearings' in a._input['smearings'].output_map()
  assert all(abs(float(i)-v) < 1e-8 for i, v in zip(a._input['smearings'].output_map()['smearings'].split(), [1.3, 0.3]))
  a.smearings = '1.3, 0.3'
  assert len(a.smearings) == 2
  assert all(abs(i-v) < 1e-8 for i, v in zip(a.smearings, [1.3, 0.3]))
  a.smearings = '1.3; 0.3'
  assert len(a.smearings) == 2
  assert all(abs(i-v) < 1e-8 for i, v in zip(a.smearings, [1.3, 0.3]))
  a.smearings = None
  assert a.smearings is None
  assert a._input['smearings'].output_map() is None
  
  try: a.smearings = 5.5
  except ValueError: pass
  else: raise Exception()
  try: a.smearings = [5.5, 'a']
  except ValueError: pass
  else: raise Exception()
Exemplo n.º 37
0
def test():
  from collections import namedtuple
  from pickle import loads, dumps
  from numpy import all, abs, array
  from pylada.crystal import Structure
  from pylada.vasp import Vasp
  from pylada.vasp.specie import U, nlep
  import pylada

  u = 0.25
  x, y = u, 0.25-u
  structure = Structure([[0,0.5,0.5],[0.5,0,0.5],[0.5,0.5,0]]) \
                       .add_atom(5.000000e-01, 5.000000e-01, 5.000000e-01, "A") \
                       .add_atom(5.000000e-01, 2.500000e-01, 2.500000e-01, "A") \
                       .add_atom(2.500000e-01, 5.000000e-01, 2.500000e-01, "A") \
                       .add_atom(2.500000e-01, 2.500000e-01, 5.000000e-01, "A") \
                       .add_atom(8.750000e-01, 8.750000e-01, 8.750000e-01, "B") \
                       .add_atom(1.250000e-01, 1.250000e-01, 1.250000e-01, "B") \
                       .add_atom(     x,     x,     x, "X") \
                       .add_atom(     x,     y,     y, "X") \
                       .add_atom(     y,     x,     y, "X") \
                       .add_atom(     y,     y,     x, "X") \
                       .add_atom(    -x,    -x,    -x, "X") \
                       .add_atom(    -x,    -y,    -y, "X") \
                       .add_atom(    -y,    -x,    -y, "X") \
                       .add_atom(    -y,    -y,    -x, "X") 
  a = Vasp()
  Specie = namedtuple('Specie', ['U'])
  a.species = {'A': Specie([]), 'B': Specie([]), 'X': Specie([])}
  pylada.vasp_has_nlep  = False

  o = a._input['ldau']
  d = {'LDAU': o.__class__}
  assert a.ldau == True
  assert o.output_map(vasp=a, structure=structure) is None
  assert eval(repr(o), d)._value == True
  assert eval(repr(o), d).keyword == 'LDAU'
  assert loads(dumps(o)).keyword == 'LDAU'
  assert loads(dumps(o))._value 

  # now disables U.
  a.species = {'A': Specie([U(2, 0, 0.5)]), 'B': Specie([]), 'X': Specie([])}
  a.ldau = False
  assert a.ldau == False
  print o
  assert o.output_map(vasp=a) is None
  # now prints U
  a.ldau = True
  map = o.output_map(vasp=a, structure=structure)
  assert map['LDAU'] == '.TRUE.'
  assert map['LDAUTYPE'] == '2'
  assert all(abs(array(map['LDUJ'].split(), dtype='float64')) < 1e-8)
  assert all(abs(array(map['LDUU'].split(), dtype='float64')-[0.5, 0, 0]) < 1e-8)
  assert all(abs(array(map['LDUL'].split(), dtype='float64')-[0, -1, -1]) < 1e-8)
  a.species = {'A': Specie([U(2, 0, 0.5)]), 'B': Specie([U(2, 1, 0.6)]), 'X': Specie([])}
  map = o.output_map(vasp=a, structure=structure)
  assert map['LDAU'] == '.TRUE.'
  assert map['LDAUTYPE'] == '2'
  assert all(abs(array(map['LDUJ'].split(), dtype='float64')) < 1e-8)
  assert all(abs(array(map['LDUU'].split(), dtype='float64')-[0.5, 0, 0.6]) < 1e-8)
  assert all(abs(array(map['LDUL'].split(), dtype='float64')-[0, -1, 1]) < 1e-8)
  

  # now tries NLEP
  pylada.vasp_has_nlep = True
  a.species = {'A': Specie([U(2, 0, 0.5)]), 'B': Specie([U(2, 0, -0.5), nlep(2, 1, -1.0)]), 'X': Specie([])}
  a.ldau = False
  assert a.ldau == False
  assert o.output_map(vasp=a) is None
  a.ldau = True
  map = o.output_map(vasp=a, structure=structure)
  assert map['LDAU'] == '.TRUE.'
  assert map['LDAUTYPE'] == '2'
  assert all(abs(array(map['LDUL1'].split(), dtype='float64')-[0, -1, 0]) < 1e-8)
  assert all(abs(array(map['LDUU1'].split(), dtype='float64')-[0.5, 0, -0.5]) < 1e-8)
  assert all(abs(array(map['LDUJ1'].split(), dtype='float64')-[0, 0, 0]) < 1e-8)
  assert all(abs(array(map['LDUO1'].split(), dtype='float64')-[1, 1, 1]) < 1e-8)
  assert all(abs(array(map['LDUL2'].split(), dtype='float64')-[-1, -1, 1]) < 1e-8)
  assert all(abs(array(map['LDUU2'].split(), dtype='float64')-[0, 0, -1.0]) < 1e-8)
  assert all(abs(array(map['LDUJ2'].split(), dtype='float64')-[0, 0, 0]) < 1e-8)
  assert all(abs(array(map['LDUO2'].split(), dtype='float64')-[1, 1, 2]) < 1e-8)

  a.species = {'A': Specie([U(2, 0, 0.5)]), 'B': Specie([U(2, 0, -0.5), nlep(2, 2, -1.0, -3.0)]), 'X': Specie([])}
  a.ldau = True
  map = o.output_map(vasp=a, structure=structure)
  assert map['LDAU'] == '.TRUE.'
  assert map['LDAUTYPE'] == '2'
  assert all(abs(array(map['LDUL1'].split(), dtype='float64')-[0, -1, 0]) < 1e-8)
  assert all(abs(array(map['LDUU1'].split(), dtype='float64')-[0.5, 0, -0.5]) < 1e-8)
  assert all(abs(array(map['LDUJ1'].split(), dtype='float64')-[0, 0, 0]) < 1e-8)
  assert all(abs(array(map['LDUO1'].split(), dtype='float64')-[1, 1, 1]) < 1e-8)
  assert all(abs(array(map['LDUL2'].split(), dtype='float64')-[-1, -1, 2]) < 1e-8)
  assert all(abs(array(map['LDUU2'].split(), dtype='float64')-[0, 0, -1.0]) < 1e-8)
  assert all(abs(array(map['LDUJ2'].split(), dtype='float64')-[0, 0, -3.0]) < 1e-8)
  assert all(abs(array(map['LDUO2'].split(), dtype='float64')-[1, 1, 3]) < 1e-8)
Exemplo n.º 38
0
def main():
  from boost.mpi import world
  from scipy.optimize import fmin as scipy_simplex
  from pylada.vasp import Extract, ExtractGW, Vasp, Specie
  from pylada.vasp.specie import nlep as nlep_parameters, U as u_parameters
  from pylada.vasp.incar import Standard, NBands
  from sys import exit

  indir = "SnO2"
  dft_in = Extract(directory=indir, comm=world)
  dft_in.OUTCAR = "OUTCAR_pbe"
  dft_in.CONTCAR = "POSCAR"
  gw_in = ExtractGW(directory=indir, comm=world)
  gw_in.OUTCAR = "OUTCAR_gw"
  gw_in.CONTCAR = "POSCAR"

  # Creates species with nlep parameters to optimize
  species = Specie\
            (
              "Sn", 
              path="pseudos/Sn", 
              U=[nlep_parameters(type="Dudarev", l=i, U0=0e0) for i in ["s", "p", "d"]]
            ),\
            Specie\
            (
              "O", 
              path="pseudos/O",
              U=[nlep_parameters(type="Dudarev", l=i, U0=0e0) for i in ["s", "p"]]
            )
  # add U to Sn atoms.
  species[0].U.append( u_parameters(type="Dudarev", U=2e0, l=2) )
  # creates vasp launcher
  vasp = Vasp\
         (
           kpoints    = lambda x: "Automatic generation\n0\ngamma\n6 6 10\n0 0 0",
           precision  = "accurate",
           smearing   = "bloechl",
           ediff      = 1e-5,
           relaxation = "ionic",
           encut      = 1, # uses ENMAX * 1, which is VASP default
           species    = species
         )
  # adds some extra parameters.
  vasp.nbands     = Standard("NBANDS", 64)
  vasp.lorbit     = Standard("LORBIT", 10)
  vasp.npar       = Standard("NPAR", 2)
  vasp.lplane     = Standard("LPLANE", ".TRUE.")
  vasp.addgrid    = Standard("ADDGRID", ".TRUE.")
  del vasp.fftgrid

  # creates objective function.
  objective = Objective(vasp, dft_in, gw_in)

  x0, f0, iter, funcalls, warnflag = scipy_simplex(objective, objective.x, maxfun=150, full_output=1, xtol=0.2)
  world.barrier()
  if world.rank == 0:
    print "minimum value:", f0
    print "for: ", x0 * units
    print "after %i iterations and %i function calls." % (iter, funcalls)
    print "with warning flag: ", warnflag 
    print final(x0)
Exemplo n.º 39
0
def test_encut():
    from os.path import dirname
    from pickle import loads, dumps
    from quantities import eV, hartree
    import quantities
    import numpy
    from pylada.vasp import Vasp
    from pylada.crystal import Structure

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")
    a = Vasp()
    a.add_specie = "Si", "{0}/pseudos/Si".format(dirname(__file__))

    o = a._input['encut']
    d = {'Encut': o.__class__}
    d.update(quantities.__dict__)
    d.update(numpy.__dict__)
    assert a.ediff is None
    assert o.output_map() is None
    assert eval(repr(o), d).output_map() is None
    assert eval(repr(o), d).keyword == 'encut'
    assert loads(dumps(o)).output_map() is None

    a.encut = 1e0
    assert abs(a.encut - 1e0) < 1e-8
    assert abs(float(o.output_map(structure=structure, vasp=a)['encut']) - 245.345) < 1e-8
    assert abs(float(eval(repr(o), d).output_map(
        structure=structure, vasp=a)['encut']) - 245.345) < 1e-8
    assert abs(float(loads(dumps(o)).output_map(
        structure=structure, vasp=a)['encut']) - 245.345) < 1e-8
    assert abs(eval(repr(o), d).value - 1.0) < 1e-8
    assert abs(loads(dumps(o)).value - 1.0) < 1e-8
    a.encut = 0.8
    assert abs(a.encut - 0.8) < 1e-8
    assert abs(float(o.output_map(structure=structure, vasp=a)['encut']) - 245.345 * 0.8) < 1e-8
    assert abs(float(eval(repr(o), d).output_map(
        structure=structure, vasp=a)['encut']) - 245.345 * 0.8) < 1e-8
    assert abs(float(loads(dumps(o)).output_map(
        structure=structure, vasp=a)['encut']) - 245.345 * 0.8) < 1e-8
    assert abs(eval(repr(o), d).value - 0.8) < 1e-8
    assert abs(loads(dumps(o)).value - 0.8) < 1e-8
    a.encut = 200
    assert abs(a.encut - 200) < 1e-8
    assert abs(float(o.output_map(structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(float(eval(repr(o), d).output_map(
        structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(float(loads(dumps(o)).output_map(structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(eval(repr(o), d).value - 200) < 1e-8
    assert abs(loads(dumps(o)).value - 200) < 1e-8
    a.encut = 200 * eV
    assert abs(a.encut - 200 * eV) < 1e-8
    assert a.encut.units == eV
    assert abs(float(o.output_map(structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(float(eval(repr(o), d).output_map(
        structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(float(loads(dumps(o)).output_map(structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(eval(repr(o), d).value - 200 * eV) < 1e-8
    assert abs(loads(dumps(o)).value - 200 * eV) < 1e-8
    assert eval(repr(o), d).value.units == eV
    assert loads(dumps(o)).value.units == eV
    a.encut = (200 * eV).rescale(hartree)
    assert a.encut.units == hartree
    assert abs(a.encut - 200 * eV) < 1e-8
    assert abs(float(o.output_map(structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(float(eval(repr(o), d).output_map(
        structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(float(loads(dumps(o)).output_map(structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(eval(repr(o), d).value - 200 * eV) < 1e-8
    assert abs(loads(dumps(o)).value - 200 * eV) < 1e-8
    assert eval(repr(o), d).value.units == hartree
    assert loads(dumps(o)).value.units == hartree

    o = a._input['encutgw']
    d = {'EncutGW': o.__class__}
    d.update(quantities.__dict__)
    d.update(numpy.__dict__)
    assert a.ediff is None
    assert o.output_map() is None
    assert eval(repr(o), d).output_map() is None
    assert eval(repr(o), d).keyword == 'encutgw'
    assert loads(dumps(o)).output_map() is None
    a.encutgw = (200 * eV).rescale(hartree)
    assert a.encutgw.units == hartree
    assert abs(a.encutgw - 200 * eV) < 1e-8
    assert abs(float(o.output_map(structure=structure, vasp=a)['encutgw']) - 200) < 1e-8
    assert abs(float(eval(repr(o), d).output_map(
        structure=structure, vasp=a)['encutgw']) - 200) < 1e-8
    assert abs(float(loads(dumps(o)).output_map(
        structure=structure, vasp=a)['encutgw']) - 200) < 1e-8
    assert abs(eval(repr(o), d).value - 200 * eV) < 1e-8
    assert abs(loads(dumps(o)).value - 200 * eV) < 1e-8
    assert eval(repr(o), d).value.units == hartree
    assert loads(dumps(o)).value.units == hartree
Exemplo n.º 40
0
    def __call__(self, structure, outdir=None, vasp=None, **kwargs ):

        from copy import deepcopy
        from os import getcwd
        from os.path import join
        from pylada.misc import RelativePath
        from pylada.error import ExternalRunFailed
        from pylada.vasp.extract import Extract, MassExtract
        from pylada.vasp import Vasp
        from pylada.vasp.relax import Relax

        # make this function stateless.
        structure_ = structure.copy()
        outdir = getcwd() if outdir is None else RelativePath(outdir).path

        ############ Calc 1 ###############
        name  = self.names[0]

        ## functional for Calc 1
        relax = Relax(copy=vasp)
        relax.relaxation = "volume ionic cellshape"
        relax.maxiter = 10
        relax.keep_steps = True
        relax.first_trial = { "kpoints": "\n0\nAuto\n10", "encut": 0.9 }
        ## end of the functional

        params = deepcopy(kwargs)
        fulldir = join(outdir, name)

        ## if this calculation has not been done run it
        output = relax(structure_, outdir=fulldir, restart=None, **params)
        if not output.success:
            raise ExternalRunFailed("VASP calculation did not succeed.") 

        ############ Calc 2 ###############  
        name  = self.names[1]

        ## functional for Calc 2
        final = Vasp(copy=vasp)
        final.nbands=24*len(structure_)
        final.kpoints="\n0\nGamma\n2 2 2\n0. 0. 0.\n"
        final.loptics=True
        final.relaxation="static"
        ## end of the functional

        params = deepcopy(kwargs)
        fulldir = join(outdir, name)

        ## if this calculation has not been done, run it
        output = final(structure_, outdir=fulldir, restart=output, **params)
        if not output.success:
            raise ExternalRunFailed("VASP calculation did not succeed.") 

        ############## GW Loop ########################
        for name in self.names[2:]:

            gw = Vasp(copy=vasp)

            gw.kpoints    ="\n0\nGamma\n2 2 2\n0. 0. 0.\n"
            gw.nbands     =24*len(structure_)
            gw.lcharg     = True

            gw.add_keyword('nelm',1)
            gw.add_keyword('algo','gw')
            gw.add_keyword('LMAXFOCKAE',4)
            gw.add_keyword('nomega',64)
            gw.add_keyword('precfock','fast')
            gw.add_keyword('encutgw',50)
            gw.add_keyword('encutlf',50)
            gw.add_keyword('lrpa',False)
            gw.add_keyword('nkred',2)

            params = deepcopy(kwargs)
            fulldir = join(outdir, name)

            ## if this calculation has not been done, run it
            output = gw(structure_, outdir=fulldir, restart=output, **params)
            if not output.success:
                raise ExternalRunFailed("VASP calculation did not succeed.") 
        #########################

        return self.Extract(fulldir)
Exemplo n.º 41
0
def vasp():
    from pylada.vasp import Vasp
    return Vasp()
def test_choice():
    from pickle import loads, dumps
    from pylada.vasp import Vasp
    a = Vasp()

    assert a.ispin is None
    assert a._input['ispin'].keyword == 'ispin'
    assert a._input['ispin'].output_map() is None
    a.ispin = 1
    assert a.ispin == 1
    assert 'ispin' in a._input['ispin'].output_map()
    assert a._input['ispin'].output_map()['ispin'] == '1'
    a.ispin = 2
    assert a.ispin == 2
    assert 'ispin' in a._input['ispin'].output_map()
    assert a._input['ispin'].output_map()['ispin'] == '2'
    a.ispin = None
    assert a.ispin is None
    assert a._input['ispin'].keyword == 'ispin'
    assert a._input['ispin'].output_map() is None

    try:
        a.ispin = 5
    except:
        pass
    else:
        raise RuntimeError()

    a.ispin = '1'
    assert a.ispin == 1
    a.ispin = '2'
    assert a.ispin == 2

    try:
        a.ispin = '3'
    except:
        pass
    else:
        raise RuntimeError()

    a.ispin = None
    o = a._input['ispin']
    d = {'ChoiceKeyword': o.__class__}
    assert repr(eval(repr(o), d)) == repr(o)
    assert eval(repr(o), d).output_map() is None
    assert repr(loads(dumps(o))) == repr(o)
    a.ispin = 2
    o = a._input['ispin']
    assert repr(eval(repr(o), d)) == repr(o)
    assert eval(repr(o), d).output_map()['ispin'] == '2'
    assert repr(loads(dumps(o))) == repr(o)
Exemplo n.º 43
0
def test_istruc():
    from collections import namedtuple
    from pickle import loads, dumps
    from os import remove
    from os.path import join, exists
    from shutil import rmtree
    from tempfile import mkdtemp
    from pylada.vasp.files import POSCAR, CONTCAR
    from pylada.vasp import Vasp
    from pylada.crystal import Structure, read, specieset, write
    from pylada.error import ValueError

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")

    Extract = namedtuple("Extract", ['directory', 'success', 'structure'])
    a = Vasp()
    o = a._input['istruc']
    d = {'IStruc': o.__class__}

    directory = mkdtemp()
    try:
        assert a.istruc == 'auto'
        assert o.output_map(vasp=a, outdir=directory,
                            structure=structure) is None
        assert eval(repr(o), d).value == 'auto'
        assert loads(dumps(o)).value == 'auto'
        assert exists(join(directory, POSCAR))
        remove(join(directory, POSCAR))

        # check reading from outcar but only on success.
        a.restart = Extract(directory, False, structure.copy())
        a.restart.structure[1].pos[0] += 0.02
        assert a.istruc == 'auto'
        assert o.output_map(vasp=a, outdir=directory,
                            structure=structure) is None
        assert exists(join(directory, POSCAR))
        other = read.poscar(join(directory, POSCAR),
                            types=specieset(structure))
        assert abs(other[1].pos[0] - 0.25) < 1e-8
        assert abs(other[1].pos[0] - 0.27) > 1e-8
        # check reading from outcar but only on success.
        a.restart = Extract(directory, True, structure.copy())
        a.restart.structure[1].pos[0] += 0.02
        assert a.istruc == 'auto'
        assert o.output_map(vasp=a, outdir=directory,
                            structure=structure) is None
        assert exists(join(directory, POSCAR))
        other = read.poscar(join(directory, POSCAR),
                            types=specieset(structure))
        assert abs(other[1].pos[0] - 0.25) > 1e-8
        assert abs(other[1].pos[0] - 0.27) < 1e-8

        # Now check CONTCAR
        write.poscar(structure, join(directory, CONTCAR))
        assert a.istruc == 'auto'
        assert o.output_map(vasp=a, outdir=directory,
                            structure=structure) is None
        assert exists(join(directory, POSCAR))
        other = read.poscar(join(directory, POSCAR),
                            types=specieset(structure))
        assert abs(other[1].pos[0] - 0.25) < 1e-8
        assert abs(other[1].pos[0] - 0.27) > 1e-8

        # Check some failure modes.
        write.poscar(structure, join(directory, CONTCAR))
        structure[0].type = 'Ge'
        a.restart = None
        try:
            o.output_map(vasp=a, outdir=directory, structure=structure)
        except ValueError:
            pass
        else:
            raise Exception()
        structure[0].type = 'Si'
        structure.add_atom(0.25, 0, 0, 'Si')
        try:
            o.output_map(vasp=a, outdir=directory, structure=structure)
        except ValueError:
            pass
        else:
            raise Exception()

    finally:
        rmtree(directory)
Exemplo n.º 44
0
def test_icharg():
    from time import sleep
    from collections import namedtuple
    from pickle import loads, dumps
    from os import remove, makedirs
    from os.path import join, exists
    from shutil import rmtree
    from tempfile import mkdtemp
    from pylada.vasp.files import WAVECAR, CHGCAR
    from pylada.vasp import Vasp
    from pylada.misc import local_path
    from pylada.error import ValueError

    Extract = namedtuple("Extract", ['directory', 'success'])
    a = Vasp()
    o = a._input['icharg']
    d = {'ICharg': o.__class__}

    directory = mkdtemp()
    if directory in ['/tmp/test', '/tmp/test/']:
        if exists(directory):
            rmtree(directory)
        makedirs(directory)
    try:
        assert a.icharg == 'auto'
        assert o.output_map(vasp=a, outdir=directory)['icharg'] == '2'
        assert eval(repr(o), d).value == 'auto'
        assert loads(dumps(o)).value == 'auto'

        restartdir = join(directory, 'restart')
        local_path(restartdir).ensure(dir=True)
        with open(join(restartdir, CHGCAR), 'w') as file:
            file.write('hello')
        with open(join(restartdir, WAVECAR), 'w') as file:
            file.write('hello')

        # do not copy if not successful
        a.restart = Extract(restartdir, False)
        assert o.output_map(vasp=a, outdir=directory)['icharg'] == '2'
        assert not exists(join(directory, CHGCAR))
        assert not exists(join(directory, WAVECAR))

        # do not copy if empty
        with open(join(restartdir, CHGCAR), 'w') as file:
            pass
        with open(join(restartdir, WAVECAR), 'w') as file:
            pass
        a.restart = Extract(restartdir, True)
        assert o.output_map(vasp=a, outdir=directory)['icharg'] == '2'
        assert not exists(join(directory, CHGCAR))
        assert not exists(join(directory, WAVECAR))

        # now copy only CHGCAR
        with open(join(restartdir, CHGCAR), 'w') as file:
            file.write('hello')
        a.restart = Extract(restartdir, True)
        assert o.output_map(vasp=a, outdir=directory)['icharg'] == '1'
        assert exists(join(directory, CHGCAR))
        assert not exists(join(directory, WAVECAR))
        remove(join(directory, CHGCAR))
        # now copy only CHGCAR with scf
        a.nonscf = True
        a.restart = Extract(restartdir, True)
        assert o.output_map(vasp=a, outdir=directory)['icharg'] == '11'
        assert exists(join(directory, CHGCAR))
        assert not exists(join(directory, WAVECAR))
        remove(join(directory, CHGCAR))

        # now copy both
        a.nonscf = False
        with open(join(restartdir, WAVECAR), 'w') as file:
            file.write('hello')
        a.restart = Extract(restartdir, True)
        assert o.output_map(vasp=a, outdir=directory)['icharg'] == '0'
        assert exists(join(directory, CHGCAR))
        assert exists(join(directory, WAVECAR))

        # now copy both with scf
        a.nonscf = True
        a.restart = Extract(restartdir, True)
        assert o.output_map(vasp=a, outdir=directory)['icharg'] == '10'
        assert exists(join(directory, CHGCAR))
        assert exists(join(directory, WAVECAR))

        # now check that latest is copied
        remove(join(restartdir, CHGCAR))
        remove(join(directory, CHGCAR))
        sleep(1.2)
        with open(join(directory, WAVECAR), 'w') as file:
            file.write('hello world')
        with open(join(directory, WAVECAR), 'r') as file:
            pass  # Buffering issues..
        a.nonscf = False
        a.restart = Extract(restartdir, True)
        assert o.output_map(vasp=a, outdir=directory)['icharg'] == '0'
        assert exists(join(directory, WAVECAR))
        with open(join(directory, WAVECAR), 'r') as file:
            assert file.read().rstrip().lstrip() == 'hello world'
        with open(join(directory, WAVECAR), 'r') as file:
            assert file.read().rstrip().lstrip() != 'hello'

        with open(join(restartdir, WAVECAR), 'w') as file:
            file.write('hello')
        assert o.output_map(vasp=a, outdir=directory)['icharg'] == '0'
        assert exists(join(directory, WAVECAR))
        with open(join(directory, WAVECAR), 'r') as file:
            assert file.read().rstrip().lstrip() == 'hello'
        with open(join(directory, WAVECAR), 'r') as file:
            assert file.read().rstrip().lstrip() != 'hello world'

        # makes sure requests are honored
        # tries request. Should fail since CHGCAR does not exist.
        remove(join(directory, WAVECAR))
        a.icharg = 'chgcar'
        assert a.icharg == 'chgcar'
        try:
            o.output_map(vasp=a, outdir=directory)
        except ValueError:
            pass
        else:
            raise Exception()
        # now try for gold.
        with open(join(restartdir, CHGCAR), 'w') as file:
            file.write('hello')
        assert o.output_map(vasp=a, outdir=directory)['icharg'] == '1'
        assert exists(join(directory, CHGCAR))
        assert not exists(join(directory, WAVECAR))
        assert eval(repr(o), d).value == 'chgcar'
        assert loads(dumps(o)).value == 'chgcar'

    finally:
        if directory not in ['/tmp/test', '/tmp/test/'] and exists(directory):
            rmtree(directory)
Exemplo n.º 45
0
def test_encut():
    from os.path import dirname
    from pickle import loads, dumps
    from quantities import eV, hartree
    import quantities
    import numpy
    from pylada.vasp import Vasp
    from pylada.crystal import Structure

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")
    a = Vasp()
    a.add_specie = "Si", "{0}/pseudos/Si".format(dirname(__file__))

    o = a._input['encut']
    d = {'Encut': o.__class__}
    d.update(quantities.__dict__)
    d.update(numpy.__dict__)
    assert a.ediff is None
    assert o.output_map() is None
    assert eval(repr(o), d).output_map() is None
    assert eval(repr(o), d).keyword == 'encut'
    assert loads(dumps(o)).output_map() is None

    a.encut = 1e0
    assert abs(a.encut - 1e0) < 1e-8
    assert abs(
        float(o.output_map(structure=structure, vasp=a)['encut']) -
        245.345) < 1e-8
    assert abs(
        float(
            eval(repr(o), d).output_map(structure=structure, vasp=a)['encut'])
        - 245.345) < 1e-8
    assert abs(
        float(
            loads(dumps(o)).output_map(structure=structure, vasp=a)['encut']) -
        245.345) < 1e-8
    assert abs(eval(repr(o), d).value - 1.0) < 1e-8
    assert abs(loads(dumps(o)).value - 1.0) < 1e-8
    a.encut = 0.8
    assert abs(a.encut - 0.8) < 1e-8
    assert abs(
        float(o.output_map(structure=structure, vasp=a)['encut']) -
        245.345 * 0.8) < 1e-8
    assert abs(
        float(
            eval(repr(o), d).output_map(structure=structure, vasp=a)['encut'])
        - 245.345 * 0.8) < 1e-8
    assert abs(
        float(
            loads(dumps(o)).output_map(structure=structure, vasp=a)['encut']) -
        245.345 * 0.8) < 1e-8
    assert abs(eval(repr(o), d).value - 0.8) < 1e-8
    assert abs(loads(dumps(o)).value - 0.8) < 1e-8
    a.encut = 200
    assert abs(a.encut - 200) < 1e-8
    assert abs(
        float(o.output_map(structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(
        float(
            eval(repr(o), d).output_map(structure=structure, vasp=a)['encut'])
        - 200) < 1e-8
    assert abs(
        float(
            loads(dumps(o)).output_map(structure=structure, vasp=a)['encut']) -
        200) < 1e-8
    assert abs(eval(repr(o), d).value - 200) < 1e-8
    assert abs(loads(dumps(o)).value - 200) < 1e-8
    a.encut = 200 * eV
    assert abs(a.encut - 200 * eV) < 1e-8
    assert a.encut.units == eV
    assert abs(
        float(o.output_map(structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(
        float(
            eval(repr(o), d).output_map(structure=structure, vasp=a)['encut'])
        - 200) < 1e-8
    assert abs(
        float(
            loads(dumps(o)).output_map(structure=structure, vasp=a)['encut']) -
        200) < 1e-8
    assert abs(eval(repr(o), d).value - 200 * eV) < 1e-8
    assert abs(loads(dumps(o)).value - 200 * eV) < 1e-8
    assert eval(repr(o), d).value.units == eV
    assert loads(dumps(o)).value.units == eV
    a.encut = (200 * eV).rescale(hartree)
    assert a.encut.units == hartree
    assert abs(a.encut - 200 * eV) < 1e-8
    assert abs(
        float(o.output_map(structure=structure, vasp=a)['encut']) - 200) < 1e-8
    assert abs(
        float(
            eval(repr(o), d).output_map(structure=structure, vasp=a)['encut'])
        - 200) < 1e-7
    assert abs(
        float(
            loads(dumps(o)).output_map(structure=structure, vasp=a)['encut']) -
        200) < 1e-8
    assert abs(eval(repr(o), d).value - 200 * eV) < 1e-8
    assert abs(loads(dumps(o)).value - 200 * eV) < 1e-8
    assert eval(repr(o), d).value.units == hartree
    assert loads(dumps(o)).value.units == hartree

    o = a._input['encutgw']
    d = {'EncutGW': o.__class__}
    d.update(quantities.__dict__)
    d.update(numpy.__dict__)
    assert a.ediff is None
    assert o.output_map() is None
    assert eval(repr(o), d).output_map() is None
    assert eval(repr(o), d).keyword == 'encutgw'
    assert loads(dumps(o)).output_map() is None
    a.encutgw = (200 * eV).rescale(hartree)
    assert a.encutgw.units == hartree
    assert abs(a.encutgw - 200 * eV) < 1e-8
    assert abs(
        float(o.output_map(structure=structure, vasp=a)['encutgw']) -
        200) < 1e-8
    assert abs(
        float(
            eval(repr(o), d).output_map(structure=structure, vasp=a)
            ['encutgw']) - 200) < 1e-7
    assert abs(
        float(
            loads(dumps(o)).output_map(structure=structure, vasp=a)['encutgw'])
        - 200) < 1e-8
    assert abs(eval(repr(o), d).value - 200 * eV) < 1e-6
    assert abs(loads(dumps(o)).value - 200 * eV) < 1e-8
    assert eval(repr(o), d).value.units == hartree
    assert loads(dumps(o)).value.units == hartree
Exemplo n.º 46
0
def test_istart():
  from time import sleep
  from collections import namedtuple
  from pickle import loads, dumps
  from os import remove, makedirs
  from os.path import join, exists
  from shutil import rmtree
  from tempfile import mkdtemp
  from pylada.vasp.files import WAVECAR
  from pylada.vasp import Vasp
  from pylada.misc import Changedir

  Extract = namedtuple("Extract", ['directory', 'success'])
  a = Vasp()
  o = a._input['istart']
  d = {'IStart': o.__class__}

  directory = mkdtemp()
  if directory in ['/tmp/test', '/tmp/test/']:
    if exists(directory): rmtree(directory)
    makedirs(directory)
  try: 
    assert a.istart == 'auto'
    assert o.output_map(vasp=a, outdir=directory)['istart'] == '0'
    assert eval(repr(o), d).value == 'auto'
    assert loads(dumps(o)).value == 'auto'

    restartdir = join(directory, 'restart')
    with Changedir(restartdir) as pwd: pass
    with open(join(restartdir, WAVECAR), 'w') as file: file.write('hello')

    # do not copy if not successful
    a.restart = Extract(restartdir, False)
    assert o.output_map(vasp=a, outdir=directory)['istart'] == '0'
    assert not exists(join(directory, 'WAVECAR'))

    # do not copy if file is empty
    a.restart = Extract(restartdir, True)
    with open(join(restartdir, WAVECAR), 'w') as file: pass
    assert o.output_map(vasp=a, outdir=directory)['istart'] == '0'
    assert not exists(join(directory, 'WAVECAR'))

    # now should copy
    assert a.istart == 'auto'
    with open(join(restartdir, WAVECAR), 'w') as file: file.write('hello')
    assert o.output_map(vasp=a, outdir=directory)['istart'] == '1'
    assert exists(join(directory, 'WAVECAR'))
      
    # check it copies only latest file.
    with open(join(restartdir, WAVECAR), 'w') as file: 
      file.write('hello')
      file.flush()
    with open(join(restartdir, WAVECAR), 'r') as file: pass
    sleep(1.5)
    with open(join(directory, WAVECAR), 'w') as file: file.write('hello world')
    with open(join(directory, WAVECAR), 'r') as file: pass
    assert o.output_map(vasp=a, outdir=directory)['istart'] == '1'
    assert exists(join(directory, 'WAVECAR'))
    with open(join(directory, WAVECAR), 'r') as file: 
      assert file.read().rstrip().lstrip() == 'hello world'
    
    sleep(0.2)
    with open(join(restartdir, WAVECAR), 'w') as file: file.write('hello')
    assert o.output_map(vasp=a, outdir=directory)['istart'] == '1'
    assert exists(join(directory, 'WAVECAR'))
    with open(join(directory, WAVECAR), 'r') as file: 
      assert file.read().rstrip().lstrip() == 'hello'

    # check if scratch is required
    remove(join(directory, WAVECAR))
    a.istart = 'scratch'
    assert a.istart == 'scratch'
    assert o.output_map(vasp=a, outdir=directory)['istart'] == '0'
    assert eval(repr(o), d).value == 'scratch'
    assert loads(dumps(o)).value == 'scratch'

  finally: 
    if directory not in ['/tmp/test', '/tmp/test/'] and exists(directory):
      rmtree(directory)
Exemplo n.º 47
0
def test(path):
  from shutil import rmtree
  from tempfile import mkdtemp
  from os.path import join
  from quantities import eV
  from pylada.vasp import Vasp, read_incar
  from pylada.crystal import Structure
  structure = Structure([[0, 0.5, 0.5],[0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
                       .add_atom(0,0,0, "Si")\
                       .add_atom(0.25,0.25,0.25, "Si")

  vasp = Vasp()
  vasp.kpoints    = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
  vasp.precision  = "accurate"
  vasp.ediff      = 1e-5
  vasp.encut      = 1
  vasp.ismear     = "metal"
  vasp.sigma      = 0.06
  vasp.relaxation = "volume"
  vasp.add_specie = "Si", "{0}/pseudos/Si".format(path)

  directory = mkdtemp()
  try: 
    vasp.write_incar(path=join(directory, 'INCAR'), structure=structure)
    other = read_incar(join(directory, 'INCAR'))
    assert abs(other.ediff - 1e-5)  < 1e-8
    assert abs(other.encut - 245.345) < 1e-8
    assert abs(other.sigma - 0.06 * eV) < 1e-8
    assert other.ibrion     == 2
    assert other.icharg     == 'atomic'
    assert other.isif       == 7
    assert other.ismear     == 'metal'
    assert other.istart     == 'scratch'
    assert other.lcharg     == False
    assert other.nsw        == 50
    assert other.relaxation == 'volume'
    assert other.system     == 'has a name'
    with open(join(directory, 'INCAR'), 'a') as file:
      file.write('\nSOMETHing = 0.5\n')
    other = read_incar(join(directory, 'INCAR'))
    assert abs(other.ediff - 1e-5)  < 1e-8
    assert abs(other.encut - 245.345) < 1e-8
    assert abs(other.sigma - 0.06 * eV) < 1e-8
    assert other.ibrion     == 2
    assert other.icharg     == 'atomic'
    assert other.isif       == 7
    assert other.ismear     == 'metal'
    assert other.istart     == 'scratch'
    assert other.lcharg     == False
    assert other.nsw        == 50
    assert other.relaxation == 'volume'
    assert other.system     == 'has a name'
    assert 'something' in other._input
    assert isinstance(other.something, float)
    assert abs(other.something - 0.5) < 1e-8
  finally: 
    rmtree(directory)
    pass
Exemplo n.º 48
0
def test_istart():
    from time import sleep
    from collections import namedtuple
    from pickle import loads, dumps
    from os import remove, makedirs
    from os.path import join, exists
    from shutil import rmtree
    from tempfile import mkdtemp
    from pylada.vasp.files import WAVECAR
    from pylada.vasp import Vasp
    from pylada.misc import local_path

    Extract = namedtuple("Extract", ['directory', 'success'])
    a = Vasp()
    o = a._input['istart']
    d = {'IStart': o.__class__}

    directory = mkdtemp()
    if directory in ['/tmp/test', '/tmp/test/']:
        if exists(directory):
            rmtree(directory)
        makedirs(directory)
    try:
        assert a.istart == 'auto'
        assert o.output_map(vasp=a, outdir=directory)['istart'] == '0'
        assert eval(repr(o), d).value == 'auto'
        assert loads(dumps(o)).value == 'auto'

        restartdir = join(directory, 'restart')
        local_path(restartdir).ensure(dir=True)
        with open(join(restartdir, WAVECAR), 'w') as file:
            file.write('hello')

        # do not copy if not successful
        a.restart = Extract(restartdir, False)
        assert o.output_map(vasp=a, outdir=directory)['istart'] == '0'
        assert not exists(join(directory, 'WAVECAR'))

        # do not copy if file is empty
        a.restart = Extract(restartdir, True)
        with open(join(restartdir, WAVECAR), 'w') as file:
            pass
        assert o.output_map(vasp=a, outdir=directory)['istart'] == '0'
        assert not exists(join(directory, 'WAVECAR'))

        # now should copy
        assert a.istart == 'auto'
        with open(join(restartdir, WAVECAR), 'w') as file:
            file.write('hello')
        assert o.output_map(vasp=a, outdir=directory)['istart'] == '1'
        assert exists(join(directory, 'WAVECAR'))

        # check it copies only latest file.
        with open(join(restartdir, WAVECAR), 'w') as file:
            file.write('hello')
            file.flush()
        with open(join(restartdir, WAVECAR), 'r') as file:
            pass
        sleep(1.5)
        with open(join(directory, WAVECAR), 'w') as file:
            file.write('hello world')
        with open(join(directory, WAVECAR), 'r') as file:
            pass
        assert o.output_map(vasp=a, outdir=directory)['istart'] == '1'
        assert exists(join(directory, 'WAVECAR'))
        with open(join(directory, WAVECAR), 'r') as file:
            assert file.read().rstrip().lstrip() == 'hello world'

        sleep(0.2)
        with open(join(restartdir, WAVECAR), 'w') as file:
            file.write('hello')
        assert o.output_map(vasp=a, outdir=directory)['istart'] == '1'
        assert exists(join(directory, 'WAVECAR'))
        with open(join(directory, WAVECAR), 'r') as file:
            assert file.read().rstrip().lstrip() == 'hello'

        # check if scratch is required
        remove(join(directory, WAVECAR))
        a.istart = 'scratch'
        assert a.istart == 'scratch'
        assert o.output_map(vasp=a, outdir=directory)['istart'] == '0'
        assert eval(repr(o), d).value == 'scratch'
        assert loads(dumps(o)).value == 'scratch'

    finally:
        if directory not in ['/tmp/test', '/tmp/test/'] and exists(directory):
            rmtree(directory)
Exemplo n.º 49
0
def test():
    from pickle import loads, dumps
    from pylada.vasp import Vasp
    import pylada

    pylada.is_vasp_4 = True
    a = Vasp()

    # default.
    assert a.algo == 'Fast'
    # wrong argument.
    try:
        a.algo = 0
    except:
        pass
    else:
        raise RuntimeError()
    try:
        a.algo = "WTF"
    except:
        pass
    else:
        raise RuntimeError()

    # possible inputs and some.
    d = {
        'Very_Fast': ['very fast', 'VERY-fAst', 'very_FAST', 'v'],
        'VeryFast': ['very fast', 'VERY-fAst', 'very_FAST', 'v'],
        'Fast': ['fast', 'f'],
        'Normal': ['normal', 'n'],
        'Damped': ['damped', 'd'],
        'Diag': ['diag'],
        'All': ['all', 'a'],
        'Nothing': ['nothing'],
        'chi': ['chi'],
        'GW': ['gw'],
        'GW0': ['gw0'],
        'scGW': ['scgw'],
        'scGW0': ['scgw0'],
        'Conjugate': ['conjugate', 'c'],
        'Subrot': ['subrot', 's'],
        'Eigenval': ['eigenval', 'e']
    }
    vasp5 = 'Subrot', 'chi', 'GW', 'GW0', 'scGW', 'scGW0', 'Conjugate', 'Eigenval', 'Exact', 'Nothing'
    dictionary = {'Algo': a._input['algo'].__class__}
    for isvasp4 in [True, False]:
        pylada.is_vasp_4 = isvasp4
        for key, items in d.iteritems():
            for value in items:
                if key in vasp5 and isvasp4:
                    try:
                        a.algo = value
                    except:
                        pass
                    else:
                        raise RuntimeError((value, key))
                    continue
                a.algo = value
                o = a._input['algo']
                if key == 'VeryFast' and isvasp4:
                    assert a.algo == 'Very_Fast'
                    assert o.output_map()['algo'] == 'Very_Fast'
                    assert loads(dumps(o)).output_map()["algo"] == 'Very_Fast'
                    assert eval(repr(o),
                                dictionary).output_map()["algo"] == 'Very_Fast'
                elif key == 'Very_Fast' and not isvasp4:
                    assert a.algo == 'VeryFast'
                    assert o.output_map()['algo'] == 'VeryFast'
                    assert loads(dumps(o)).output_map()["algo"] == 'VeryFast'
                    assert eval(repr(o),
                                dictionary).output_map()["algo"] == 'VeryFast'
                else:
                    assert a.algo == key
                    assert o.output_map()['algo'] == key
                    assert loads(dumps(o)).output_map()["algo"] == key
                    assert eval(repr(o),
                                dictionary).output_map()["algo"] == key

    a.algo = None
    assert a.algo is None
    assert o.output_map() is None
    assert loads(dumps(o)).output_map() is None
    assert eval(repr(o), dictionary).output_map() is None
Exemplo n.º 50
0
    n1=int(round(b1/step))
    if np.mod(n1,2)!=0: n1=n1-1
    n2=int(round(b2/step))
    if np.mod(n2,2)!=0: n2=n2-1
    n3=int(round(b3/step))
    if np.mod(n3,2)!=0: n3=n3-1
    print n1,n2,n3

    if n1==0:n1=1
    if n2==0:n2=1
    if n3==0:n3=1

    return "\n0\nGamma\n%2i %2i %2i\n 0. 0. 0.\n" %(n1,n2,n3)

############### setting up the functional
vasp=Vasp()

vasp.program = '/home/vstevano/bin/vasp'

pseudoDir = '/home/vstevano/software/pseudos'
vasp.add_specie = "In", pseudoDir + "/In"
vasp.add_specie = "O", pseudoDir + "/O"

vasp.prec       = "accurate"
vasp.encut      = 340.
vasp.ismear     = 0
vasp.sigma      = 0.05
vasp.ediff      = 1.0e-6
vasp.ediffg     = -0.01
vasp.convergence= 1.0e-6
vasp.nsw        = 1
Exemplo n.º 51
0
def test_icharg(): 
  from time import sleep
  from collections import namedtuple
  from pickle import loads, dumps
  from os import remove, makedirs
  from os.path import join, exists
  from shutil import rmtree
  from tempfile import mkdtemp
  from pylada.vasp.files import WAVECAR, CHGCAR
  from pylada.vasp import Vasp
  from pylada.misc import Changedir
  from pylada.error import ValueError

  Extract = namedtuple("Extract", ['directory', 'success'])
  a = Vasp()
  o = a._input['icharg']
  d = {'ICharg': o.__class__}

  directory = mkdtemp()
  if directory in ['/tmp/test', '/tmp/test/']:
    if exists(directory): rmtree(directory)
    makedirs(directory)
  try: 
    assert a.icharg == 'auto'
    assert o.output_map(vasp=a, outdir=directory)['icharg'] == '2'
    assert eval(repr(o), d).value == 'auto'
    assert loads(dumps(o)).value == 'auto'

    restartdir = join(directory, 'restart')
    with Changedir(restartdir) as pwd: pass
    with open(join(restartdir, CHGCAR), 'w') as file: file.write('hello')
    with open(join(restartdir, WAVECAR), 'w') as file: file.write('hello')

    # do not copy if not successful
    a.restart = Extract(restartdir, False)
    assert o.output_map(vasp=a, outdir=directory)['icharg'] == '2'
    assert not exists(join(directory, CHGCAR))
    assert not exists(join(directory, WAVECAR))

    # do not copy if empty
    with open(join(restartdir, CHGCAR), 'w') as file: pass
    with open(join(restartdir, WAVECAR), 'w') as file: pass
    a.restart = Extract(restartdir, True)
    assert o.output_map(vasp=a, outdir=directory)['icharg'] == '2'
    assert not exists(join(directory, CHGCAR))
    assert not exists(join(directory, WAVECAR))

    # now copy only CHGCAR
    with open(join(restartdir, CHGCAR), 'w') as file: file.write('hello')
    a.restart = Extract(restartdir, True)
    assert o.output_map(vasp=a, outdir=directory)['icharg'] == '1'
    assert exists(join(directory, CHGCAR))
    assert not exists(join(directory, WAVECAR))
    remove(join(directory, CHGCAR))
    # now copy only CHGCAR with scf
    a.nonscf = True
    a.restart = Extract(restartdir, True)
    assert o.output_map(vasp=a, outdir=directory)['icharg'] == '11'
    assert exists(join(directory, CHGCAR))
    assert not exists(join(directory, WAVECAR))
    remove(join(directory, CHGCAR))

    # now copy both 
    a.nonscf = False
    with open(join(restartdir, WAVECAR), 'w') as file: file.write('hello')
    a.restart = Extract(restartdir, True)
    assert o.output_map(vasp=a, outdir=directory)['icharg'] == '0'
    assert exists(join(directory, CHGCAR))
    assert exists(join(directory, WAVECAR))

    # now copy both with scf
    a.nonscf = True
    a.restart = Extract(restartdir, True)
    assert o.output_map(vasp=a, outdir=directory)['icharg'] == '10'
    assert exists(join(directory, CHGCAR))
    assert exists(join(directory, WAVECAR))

    # now check that latest is copied
    remove(join(restartdir, CHGCAR))
    remove(join(directory, CHGCAR))
    sleep(1.2)
    with open(join(directory, WAVECAR), 'w') as file: file.write('hello world')
    with open(join(directory, WAVECAR), 'r') as file: pass # Buffering issues..
    a.nonscf = False
    a.restart = Extract(restartdir, True)
    assert o.output_map(vasp=a, outdir=directory)['icharg'] == '0'
    assert exists(join(directory, WAVECAR))
    with open(join(directory, WAVECAR), 'r') as file:
      assert file.read().rstrip().lstrip() == 'hello world'
    with open(join(directory, WAVECAR), 'r') as file:
      assert file.read().rstrip().lstrip() != 'hello'

    with open(join(restartdir, WAVECAR), 'w') as file: file.write('hello')
    assert o.output_map(vasp=a, outdir=directory)['icharg'] == '0'
    assert exists(join(directory, WAVECAR))
    with open(join(directory, WAVECAR), 'r') as file:
      assert file.read().rstrip().lstrip() == 'hello'
    with open(join(directory, WAVECAR), 'r') as file:
      assert file.read().rstrip().lstrip() != 'hello world'

    # makes sure requests are honored
    # tries request. Should fail since CHGCAR does not exist.
    remove(join(directory, WAVECAR))
    a.icharg = 'chgcar'
    assert a.icharg == 'chgcar'
    try: o.output_map(vasp=a, outdir=directory)
    except ValueError: pass
    else: raise Exception()
    # now try for gold.
    with open(join(restartdir, CHGCAR), 'w') as file: file.write('hello')
    assert o.output_map(vasp=a, outdir=directory)['icharg'] == '1'
    assert exists(join(directory, CHGCAR))
    assert not exists(join(directory, WAVECAR))
    assert eval(repr(o), d).value == 'chgcar'
    assert loads(dumps(o)).value == 'chgcar'

  finally: 
    if directory not in ['/tmp/test', '/tmp/test/'] and exists(directory):
      rmtree(directory)
Exemplo n.º 52
0
def test_magmom():
    from pickle import loads, dumps
    from pylada.crystal.cppwrappers import Structure
    from pylada.vasp import Vasp

    u = 0.25
    x, y = u, 0.25 - u
    structure = Structure([[0,0.5,0.5],[0.5,0,0.5],[0.5,0.5,0]]) \
                         .add_atom(5.000000e-01, 5.000000e-01, 5.000000e-01, "Mg") \
                         .add_atom(5.000000e-01, 2.500000e-01, 2.500000e-01, "Mg") \
                         .add_atom(2.500000e-01, 5.000000e-01, 2.500000e-01, "Mg") \
                         .add_atom(2.500000e-01, 2.500000e-01, 5.000000e-01, "Mg") \
                         .add_atom(8.750000e-01, 8.750000e-01, 8.750000e-01, "Al") \
                         .add_atom(1.250000e-01, 1.250000e-01, 1.250000e-01, "Al") \
                         .add_atom(     x,     x,     x, "O") \
                         .add_atom(     x,     y,     y, "O") \
                         .add_atom(     y,     x,     y, "O") \
                         .add_atom(     y,     y,     x, "O") \
                         .add_atom(    -x,    -x,    -x, "O") \
                         .add_atom(    -x,    -y,    -y, "O") \
                         .add_atom(    -y,    -x,    -y, "O") \
                         .add_atom(    -y,    -y,    -x, "O")

    for atom in structure:
        if atom.type == 'Mg': atom.magmom = -1e0

    vasp = Vasp()
    vasp.magmom = None
    assert vasp.magmom is None
    assert vasp._input['magmom'].keyword == 'MAGMOM'
    assert vasp._input['magmom'].output_map(vasp=vasp,
                                            structure=structure) is None

    # ispin == 1
    vasp.magmom = True
    vasp.ispin = 1
    assert vasp._input['magmom'].output_map(vasp=vasp,
                                            structure=structure) is None
    # ispins == 2, magmom == False
    vasp.ispin = 2
    vasp.magmom = None
    assert vasp._input['magmom'].output_map(vasp=vasp,
                                            structure=structure) is None
    vasp.magmom = False
    assert vasp._input['magmom'].output_map(vasp=vasp,
                                            structure=structure) is None
    # now for real print
    vasp.magmom = True
    assert 'MAGMOM' in vasp._input['magmom'].output_map(vasp=vasp,
                                                        structure=structure)
    print vasp._input['magmom'].output_map(vasp=vasp,
                                           structure=structure)['MAGMOM']
    assert vasp._input['magmom'].output_map(
        vasp=vasp, structure=structure)['MAGMOM'] == '4*-1.0 2*0.0 8*0.0'
    # now print a string directly.
    vasp.magmom = 'hello'
    assert vasp.magmom == 'hello'
    assert 'MAGMOM' in vasp._input['magmom'].output_map(vasp=vasp,
                                                        structure=structure)
    assert vasp._input['magmom'].output_map(
        vasp=vasp, structure=structure)['MAGMOM'] == 'hello'

    # check repr
    assert repr(vasp._input['magmom']) == "Magmom(value='hello')"
    # check pickling
    assert repr(loads(dumps(vasp._input['magmom']))) == "Magmom(value='hello')"

    # more tests.
    for atom, mag in zip(structure, [1, -1, 1, 1]):
        if atom.type == 'Mg': atom.magmom = mag
    for atom, mag in zip(structure, [0.5, 0.5]):
        if atom.type == 'Al': atom.magmom = mag

    vasp.magmom = True
    assert 'MAGMOM' in vasp._input['magmom'].output_map(vasp=vasp,
                                                        structure=structure)
    assert vasp._input['magmom'].output_map(
        vasp=vasp,
        structure=structure)['MAGMOM'] == '1.0 -1.0 2*1.0 2*0.0 8*0.0'
Exemplo n.º 53
0
def test_istruc():
  from collections import namedtuple
  from pickle import loads, dumps
  from os import remove
  from os.path import join, exists
  from shutil import rmtree
  from tempfile import mkdtemp
  from pylada.vasp.files import POSCAR, CONTCAR
  from pylada.vasp import Vasp
  from pylada.crystal import Structure, read, specieset, write
  from pylada.error import ValueError

  structure = Structure([[0, 0.5, 0.5],[0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
                       .add_atom(0,0,0, "Si")\
                       .add_atom(0.25,0.25,0.25, "Si")

  Extract = namedtuple("Extract", ['directory', 'success', 'structure'])
  a = Vasp()
  o = a._input['istruc']
  d = {'IStruc': o.__class__}

  directory = mkdtemp()
  try: 
    assert a.istruc == 'auto'
    assert o.output_map(vasp=a, outdir=directory, structure=structure) is None
    assert eval(repr(o), d).value == 'auto'
    assert loads(dumps(o)).value == 'auto'
    assert exists(join(directory, POSCAR))
    remove(join(directory, POSCAR))

    # check reading from outcar but only on success.
    a.restart = Extract(directory, False, structure.copy())
    a.restart.structure[1].pos[0] += 0.02
    assert a.istruc == 'auto'
    assert o.output_map(vasp=a, outdir=directory, structure=structure) is None
    assert exists(join(directory, POSCAR))
    other = read.poscar(join(directory, POSCAR), types=specieset(structure))
    assert abs(other[1].pos[0] - 0.25) < 1e-8
    assert abs(other[1].pos[0] - 0.27) > 1e-8
    # check reading from outcar but only on success.
    a.restart = Extract(directory, True, structure.copy())
    a.restart.structure[1].pos[0] += 0.02
    assert a.istruc == 'auto'
    assert o.output_map(vasp=a, outdir=directory, structure=structure) is None
    assert exists(join(directory, POSCAR))
    other = read.poscar(join(directory, POSCAR), types=specieset(structure))
    assert abs(other[1].pos[0] - 0.25) > 1e-8
    assert abs(other[1].pos[0] - 0.27) < 1e-8

    # Now check CONTCAR
    write.poscar(structure, join(directory, CONTCAR))
    assert a.istruc == 'auto'
    assert o.output_map(vasp=a, outdir=directory, structure=structure) is None
    assert exists(join(directory, POSCAR))
    other = read.poscar(join(directory, POSCAR), types=specieset(structure))
    assert abs(other[1].pos[0] - 0.25) < 1e-8
    assert abs(other[1].pos[0] - 0.27) > 1e-8

    # Check some failure modes.
    write.poscar(structure, join(directory, CONTCAR))
    structure[0].type = 'Ge'
    a.restart = None
    try: o.output_map(vasp=a, outdir=directory, structure=structure)
    except ValueError: pass
    else: raise Exception()
    structure[0].type = 'Si'
    structure.add_atom(0.25,0,0, 'Si')
    try: o.output_map(vasp=a, outdir=directory, structure=structure)
    except ValueError: pass
    else: raise Exception()

  finally: rmtree(directory)
Exemplo n.º 54
0
def test_istart():
    from time import sleep
    from collections import namedtuple
    from pickle import loads, dumps
    from os import remove, makedirs
    from os.path import join, exists
    from shutil import rmtree
    from tempfile import mkdtemp
    from pylada.vasp.files import WAVECAR
    from pylada.vasp import Vasp
    from pylada.misc import Changedir

    Extract = namedtuple("Extract", ["directory", "success"])
    a = Vasp()
    o = a._input["istart"]
    d = {"IStart": o.__class__}

    directory = mkdtemp()
    if directory in ["/tmp/test", "/tmp/test/"]:
        if exists(directory):
            rmtree(directory)
        makedirs(directory)
    try:
        assert a.istart == "auto"
        assert o.output_map(vasp=a, outdir=directory)["istart"] == "0"
        assert eval(repr(o), d).value == "auto"
        assert loads(dumps(o)).value == "auto"

        restartdir = join(directory, "restart")
        with Changedir(restartdir) as pwd:
            pass
        with open(join(restartdir, WAVECAR), "w") as file:
            file.write("hello")

        # do not copy if not successful
        a.restart = Extract(restartdir, False)
        assert o.output_map(vasp=a, outdir=directory)["istart"] == "0"
        assert not exists(join(directory, "WAVECAR"))

        # do not copy if file is empty
        a.restart = Extract(restartdir, True)
        with open(join(restartdir, WAVECAR), "w") as file:
            pass
        assert o.output_map(vasp=a, outdir=directory)["istart"] == "0"
        assert not exists(join(directory, "WAVECAR"))

        # now should copy
        assert a.istart == "auto"
        with open(join(restartdir, WAVECAR), "w") as file:
            file.write("hello")
        assert o.output_map(vasp=a, outdir=directory)["istart"] == "1"
        assert exists(join(directory, "WAVECAR"))

        # check it copies only latest file.
        with open(join(restartdir, WAVECAR), "w") as file:
            file.write("hello")
            file.flush()
        with open(join(restartdir, WAVECAR), "r") as file:
            pass
        sleep(1.5)
        with open(join(directory, WAVECAR), "w") as file:
            file.write("hello world")
        with open(join(directory, WAVECAR), "r") as file:
            pass
        assert o.output_map(vasp=a, outdir=directory)["istart"] == "1"
        assert exists(join(directory, "WAVECAR"))
        with open(join(directory, WAVECAR), "r") as file:
            assert file.read().rstrip().lstrip() == "hello world"

        sleep(0.2)
        with open(join(restartdir, WAVECAR), "w") as file:
            file.write("hello")
        assert o.output_map(vasp=a, outdir=directory)["istart"] == "1"
        assert exists(join(directory, "WAVECAR"))
        with open(join(directory, WAVECAR), "r") as file:
            assert file.read().rstrip().lstrip() == "hello"

        # check if scratch is required
        remove(join(directory, WAVECAR))
        a.istart = "scratch"
        assert a.istart == "scratch"
        assert o.output_map(vasp=a, outdir=directory)["istart"] == "0"
        assert eval(repr(o), d).value == "scratch"
        assert loads(dumps(o)).value == "scratch"

    finally:
        if directory not in ["/tmp/test", "/tmp/test/"] and exists(directory):
            rmtree(directory)
Exemplo n.º 55
0
def test_algo_keyword():
    from pickle import loads, dumps
    from pylada.vasp import Vasp
    import pylada

    pylada.is_vasp_4 = True
    a = Vasp()

    # default.
    assert a.algo == 'Fast'
    # wrong argument.
    try:
        a.algo = 0
    except:
        pass
    else:
        raise RuntimeError()
    try:
        a.algo = "WTF"
    except:
        pass
    else:
        raise RuntimeError()

    # possible inputs and some.
    d = {
        'Very_Fast': ['very fast', 'VERY-fAst', 'very_FAST', 'v'],
        'VeryFast': ['very fast', 'VERY-fAst', 'very_FAST', 'v'],
        'Fast': ['fast', 'f'],
        'Normal': ['normal', 'n'],
        'Damped': ['damped', 'd'],
        'Diag': ['diag'],
        'All': ['all', 'a'],
        'None': ['none'],
        'Nothing': ['nothing'],
        'chi': ['chi'],
        'GW': ['gw'],
        'GW0': ['gw0'],
        'scGW': ['scgw'],
        'scGW0': ['scgw0'],
        'Conjugate': ['conjugate', 'c'],
        'Subrot': ['subrot', 's'],
        'Eigenval': ['eigenval', 'e']
    }
    vasp5 = 'Subrot', 'chi', 'GW', 'GW0', 'scGW', 'scGW0', 'Conjugate', 'Eigenval', 'Exact', 'Nothing'
    dictionary = {'Algo': a._input['algo'].__class__}
    for isvasp4 in [True, False]:
        pylada.is_vasp_4 = isvasp4
        for key, items in d.items():
            for value in items:
                if key in vasp5 and isvasp4:
                    try:
                        a.algo = value
                    except:
                        pass
                    else:
                        raise RuntimeError((value, key))
                    continue
                a.algo = value
                o = a._input['algo']
                if key == 'VeryFast' and isvasp4:
                    assert a.algo == 'Very_Fast'
                    assert o.output_map()['algo'] == 'Very_Fast'
                    assert loads(dumps(o)).output_map()["algo"] == 'Very_Fast'
                    assert eval(repr(o), dictionary).output_map()["algo"] == 'Very_Fast'
                elif key == 'Very_Fast' and not isvasp4:
                    assert a.algo == 'VeryFast'
                    assert o.output_map()['algo'] == 'VeryFast'
                    assert loads(dumps(o)).output_map()["algo"] == 'VeryFast'
                    assert eval(repr(o), dictionary).output_map()["algo"] == 'VeryFast'
                else:
                    assert a.algo == key
                    assert o.output_map()['algo'] == key
                    assert loads(dumps(o)).output_map()["algo"] == key
                    assert eval(repr(o), dictionary).output_map()["algo"] == key

    a.algo = None
    assert a.algo is None
    assert o.output_map() is None
    assert loads(dumps(o)).output_map() is None
    assert eval(repr(o), dictionary).output_map() is None
Exemplo n.º 56
0
def test_incar():
  from shutil import rmtree
  from tempfile import mkdtemp
  from os.path import join, dirname
  from quantities import eV
  from pylada.vasp import Vasp, read_incar
  from pylada.crystal import Structure
  structure = Structure([[0, 0.5, 0.5],[0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
                       .add_atom(0,0,0, "Si")\
                       .add_atom(0.25,0.25,0.25, "Si")

  vasp = Vasp()
  vasp.kpoints    = "Automatic generation\n0\nMonkhorst\n2 2 2\n0 0 0"
  vasp.precision  = "accurate"
  vasp.ediff      = 1e-5
  vasp.encut      = 1
  vasp.ismear     = "metal"
  vasp.sigma      = 0.06
  vasp.relaxation = "volume"
  vasp.add_specie = "Si", join(dirname(__file__), 'pseudos', 'Si')

  directory = mkdtemp()
  try: 
    vasp.write_incar(path=join(directory, 'INCAR'), structure=structure)
    other = read_incar(join(directory, 'INCAR'))
    assert abs(other.ediff - 1e-5)  < 1e-8
    assert abs(other.encut - 245.345) < 1e-8
    assert abs(other.sigma - 0.06 * eV) < 1e-8
    assert other.ibrion     == 2
    assert other.icharg     == 'atomic'
    assert other.isif       == 7
    assert other.ismear     == 'metal'
    assert other.istart     == 'scratch'
    assert other.lcharg     == False
    assert other.nsw        == 50
    assert other.relaxation == 'volume'
    assert other.system     == 'has a name'
    with open(join(directory, 'INCAR'), 'a') as file:
      file.write('\nSOMETHing = 0.5\n')
    other = read_incar(join(directory, 'INCAR'))
    assert abs(other.ediff - 1e-5)  < 1e-8
    assert abs(other.encut - 245.345) < 1e-8
    assert abs(other.sigma - 0.06 * eV) < 1e-8
    assert other.ibrion     == 2
    assert other.icharg     == 'atomic'
    assert other.isif       == 7
    assert other.ismear     == 'metal'
    assert other.istart     == 'scratch'
    assert other.lcharg     == False
    assert other.nsw        == 50
    assert other.relaxation == 'volume'
    assert other.system     == 'has a name'
    assert 'something' in other._input
    assert isinstance(other.something, float)
    assert abs(other.something - 0.5) < 1e-8
  finally: 
    rmtree(directory)
    pass