Beispiel #1
0
    def __init__(self, executable=None, verbose=0):

        self.executable = executable
        if executable is None:
            self.executable = pj(abipy_env.bindir, self._name)

        self.executable = which(self.executable)

        if self.executable is None:
            raise self.Error("%s is not executable" % self.executable)
        assert basename(self.executable) == self._name

        self.verbose = int(verbose)
Beispiel #2
0
    def __init__(self, executable, verbose=0):
        """
        Args:
            executable:
                path to the executable.
            verbose:
                Verbosity level
        """
        if executable is None: executable = self.name

        self.executable = which(executable)

        self.verbose = int(verbose)

        if self.executable is None:
            msg = "Cannot find executable %s is PATH\n Use export PATH=/dir_with_exec:$PATH" % executable
            raise self.Error(msg)

        assert os.path.basename(self.executable) == self._name
Beispiel #3
0
    def __init__(self, executable, verbose=0):
        """
        Args:
            executable:
                path to the executable.
            verbose:
                Verbosity level.
        """
        if executable is None: executable = self.name

        self.executable = which(executable)

        self.verbose = int(verbose)

        if self.executable is None:
            msg = "Cannot find executable %s is PATH\n Use export PATH=/dir_with_exec:$PATH" % executable
            raise self.Error(msg)

        assert os.path.basename(self.executable) == self._name
Beispiel #4
0
import numpy as np
import warnings

from pymatgen.io.vaspio.vasp_input import Poscar
from pymatgen.core.sites import PeriodicSite
from pymatgen.core.structure import Structure
from pymatgen.symmetry.finder import SymmetryFinder
from pymatgen.core.periodic_table import DummySpecie
from pymatgen.util.io_utils import which
from pymatgen.util.decorators import requires

logger = logging.getLogger(__name__)


@requires(which('multienum.x') and which('makestr.x'),
          "EnumlibAdaptor requires the executables 'multienum.x' and "
          "'makestr.x' to be in the path. Please download the library at"
          "http://enum.sourceforge.net/ and follow the instructions in "
          "the README to compile these two executables accordingly.")
class EnumlibAdaptor(object):
    """
    An adaptor for enumlib.

    .. attribute:: structures

        List of all enumerated structures.
    """
    amount_tol = 1e-5

    def __init__(self, structure, min_cell_size=1, max_cell_size=1,
Beispiel #5
0
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "*****@*****.**"
__date__ = "Jul 22, 2012"

import unittest
import os

from pymatgen.command_line.bader_caller import BaderAnalysis
from pymatgen.util.io_utils import which


@unittest.skipIf(not which('bader'), "bader executable not present.")
class BaderAnalysisTest(unittest.TestCase):

    def test_init(self):
        test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                                'test_files')
        analysis = BaderAnalysis(os.path.join(test_dir, "CHGCAR.Fe3O4"),
                                 os.path.join(test_dir, "POTCAR.Fe3O4"))
        self.assertEqual(len(analysis.data), 14)
        self.assertAlmostEqual(analysis.data[0]["charge"], 6.1485)
        self.assertAlmostEqual(analysis.nelectrons, 96)
        self.assertAlmostEqual(analysis.vacuum_charge, 0)
        ans = [-1.8515, -1.8132, -1.8132, -1.5562, -1.8132, -1.8515, 1.3369,
               1.3378, 1.3373, 1.3374, 1.3374, 1.3369, 1.3373, 1.3378]
        for i in range(14):
            self.assertAlmostEqual(ans[i], analysis.get_charge_transfer(i))
Beispiel #6
0
__email__ = "*****@*****.**"
__date__ = "Jul 22, 2012"

import unittest
import os

from pymatgen.command_line.enumlib_caller import EnumlibAdaptor
from pymatgen import Element, Structure
from pymatgen.io.cifio import CifParser
from pymatgen.transformations.standard_transformations import \
    SubstitutionTransformation
from pymatgen.util.io_utils import which
from pymatgen.transformations.site_transformations import \
    RemoveSitesTransformation

enumlib_present = which('multienum.x') and which('makestr.x')


@unittest.skipIf(not enumlib_present, "enum_lib not present.")
class EnumlibAdaptorTest(unittest.TestCase):
    def test_init(self):
        test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                                'test_files')
        parser = CifParser(os.path.join(test_dir, "LiFePO4.cif"))
        struct = parser.get_structures(False)[0]
        subtrans = SubstitutionTransformation({'Li': {'Li': 0.5}})
        adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 2)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 86)
        for s in structures:
Beispiel #7
0
__email__ = "*****@*****.**"
__status__ = "Beta"
__date__ = "4/5/13"

import os
import subprocess
import tempfile
import shutil

from pymatgen.io.vaspio.vasp_output import Chgcar
from pymatgen.io.vaspio.vasp_input import Potcar
from pymatgen.util.io_utils import which
from pymatgen.util.decorators import requires


@requires(which("bader"),
          "BaderAnalysis requires the executable bader to be in the path."
          " Please download the library at http://theory.cm.utexas"
          ".edu/vasp/bader/ and compile the executable.")
class BaderAnalysis(object):
    """
    Bader analysis for a CHGCAR.

    .. attribute: data

        Atomic data parsed from bader analysis. Essentially a list of dicts
        of the form::

        [
            {
                "dist": 8.769,
import unittest

from pymatgen.command_line.aconvasp_caller import get_num_division_kpoints, \
    get_minkowski_red, get_vasp_kpoint_file_sym
from pymatgen.core.composition import Composition
from pymatgen.core.structure import Lattice, Structure
from pymatgen.core.periodic_table import Element
from pymatgen.util.io_utils import which

aconvasp_present = which('aconvasp')


@unittest.skipIf(not aconvasp_present, "aconvasp not present.")
class AconvaspCallerTest(unittest.TestCase):
    def setUp(self):
        self.si = Element("Si")
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 0.75])
        self.lattice = Lattice([[3.8401979337, 0.00, 0.00],
                                [1.9200989668, 3.3257101909, 0.00],
                                [0.00, -2.2171384943, 3.1355090603]])
        self.struct = Structure(self.lattice, [self.si, self.si], coords)

    def test_get_num_division_kpoints(self):
        self.assertListEqual(get_num_division_kpoints(self.struct, 500),
                             [6, 7, 6])

    def test_get_minkowski_red(self):
        new_struct = get_minkowski_red(self.struct)
        self.assertAlmostEqual(new_struct.lattice.a, 3.840198)
Beispiel #9
0
#!/usr/bin/python

import unittest
import sys

from pymatgen.analysis.defects.point_defects import *
from pymatgen.core.structure import Structure
from pymatgen.core.periodic_table import Element
from pymatgen.util.io_utils import which

try:
    import zeo
except ImportError:
    zeo = None

gulp_present = which('gulp')


class ValenceIonicRadiusEvaluatorTest(unittest.TestCase):
    def setUp(self):
        """
        Setup MgO rocksalt structure for testing Vacancy
        """
        mgo_latt = [[4.212, 0, 0], [0, 4.212, 0], [0, 0, 4.212]]
        mgo_specie = ["Mg"] * 4 + ["O"] * 4
        mgo_frac_cord = [[0, 0, 0], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5],
                         [0.5, 0, 0], [0, 0.5, 0], [0, 0, 0.5], [0.5, 0.5, 0.5]]
        self._mgo_uc = Structure(mgo_latt, mgo_specie, mgo_frac_cord, True,
                                 True)
        self._mgo_valrad_evaluator = ValenceIonicRadiusEvaluator(self._mgo_uc)
Beispiel #10
0
__email__ = "*****@*****.**"
__status__ = "Beta"
__date__ = "4/5/13"

import os
import subprocess
import tempfile
import shutil

from pymatgen.io.vaspio.vasp_output import Chgcar
from pymatgen.io.vaspio.vasp_input import Potcar
from pymatgen.util.io_utils import which
from pymatgen.util.decorators import requires


@requires(which("bader"),
          "BaderAnalysis requires the executable bader to be in the path."
          " Please download the library at http://theory.cm.utexas"
          ".edu/vasp/bader/ and compile the executable.")
class BaderAnalysis(object):
    """
    Bader analysis for a CHGCAR.

    .. attribute: data

        Atomic data parsed from bader analysis. Essentially a list of dicts
        of the form::

        [
            {
                "dist": 8.769,
import unittest

from pymatgen.command_line.aconvasp_caller import get_num_division_kpoints, \
    get_minkowski_red, get_vasp_kpoint_file_sym
from pymatgen.core.composition import Composition
from pymatgen.core.structure import Lattice, Structure
from pymatgen.core.periodic_table import Element
from pymatgen.util.io_utils import which


aconvasp_present = which('aconvasp')


@unittest.skipIf(not aconvasp_present, "aconvasp not present.")
class AconvaspCallerTest(unittest.TestCase):

    def setUp(self):
        self.si = Element("Si")
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 0.75])
        self.lattice = Lattice([[3.8401979337, 0.00, 0.00],
                                [1.9200989668, 3.3257101909, 0.00],
                                [0.00, -2.2171384943, 3.1355090603]])
        self.struct = Structure(self.lattice, [self.si, self.si], coords)

    def test_get_num_division_kpoints(self):
        self.assertListEqual(get_num_division_kpoints(self.struct, 500),
                             [6, 7, 6])

    def test_get_minkowski_red(self):
Beispiel #12
0
class BoltztrapRunner():
    """
    This class is used to run Boltztrap on a band structure object
    """
    @requires(which('x_trans'),
              "BoltztrapRunner requires the executables 'x_trans' to be in "
              "the path. Please download the Boltztrap at "
              "http://www.icams.de/content/departments/ams/madsen/boltztrap"
              ".html and follow the instructions in the README to compile "
              "Bolztrap accordingly. Then add x_trans to your path")
    def __init__(self,
                 bs,
                 nelec,
                 dos_type="HISTO",
                 energy_grid=0.005,
                 lpfac=10,
                 sym_nb=None):
        """
        Args:
            bs:
                A band structure object
            nelec:
                the number of electrons
            dos_type:
                two options here for the band structure integration: "HISTO"
                (histogram) or "TETRA" using the tetrahedon method. TETRA
                gives typically better results especially for DOSes but takes
                more time
            energy_grid:
                the energy steps used for the integration. in eV
            lpfac:
                the number of interpolation points in the real space. By
                default 10 gives 10 time more points in the real space than
                the number of kpoints given in reciprocal space
            sym_nb:
                ?
        """
        self.lpfac = lpfac
        self._bs = bs
        self._nelec = nelec
        self.dos_type = dos_type
        self.energy_grid = energy_grid
        self.sym_nb = sym_nb
        self.error = []

    def _make_energy_file(self, file_name):
        with open(file_name, 'w') as f:
            f.write("test\n")
            f.write(str(len(self._bs.kpoints)) + "\n")
            for i in range(len(self._bs.kpoints)):
                tmp_eigs = []
                for spin in self._bs._bands:
                    for j in range(int(math.floor(self._bs._nb_bands * 0.9))):
                        tmp_eigs.append(
                            Energy(
                                self._bs._bands[spin][j][i] - self._bs.efermi,
                                "eV").to("Ry"))
                tmp_eigs.sort()
                f.write("%12.8f %12.8f %12.8f %d\n" %
                        (self._bs.kpoints[i].frac_coords[0],
                         self._bs.kpoints[i].frac_coords[1],
                         self._bs.kpoints[i].frac_coords[2], len(tmp_eigs)))
                for j in range(len(tmp_eigs)):
                    f.write("%18.8f\n" % float(tmp_eigs[j]))

    def _make_struc_file(self, file_name):
        sym = SymmetryFinder(self._bs._structure, symprec=0.01)
        with open(file_name, 'w') as f:
            f.write(self._bs._structure.composition.formula + " " +
                    str(sym.get_spacegroup_symbol()) + "\n")
            for i in range(3):
                line = ''
                for j in range(3):
                    line += "%12.5f" % (Length(
                        self._bs._structure.lattice.matrix[i][j],
                        "ang").to("bohr"))
                f.write(line + '\n')
            ops = sym.get_symmetry_dataset()['rotations']
            f.write(str(len(ops)) + "\n")
            for c in ops:
                f.write('\n'.join(
                    [' '.join([str(int(i)) for i in row]) for row in c]))
                f.write('\n')

    def _make_intrans_file(self,
                           file_name,
                           doping=[1e15, 1e16, 1e17, 1e18, 1e19, 1e20]):
        with open(file_name, 'w') as fout:
            fout.write("GENE          # use generic interface\n")
            fout.write(
                "1 0 0 0.0         # iskip (not presently used) idebug setgap shiftgap \n"
            )
            fout.write(
                "0.0 %f 0.1 %6.1f     # Fermilevel (Ry),energygrid,energy span around Fermilevel, number of electrons\n"
                % (Energy(self.energy_grid, "eV").to("Ry"), self._nelec))
            fout.write(
                "CALC                    # CALC (calculate expansion coeff), NOCALC read from file\n"
            )
            fout.write(
                "%d                        # lpfac, number of latt-points per k-point\n"
                % self.lpfac)
            fout.write(
                "BOLTZ                     # run mode (only BOLTZ is supported)\n"
            )
            fout.write(
                ".15                       # (efcut) energy range of chemical potential\n"
            )
            fout.write("800. 100.                  # Tmax, temperature grid\n")
            fout.write(
                "-1.  # energyrange of bands given DOS output sig_xxx and dos_xxx (xxx is band number)\n"
            )
            fout.write(self.dos_type + "\n")
            fout.write("1 0 0 -1\n")
            fout.write(str(2 * len(doping)) + "\n")
            for d in doping:
                fout.write(str(d) + "\n")
            for d in doping:
                fout.write(str(-d) + "\n")

    def _make_all_files(self, path):
        if self._bs.is_spin_polarized:
            self._make_energy_file(os.path.join(path, "boltztrap.energyso"))
        else:
            self._make_energy_file(os.path.join(path, "boltztrap.energy"))
        self._make_struc_file(os.path.join(path, "boltztrap.struct"))
        self._make_intrans_file(os.path.join(path, "boltztrap.intrans"))

    def run(self, prev_sigma=None, path_dir=None):
        dir_bz_name = "boltztrap"
        path_dir_orig = path_dir
        if path_dir is None:
            temp_dir = tempfile.mkdtemp()
            path_dir_orig = temp_dir
            path_dir = os.path.join(temp_dir, dir_bz_name)
        else:
            path_dir = os.path.join(path_dir_orig, dir_bz_name)
        if not os.path.exists(path_dir):
            os.mkdir(path_dir)
        else:
            for c in os.listdir(path_dir):
                os.remove(path_dir + "/" + c)
        os.chdir(path_dir)

        self._make_all_files(path_dir)
        if self._bs.is_spin_polarized:
            p = subprocess.Popen(["x_trans", "BoltzTraP", "-so"],
                                 stdout=subprocess.PIPE,
                                 stdin=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            p.wait()
        else:
            p = subprocess.Popen(["x_trans", "BoltzTraP"],
                                 stdout=subprocess.PIPE,
                                 stdin=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            p.wait()
        for c in p.communicate():
            if "STOP error in factorization" in c:
                raise BoltztrapError("STOP error in factorization")

        with open(os.path.join(path_dir, dir_bz_name + ".outputtrans")) as f:
            warning = False
            for l in f:
                if "WARNING" in l:
                    warning = True
                    break
            if warning:
                print "There was a warning! Increase lpfac to " + \
                      str(self.lpfac * 2)
                self.lpfac *= 2
                self._make_intrans_file(
                    os.path.join(path_dir, dir_bz_name + ".intrans"))
                if self.lpfac > 100:
                    raise BoltztrapError(
                        "lpfac higher than 100 and still a warning")
                self.run(path_dir_orig)
        #here we check if the doping levels were well computed
        #sometimes boltztrap mess this up because of two small energy grids
        analyzer = BoltztrapAnalyzer.from_files(path_dir)
        doping_ok = True
        for doping in ['n', 'p']:
            for c in analyzer.mu_doping[doping]:
                if len(analyzer.mu_doping[doping][c]) != len(
                        analyzer.doping[doping]):
                    doping_ok = False
                    break
                if doping == 'p' and \
                        sorted(analyzer.mu_doping[doping][c], reverse=True) != analyzer.mu_doping[doping][c]:
                    doping_ok = False
                    break
                if doping == 'n' and sorted(analyzer.mu_doping[doping][c]
                                            ) != analyzer.mu_doping[doping][c]:
                    doping_ok = False
                    break
        if not doping_ok:
            self.energy_grid /= 10
            print "lowers energy grid to " + str(self.energy_grid)
            if self.energy_grid < 0.00005:
                raise BoltztrapError(
                    "energy grid lower than 0.00005 and still no good doping")
            self._make_intrans_file(path_dir + "/" + dir_bz_name + ".intrans")
            self.run(prev_sigma=None, path_dir=path_dir_orig)
        analyzer = BoltztrapAnalyzer.from_files(path_dir)
        #here, we test if a property (eff_mass tensor) converges
        if prev_sigma is None or \
                abs(sum(analyzer.get_eig_average_eff_mass_tensor()['n']) / 3
                        - prev_sigma)\
                / prev_sigma > 0.05:
            if prev_sigma is not None:
                print abs(sum(analyzer.get_eig_average_eff_mass_tensor()['n'])
                          / 3 - prev_sigma) / prev_sigma, \
                    self.lpfac, \
                    analyzer.get_average_eff_mass_tensor(300, 1e18)
            self.lpfac *= 2
            if self.lpfac > 100:
                raise BoltztrapError(
                    "lpfac higher than 100 and still not converged")
            self._make_intrans_file(path_dir + "/" + dir_bz_name + ".intrans")
            self.run(prev_sigma=sum(
                analyzer.get_eig_average_eff_mass_tensor()['n']) / 3,
                     path_dir=path_dir_orig)
        else:
            print "converged", \
                abs(sum(analyzer.get_eig_average_eff_mass_tensor()['n'])/3
                    - prev_sigma) / prev_sigma, \
                self.lpfac, analyzer.get_average_eff_mass_tensor(300, 1e18)
        return path_dir
Beispiel #13
0
import numpy as np
import warnings

from pymatgen.io.vaspio.vasp_input import Poscar
from pymatgen.core.sites import PeriodicSite
from pymatgen.core.structure import Structure
from pymatgen.symmetry.finder import SymmetryFinder
from pymatgen.core.periodic_table import DummySpecie
from pymatgen.util.io_utils import which
from pymatgen.util.decorators import requires

logger = logging.getLogger(__name__)


@requires(
    which('multienum.x') and which('makestr.x'),
    "EnumlibAdaptor requires the executables 'multienum.x' and "
    "'makestr.x' to be in the path. Please download the library at"
    "http://enum.sourceforge.net/ and follow the instructions in "
    "the README to compile these two executables accordingly.")
class EnumlibAdaptor(object):
    """
    An adaptor for enumlib.

    .. attribute:: structures

        List of all enumerated structures.
    """
    amount_tol = 1e-5

    def __init__(self,
def get_table():
    """
    Loads a lightweight lambda table for use in unit tests to reduce
    initialization time, and make unit tests insensitive to changes in the
    default lambda table.
    """
    data_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                            'test_files', 'struct_predictor')
    json_file = os.path.join(data_dir, 'test_lambda.json')
    with open(json_file) as f:
        lambda_table = json.load(f)
    return lambda_table


if which('multienum.x') and which('makestr.x'):
    enumlib_present = True
else:
    enumlib_present = False


class SuperTransformationTest(unittest.TestCase):

    def test_apply_transformation(self):
        tl = [SubstitutionTransformation({"Li+":"Na+"}),
              SubstitutionTransformation({"Li+":"K+"})]
        t = SuperTransformation(tl)
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.375, 0.375, 0.375])
        coords.append([.5, .5, .5])
Beispiel #15
0
__date__ = "Jul 22, 2012"

import unittest
import os

from pymatgen.command_line.enumlib_caller import EnumlibAdaptor
from pymatgen import Element, Structure
from pymatgen.io.cifio import CifParser
from pymatgen.transformations.standard_transformations import \
    SubstitutionTransformation
from pymatgen.util.io_utils import which
from pymatgen.transformations.site_transformations import \
    RemoveSitesTransformation


enumlib_present = which('multienum.x') and which('makestr.x')


@unittest.skipIf(not enumlib_present, "enum_lib not present.")
class EnumlibAdaptorTest(unittest.TestCase):

    def test_init(self):
        test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                                'test_files')
        parser = CifParser(os.path.join(test_dir, "LiFePO4.cif"))
        struct = parser.get_structures(False)[0]
        subtrans = SubstitutionTransformation({'Li': {'Li': 0.5}})
        adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 2)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 86)
Beispiel #16
0
 def which(program):
     """Returns full path to a executable. None if not found or not executable."""
     return which(program)
Beispiel #17
0
"""
Created on Jan 22, 2013

@author: Bharat Medasani
"""
import unittest
import os

from pymatgen.command_line.gulp_caller import *
from pymatgen.core.structure import Structure
from pymatgen.util.io_utils import which
from pymatgen.io.vaspio.vasp_input import Poscar

test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                        'test_files')
gulp_present = which('gulp')


@unittest.skipIf(not gulp_present, "gulp not present.")
class GulpCallerInitTest(unittest.TestCase):
    def test_default_init(self):
        gulp_caller = GulpCaller()

    def test_explicit_path(self):
        gulp_caller = GulpCaller(gulp_present)


@unittest.skipIf(not gulp_present, "gulp not present.")
class GulpCallerTest(unittest.TestCase):

    def setUp(self):