Exemplo n.º 1
0
def convert_fmt(args):
    iformat = args.input_format[0]
    oformat = args.output_format[0]
    filename = args.input_filename[0]
    out_filename = args.output_filename[0]

    try:

        if iformat == "POSCAR":
            p = Poscar.from_file(filename)
            structure = p.structure
        elif iformat == "CIF":
            r = CifParser(filename)
            structure = r.get_structures()[0]
        elif iformat == "CONVENTIONAL_CIF":
            r = CifParser(filename)
            structure = r.get_structures(primitive=False)[0]
        elif iformat == "CSSR":
            structure = Cssr.from_file(filename).structure
        else:
            structure = Structure.from_file(filename)

        if oformat == "smart":
            structure.to(filename=out_filename)
        elif oformat == "POSCAR":
            p = Poscar(structure)
            p.write_file(out_filename)
        elif oformat == "CIF":
            w = CifWriter(structure)
            w.write_file(out_filename)
        elif oformat == "CSSR":
            c = Cssr(structure)
            c.write_file(out_filename)
        elif oformat == "VASP":
            ts = TransformedStructure(
                structure, [],
                history=[{"source": "file",
                          "datetime": str(datetime.datetime.now()),
                          "original_file": open(filename).read()}])
            ts.write_vasp_input(MPRelaxSet, output_dir=out_filename)
        elif oformat == "MITVASP":
            ts = TransformedStructure(
                structure, [],
                history=[{"source": "file",
                          "datetime": str(datetime.datetime.now()),
                          "original_file": open(filename).read()}])
            ts.write_vasp_input(MITRelaxSet, output_dir=out_filename)

    except Exception as ex:
        print("Error converting file. Are they in the right format?")
        print(str(ex))
Exemplo n.º 2
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
Exemplo n.º 3
0
def read_structure(filename, primitive=True, sort=False):
    """
    Reads a structure based on file extension. 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 and pymatgen's JSON serialized structures.

    Args:
        filename (str): A filename to read from.
        primitive (bool): Whether to convert to a primitive cell for cifs.
            Defaults to True.
        sort (bool): Whether to sort sites. Default to False.

    Returns:
        A Structure object.
    """
    fname = os.path.basename(filename)
    if fnmatch(fname.lower(), "*.cif*"):
        parser = CifParser(filename)
        s = parser.get_structures(primitive=primitive)[0]
    elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"):
        s = Poscar.from_file(filename, False).structure
    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*"):
        cssr = Cssr.from_file(filename)
        s = cssr.structure
    elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
        with zopen(filename) as f:
            s = json.load(f, cls=MontyDecoder)
            if type(s) != Structure:
                raise IOError("File does not contain a valid serialized "
                              "structure")
    else:
        raise ValueError("Unrecognized file extension!")
    if sort:
        s = s.get_sorted_structure()
    return s
Exemplo n.º 4
0
def read_structure(filename, primitive=True, sort=False):
    """
    Reads a structure based on file extension. 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 and pymatgen's JSON serialized structures.

    Args:
        filename (str): A filename to read from.
        primitive (bool): Whether to convert to a primitive cell for cifs.
            Defaults to True.
        sort (bool): Whether to sort sites. Default to False.

    Returns:
        A Structure object.
    """
    fname = os.path.basename(filename)
    if fnmatch(fname.lower(), "*.cif*"):
        parser = CifParser(filename)
        s = parser.get_structures(primitive=primitive)[0]
    elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"):
        s = Poscar.from_file(filename, False).structure
    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*"):
        cssr = Cssr.from_file(filename)
        s = cssr.structure
    elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
        with zopen(filename) as f:
            s = json.load(f, cls=MontyDecoder)
            if type(s) != Structure:
                raise IOError("File does not contain a valid serialized "
                              "structure")
    else:
        raise ValueError("Unrecognized file extension!")
    if sort:
        s = s.get_sorted_structure()
    return s
Exemplo n.º 5
0
 def test_from_file(self):
     filename = os.path.join(test_dir, "Si.cssr")
     cssr = Cssr.from_file(filename)
     self.assertIsInstance(cssr.structure, Structure)
Exemplo n.º 6
0
 def test_from_file(self):
     filename = os.path.join(PymatgenTest.TEST_FILES_DIR, "Si.cssr")
     cssr = Cssr.from_file(filename)
     self.assertIsInstance(cssr.structure, Structure)
Exemplo n.º 7
0
 def test_from_file(self):
     filename = os.path.join(test_dir, "Si.cssr")
     cssr = Cssr.from_file(filename)
     self.assertIsInstance(cssr.structure, Structure)