Ejemplo n.º 1
0
 def test_writestring(self):
     # Test for the string export of s atructure into the exciting input xml schema
     input_string = (
         '<input xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
         'xsi:noNamespaceSchemaLocation="http://xml.exciting-code.org/excitinginput'
         '.xsd">\n  <title>Na4 Cl4</title>\n  <structure speciespath="./">\n    '
         '<crystal scale="1.8897543768634038">\n      <basevect>      5.62000000'
         '       0.00000000       0.00000000</basevect>\n      <basevect>      '
         '0.00000000       5.62000000       0.00000000</basevect>\n      '
         '<basevect>      0.00000000       0.00000000       5.62000000</basevect>'
         '\n    </crystal>\n    <species speciesfile="Na.xml">\n      <atom coord='
         '"      0.00000000       0.00000000       0.00000000" />\n      <atom coor'
         'd="      0.50000000       0.50000000       0.00000000" />\n      <atom co'
         'ord="      0.50000000       0.00000000       0.50000000" />\n      <atom '
         'coord="      0.00000000       0.50000000       0.50000000" />\n    </spec'
         'ies>\n    <species speciesfile="Cl.xml">\n      <atom coord="      0.5000'
         '0000       0.00000000       0.00000000" />\n      <atom coord="      0.00'
         '000000       0.50000000       0.00000000" />\n      <atom coord="      0.'
         '00000000       0.00000000       0.50000000" />\n      <atom coord="      '
         '0.50000000       0.50000000       0.50000000" />\n    </species>\n  </str'
         'ucture>\n</input>\n')
     lattice = Lattice.cubic('5.62')
     structure = Structure(lattice, ['Na', 'Na', 'Na', 'Na',
                                     'Cl', 'Cl', 'Cl', 'Cl'],
                           [[0, 0, 0], [0.5, 0.5, 0.0], [0.5, 0.0, 0.5],
                            [0.0, 0.5, 0.5],
                            [0.5, 0.0, 0.0], [0.0, 0.5, 0.0],
                            [0.0, 0.0, 0.5], [0.5, 0.5, 0.5]])
     excin = ExcitingInput(structure)
     for l1, l2 in zip(input_string.split("\n"),
                       excin.write_string('unchanged').split("\n")):
         if not l1.strip().startswith("<crystal scale"):
             self.assertEqual(l1, l2)
Ejemplo n.º 2
0
    def test_writebandstr(self):
        filepath = os.path.join(test_dir, 'CsI3Pb.cif')
        structure = Structure.from_file(filepath)
        excin = ExcitingInput(structure)
        string = excin.write_string('primitive', bandstr=True)
        bandstr = string.split('<properties>')[1].split('</properties>')[0]

        coord = []
        label = []
        coord_ref = [[0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0],
                     [0.0, 0.5, 0.0],
                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.5], [0.5, 0.0, 0.5],
                     [0.5, 0.5, 0.5],
                     [0.0, 0.5, 0.5], [0.0, 0.0, 0.5], [0.0, 0.5, 0.0],
                     [0.0, 0.5, 0.5],
                     [0.5, 0.0, 0.5], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0],
                     [0.5, 0.5, 0.5]]
        label_ref = ['GAMMA', 'X', 'S', 'Y', 'GAMMA', 'Z', 'U', 'R', 'T', 'Z',
                     'Y', 'T',
                     'U', 'X', 'S', 'R']
        root = ET.fromstring(bandstr)
        for plot1d in root.iter('plot1d'):
            for point in plot1d.iter('point'):
                coord.append([float(i) for i in point.get('coord').split()])
                label.append(point.get('label'))
        self.assertEqual(label, label_ref)
        self.assertEqual(coord, coord_ref)
Ejemplo n.º 3
0
    def test_writebandstr(self):
        filepath = os.path.join(test_dir, 'CsI3Pb.cif')
        structure = Structure.from_file(filepath)
        excin = ExcitingInput(structure)
        string = excin.write_string('primitive', bandstr=True)
        bandstr = string.split('<properties>')[1].split('</properties>')[0]

        coord = []
        label = []
        coord_ref = [[0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0],
                     [0.0, 0.5, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.5],
                     [0.5, 0.0, 0.5], [0.5, 0.5, 0.5], [0.0, 0.5, 0.5],
                     [0.0, 0.0, 0.5], [0.0, 0.5, 0.0], [0.0, 0.5, 0.5],
                     [0.5, 0.0, 0.5], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0],
                     [0.5, 0.5, 0.5]]
        label_ref = [
            'GAMMA', 'X', 'S', 'Y', 'GAMMA', 'Z', 'U', 'R', 'T', 'Z', 'Y', 'T',
            'U', 'X', 'S', 'R'
        ]
        root = ET.fromstring(bandstr)
        for plot1d in root.iter('plot1d'):
            for point in plot1d.iter('point'):
                coord.append([float(i) for i in point.get('coord').split()])
                label.append(point.get('label'))
        self.assertEqual(label, label_ref)
        self.assertEqual(coord, coord_ref)
Ejemplo n.º 4
0
 def test_writestring(self):
     # Test for the string export of s atructure into the exciting input xml schema
     input_string = (
         '<input xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
         'xsi:noNamespaceSchemaLocation="http://xml.exciting-code.org/excitinginput'
         '.xsd">\n  <title>Na4 Cl4</title>\n  <structure speciespath="./">\n    '
         '<crystal scale="1.8897543768634038">\n      <basevect>      5.62000000'
         '       0.00000000       0.00000000</basevect>\n      <basevect>      '
         '0.00000000       5.62000000       0.00000000</basevect>\n      '
         '<basevect>      0.00000000       0.00000000       5.62000000</basevect>'
         '\n    </crystal>\n    <species speciesfile="Na.xml">\n      <atom coord='
         '"      0.00000000       0.00000000       0.00000000" />\n      <atom coor'
         'd="      0.50000000       0.50000000       0.00000000" />\n      <atom co'
         'ord="      0.50000000       0.00000000       0.50000000" />\n      <atom '
         'coord="      0.00000000       0.50000000       0.50000000" />\n    </spec'
         'ies>\n    <species speciesfile="Cl.xml">\n      <atom coord="      0.5000'
         '0000       0.00000000       0.00000000" />\n      <atom coord="      0.00'
         '000000       0.50000000       0.00000000" />\n      <atom coord="      0.'
         '00000000       0.00000000       0.50000000" />\n      <atom coord="      '
         '0.50000000       0.50000000       0.50000000" />\n    </species>\n  </str'
         'ucture>\n</input>\n')
     lattice = Lattice.cubic('5.62')
     structure = Structure(
         lattice, ['Na', 'Na', 'Na', 'Na', 'Cl', 'Cl', 'Cl', 'Cl'],
         [[0, 0, 0], [0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.0, 0.5, 0.5],
          [0.5, 0.0, 0.0], [0.0, 0.5, 0.0], [0.0, 0.0, 0.5],
          [0.5, 0.5, 0.5]])
     excin = ExcitingInput(structure)
     for l1, l2 in zip(input_string.split("\n"),
                       excin.write_string('unchanged').split("\n")):
         if not l1.strip().startswith("<crystal scale"):
             self.assertEqual(l1.strip(), l2.strip())
Ejemplo n.º 5
0
    def test_writebandstr(self):
        filepath = os.path.join(test_dir, "CsI3Pb.cif")
        structure = Structure.from_file(filepath)
        excin = ExcitingInput(structure)
        string = excin.write_string("primitive", bandstr=True)
        bandstr = string.split("<properties>")[1].split("</properties>")[0]

        coord = []
        label = []
        coord_ref = [
            [0.0, 0.0, 0.0],
            [0.5, 0.0, 0.0],
            [0.5, 0.5, 0.0],
            [0.0, 0.5, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.5],
            [0.5, 0.0, 0.5],
            [0.5, 0.5, 0.5],
            [0.0, 0.5, 0.5],
            [0.0, 0.0, 0.5],
            [0.0, 0.5, 0.0],
            [0.0, 0.5, 0.5],
            [0.5, 0.0, 0.5],
            [0.5, 0.0, 0.0],
            [0.5, 0.5, 0.0],
            [0.5, 0.5, 0.5],
        ]
        label_ref = [
            "GAMMA",
            "X",
            "S",
            "Y",
            "GAMMA",
            "Z",
            "U",
            "R",
            "T",
            "Z",
            "Y",
            "T",
            "U",
            "X",
            "S",
            "R",
        ]
        root = ET.fromstring(bandstr)
        for plot1d in root.iter("plot1d"):
            for point in plot1d.iter("point"):
                coord.append([float(i) for i in point.get("coord").split()])
                label.append(point.get("label"))
        self.assertEqual(label, label_ref)
        self.assertEqual(coord, coord_ref)
Ejemplo n.º 6
0
    def test_paramdict(self):
        coords = [[0.0, 0.0, 0.0], [0.75, 0.5, 0.75]]
        lattice = Lattice.from_parameters(a=3.84,
                                          b=3.84,
                                          c=3.84,
                                          alpha=120,
                                          beta=90,
                                          gamma=60)
        struct = Structure(lattice, ["Si", "Si"], coords)
        paradir = {
            "grst": {
                "do": "fromscratch",
                "ngridk": "8 8 8",
                "xctype": "GGA_PBE_SOL",
                "gmaxvr": "14.0",
            },
            "xs": {
                "xstype": "BSE",
                "ngridk": "4 4 4",
                "ngridq": "4 4 4",
                "nempty": "30",
                "gqmax": "3.0",
                "broad": "0.07",
                "tevout": "true",
                "energywindow": {
                    "intv": "0.0 1.0",
                    "points": "1200"
                },
                "screening": {
                    "screentype": "full",
                    "nempty": "100"
                },
                "BSE": {
                    "bsetype": "singlet",
                    "nstlbse": "1 5 1 4"
                },
            },
        }

        test_input = ExcitingInput(struct)
        test_string = test_input.write_string("unchanged", **paradir)

        # read reference file
        filepath = os.path.join(PymatgenTest.TEST_FILES_DIR,
                                "input_exciting2.xml")
        tree = ET.parse(filepath)
        root = tree.getroot()
        ref_string = ET.tostring(root, encoding="unicode")

        self.assertEqual(ref_string.strip(), test_string.strip())
Ejemplo n.º 7
0
 def test_fromfile(self):
     # Test for the import of a structure directly from an exciting
     # input file
     filepath = os.path.join(test_dir, 'input1.xml')
     excin = ExcitingInput.from_file(filepath)
     lattice = [[0.0, 2.81, 2.81], [2.81, 0.0, 2.81], [2.81, 2.81, 0.0]]
     atoms = ['Na', 'Cl']
     fraccoords = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]]
     self.assertEqual(lattice, excin.structure.lattice.matrix.tolist())
     self.assertEqual(atoms,
                      [site.specie.symbol for site in excin.structure])
     self.assertEqual(fraccoords, [site.frac_coords.tolist() for site in
                                   excin.structure])
Ejemplo n.º 8
0
 def test_fromfile(self):
     # Test for the import of a structure directly from an exciting
     # input file
     filepath = os.path.join(test_dir, 'input1.xml')
     excin = ExcitingInput.from_file(filepath)
     lattice = [[0.0, 2.81, 2.81], [2.81, 0.0, 2.81], [2.81, 2.81, 0.0]]
     atoms = ['Na', 'Cl']
     fraccoords = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]]
     self.assertEqual(lattice, excin.structure.lattice.matrix.tolist())
     self.assertEqual(atoms,
                      [site.specie.symbol for site in excin.structure])
     self.assertEqual(
         fraccoords,
         [site.frac_coords.tolist() for site in excin.structure])
Ejemplo n.º 9
0
 def parse(self, options, *args, **kwargs):
     path = self.raw_value
     if exists(path):
         if isfile(path):
             filename = basename(path)
             if filename.lower().endswith('.cif'):
                 from pymatgen.io.cif import CifParser
                 try:
                     result = CifParser(path).get_structures()[0]
                 except:
                     self.write_message(
                         'Could not parse CIF file: "{0}"'.format(path))
                     raise InvalidOption
             elif filename.lower().endswith('.cssr'):
                 from pymatgen.io.cssr import Cssr
                 try:
                     result = Cssr.from_file(path).structure
                 except:
                     self.write_message(
                         'Could not parse CSSR file: "{0}"'.format(path))
                     raise InvalidOption
             elif filename.lower().endswith('.xml'):
                 from pymatgen.io.exciting import ExcitingInput
                 try:
                     result = ExcitingInput.from_file(path).structure
                 except:
                     self.write_message(
                         'Could not parse Exciting input file: "{0}"'.
                         format(path))
                     raise InvalidOption
             else:
                 from pymatgen.io.vasp import Poscar
                 try:
                     result = Poscar.from_file(path).structure
                 except:
                     self.write_message(
                         'Could not parse POSCAR file "{0}"'.format(path))
                     raise InvalidOption
             if not 'result' in locals():
                 write_message('File format not supported')
                 raise InvalidOption
             else:
                 return result
         else:
             self.write_message('"{0}" is a directory!'.format(path))
             raise InvalidOption
     else:
         self.write_message('Cannot locate file "{0}"'.format(path))
         raise InvalidOption
Ejemplo n.º 10
0
 def test_fromfile(self):
     # Test for the import of a structure directly from an exciting
     # input file
     filepath = os.path.join(PymatgenTest.TEST_FILES_DIR,
                             "input_exciting1.xml")
     excin = ExcitingInput.from_file(filepath)
     lattice = [[0.0, 2.81, 2.81], [2.81, 0.0, 2.81], [2.81, 2.81, 0.0]]
     atoms = ["Na", "Cl"]
     fraccoords = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]]
     self.assertArrayAlmostEqual(lattice,
                                 excin.structure.lattice.matrix.tolist())
     self.assertEqual(atoms,
                      [site.specie.symbol for site in excin.structure])
     self.assertEqual(
         fraccoords,
         [site.frac_coords.tolist() for site in excin.structure])
Ejemplo n.º 11
0
    def from_file(cls, filename, primitive=False, sort=False, merge_tol=0.0):
        """
        Reads a structure from a file. For example, anything ending in
        a "cif" is assumed to be a Crystallographic Information Format file.
        Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT,
        vasprun.xml, CSSR, Netcdf and pymatgen's JSON serialized structures.

        Args:
            filename (str): The filename to read from.
            primitive (bool): Whether to convert to a primitive cell
                Only available for cifs. Defaults to False.
            sort (bool): Whether to sort sites. Default to False.
            merge_tol (float): If this is some positive number, sites that
                are within merge_tol from each other will be merged. Usually
                0.01 should be enough to deal with common numerical issues.

        Returns:
            Structure.
        """
        filename = str(filename)
        if filename.endswith(".nc"):
            # Read Structure from a netcdf file.
            from pymatgen.io.abinit.netcdf import structure_from_ncdata
            s = structure_from_ncdata(filename, cls=cls)
            if sort:
                s = s.get_sorted_structure()
            return s

        from pymatgen.io.lmto import LMTOCtrl
        from pymatgen.io.vasp import Vasprun, Chgcar
        from pymatgen.io.exciting import ExcitingInput
        from monty.io import zopen
        fname = os.path.basename(filename)
        with zopen(filename, "rt") as f:
            contents = f.read()
        if fnmatch(fname.lower(), "*.cif*") or fnmatch(fname.lower(), "*.mcif*"):
            return cls.from_str(contents, fmt="cif",
                                primitive=primitive, sort=sort,
                                merge_tol=merge_tol)
        elif fnmatch(fname, "*POSCAR*") or fnmatch(fname, "*CONTCAR*") or fnmatch(fname, "*.vasp"):
            s = cls.from_str(contents, fmt="poscar",
                             primitive=primitive, sort=sort,
                             merge_tol=merge_tol)

        elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"):
            s = Chgcar.from_file(filename).structure
        elif fnmatch(fname, "vasprun*.xml*"):
            s = Vasprun(filename).final_structure
        elif fnmatch(fname.lower(), "*.cssr*"):
            return cls.from_str(contents, fmt="cssr",
                                primitive=primitive, sort=sort,
                                merge_tol=merge_tol)
        elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
            return cls.from_str(contents, fmt="json",
                                primitive=primitive, sort=sort,
                                merge_tol=merge_tol)
        elif fnmatch(fname, "*.yaml*"):
            return cls.from_str(contents, fmt="yaml",
                                primitive=primitive, sort=sort,
                                merge_tol=merge_tol)
        elif fnmatch(fname, "*.xsf"):
            return cls.from_str(contents, fmt="xsf",
                                primitive=primitive, sort=sort,
                                merge_tol=merge_tol)
        elif fnmatch(fname, "input*.xml"):
            return ExcitingInput.from_file(fname).structure
        elif fnmatch(fname, "*rndstr.in*") \
                or fnmatch(fname, "*lat.in*") \
                or fnmatch(fname, "*bestsqs*"):
            return cls.from_str(contents, fmt="mcsqs",
                                primitive=primitive, sort=sort,
                                merge_tol=merge_tol)
        elif fnmatch(fname, "CTRL*"):
            return LMTOCtrl.from_file(filename=filename).structure
        else:
            raise ValueError("Unrecognized file extension!")
        if sort:
            s = s.get_sorted_structure()
        if merge_tol:
            s.merge_sites(merge_tol)

        s.__class__ = cls
        return s