def write_structure(structure, filename): """ Write a structure to a file 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, CSSR and pymatgen's JSON serialized structures. Args: structure (Structure/IStructure): Structure to write filename (str): A filename to write to. """ fname = os.path.basename(filename) if fnmatch(fname, "*.cif*"): writer = CifWriter(structure) elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"): writer = Poscar(structure) elif fnmatch(fname.lower(), "*.cssr*"): writer = Cssr(structure) elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"): with zopen(filename, "wt") as f: f.write(str2unicode(json.dumps(structure, cls=MontyEncoder))) return else: raise ValueError("Unrecognized file extension!") writer.write_file(filename)
def write_structure(structure, filename): """ Write a structure to a file 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, CSSR and pymatgen's JSON serialized structures. Args: structure (Structure/IStructure): Structure to write filename (str): A filename to write to. """ fname = os.path.basename(filename) if fnmatch(fname, "*.cif*"): writer = CifWriter(structure) elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"): writer = Poscar(structure) elif fnmatch(fname.lower(), "*.cssr*"): writer = Cssr(structure) elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"): with zopen(filename, "w") as f: json.dump(structure, f, cls=PMGJSONEncoder) return else: raise ValueError("Unrecognized file extension!") writer.write_file(filename)
def write_structure(structure, filename): """ Write a structure to a file 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, CSSR and pymatgen's JSON serialized structures. Args: structure: Structure to write filename: A filename to write to. """ lower_filename = os.path.basename(filename).lower() if re.search("\.cif", lower_filename): writer = CifWriter(structure) elif lower_filename.startswith("poscar") \ or lower_filename.startswith("contcar"): writer = Poscar(structure) elif re.search("\.cssr", lower_filename): writer = Cssr(structure) elif re.search("\.[mj]son", lower_filename): with zopen(lower_filename, "w") as f: json.dump(structure, f, cls=PMGJSONEncoder) return else: raise ValueError("Unrecognized file extension!") writer.write_file(filename)
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 == "smart": structure = read_structure(filename) if iformat == "POSCAR": p = Poscar.from_file(filename) structure = p.structure elif iformat == "CIF": r = CifParser(filename) structure = r.get_structures()[0] elif iformat == "CSSR": structure = Cssr.from_file(filename).structure if oformat == "smart": write_structure(structure, 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": input_set = MPVaspInputSet() ts = TransformedStructure(structure, [], history=[{ "source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read() }]) ts.write_vasp_input(input_set, output_dir=out_filename) elif oformat == "MITVASP": input_set = MITVaspInputSet() ts = TransformedStructure(structure, [], history=[{ "source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read() }]) ts.write_vasp_input(input_set, output_dir=out_filename) except Exception as ex: print "Error converting file. Are they in the right format?" print str(ex)
def cif(src="POSCAR"): """ cifファイルを作成 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) std = finder.get_conventional_standard_structure() cif = CifWriter(std, find_spacegroup=True, symprec=0.1) cif.write_file("poscar.cif")
def prim_cif(self, dst): """ primitive cellでのcifフォーマットをgetする """ finder = SpacegroupAnalyzer(self.structure) structure = finder.get_primitive_standard_structure() structure = finder.get_conventional_standard_structure() cif = CifWriter(structure, find_spacegroup=True, symprec=0.1) cif.write_file(dst)
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 == "smart": structure = read_structure(filename) if iformat == "POSCAR": p = Poscar.from_file(filename) structure = p.structure elif iformat == "CIF": r = CifParser(filename) structure = r.get_structures()[0] elif iformat == "CSSR": structure = Cssr.from_file(filename).structure if oformat == "smart": write_structure(structure, 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": input_set = MPVaspInputSet() ts = TransformedStructure( structure, [], history=[ {"source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read()} ], ) ts.write_vasp_input(input_set, output_dir=out_filename) elif oformat == "MITVASP": input_set = MITVaspInputSet() ts = TransformedStructure( structure, [], history=[ {"source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read()} ], ) ts.write_vasp_input(input_set, output_dir=out_filename) except Exception as ex: print "Error converting file. Are they in the right format?" print str(ex)
def batch_write_vasp_input(structures, vasp_input_set, output_dir, make_dir_if_not_present=True, subfolder=None, sanitize=False, include_cif=False): """ Batch write vasp input for a sequence of structures to output_dir, following the format output_dir/{group}/{formula}_{number}. Args: structures: Sequence of Structures. vasp_input_set: pymatgen.io.vaspio_set.VaspInputSet like object that creates vasp input files from structures output_dir: Directory to output files make_dir_if_not_present: Create the directory if not present. Defaults to True. subfolder: function to create subdirectory name from structure. Defaults to simply "formula_count". sanitize: Boolean indicating whether to sanitize the structure before writing the VASP input files. Sanitized output are generally easier for viewing and certain forms of analysis. Defaults to False. include_cif: Boolean indication whether to output a CIF as well. CIF files are generally better supported in visualization programs. """ for i, s in enumerate(structures): formula = re.sub("\s+", "", s.formula) if subfolder is not None: subdir = subfolder(s) dirname = os.path.join(output_dir, subdir) else: dirname = os.path.join(output_dir, '{}_{}'.format(formula, i)) if sanitize: s = s.copy(sanitize=True) vasp_input_set.write_input( s, dirname, make_dir_if_not_present=make_dir_if_not_present) if include_cif: from pymatgen.io.cifio import CifWriter writer = CifWriter(s) writer.write_file( os.path.join(dirname, "{}_{}.cif".format(formula, i)))
def batch_write_vasp_input(structures, vasp_input_set, output_dir, make_dir_if_not_present=True, subfolder=None, sanitize=False, include_cif=False): """ Batch write vasp input for a sequence of structures to output_dir, following the format output_dir/{group}/{formula}_{number}. Args: structures: Sequence of Structures. vasp_input_set: pymatgen.io.vaspio_set.VaspInputSet like object that creates vasp input files from structures output_dir: Directory to output files make_dir_if_not_present: Create the directory if not present. Defaults to True. subfolder: function to create subdirectory name from structure. Defaults to simply "formula_count". sanitize: Boolean indicating whether to sanitize the structure before writing the VASP input files. Sanitized output are generally easier for viewing and certain forms of analysis. Defaults to False. include_cif: Boolean indication whether to output a CIF as well. CIF files are generally better supported in visualization programs. """ for i, s in enumerate(structures): formula = re.sub("\s+", "", s.formula) if subfolder is not None: subdir = subfolder(s) dirname = os.path.join(output_dir, subdir) else: dirname = os.path.join(output_dir, '{}_{}'.format(formula, i)) if sanitize: s = s.copy(sanitize=True) vasp_input_set.write_input( s, dirname, make_dir_if_not_present=make_dir_if_not_present ) if include_cif: from pymatgen.io.cifio import CifWriter writer = CifWriter(s) writer.write_file(os.path.join(dirname, "{}_{}.cif".format(formula, i)))
def batch_write_vasp_input(transformed_structures, vasp_input_set, output_dir, create_directory=True, subfolder=None, include_cif=False): """ Batch write vasp input for a sequence of transformed structures to output_dir, following the format output_dir/{group}/{formula}_{number}. Args: transformed_structures: Sequence of TransformedStructures. vasp_input_set: pymatgen.io.vaspio_set.VaspInputSet like object that creates vasp input files from structures output_dir: Directory to output files create_directory: Create the directory if not present. Defaults to True. subfolder: function to create subdirectory name from transformed_structure. eg. lambda x: x.other_parameters["tags"][0] to use the first tag. include_cif: Boolean indication whether to output a CIF as well. CIF files are generally better supported in visualization programs. """ for i, s in enumerate(transformed_structures): formula = re.sub("\s+", "", s.final_structure.formula) if subfolder is not None: subdir = subfolder(s) dirname = os.path.join(output_dir, subdir, "{}_{}".format(formula, i)) else: dirname = os.path.join(output_dir, "{}_{}".format(formula, i)) s.write_vasp_input(vasp_input_set, dirname, create_directory=create_directory) if include_cif: from pymatgen.io.cifio import CifWriter writer = CifWriter(s.final_structure) writer.write_file(os.path.join(dirname, "{}.cif".format(formula)))
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 == "smart": structure = read_structure(filename) if iformat == "POSCAR": p = Poscar.from_file(filename) structure = p.structure elif iformat == "CIF": r = CifParser(filename) structure = r.get_structures()[0] elif iformat == "CSSR": structure = Cssr.from_file(filename).structure if oformat == "smart": write_structure(structure, 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": input_set = MaterialsProjectVaspInputSet() transmuter = StandardTransmuter.from_structures([structure], []) transmuter.write_vasp_input(input_set, output_dir=out_filename) except Exception as ex: print "Error converting file. Are they in the right format?" print str(ex)
def write_structure(structure, filename): """ Write a structure to a file based on file extension. For example, anything ending in a "cif" is assumed to be a Crystallographic Information Format file. Args: structure: Structure to write filename: A filename to write to. """ lower_filename = os.path.basename(filename).lower() if re.search("\.cif", lower_filename): writer = CifWriter(structure) elif lower_filename.startswith("poscar") \ or lower_filename.startswith("contcar"): writer = Poscar(structure) elif re.search("\.cssr", lower_filename): writer = Cssr(structure) else: raise ValueError("Unrecognized file extension!") writer.write_file(filename)
def move_atom(input_cif, output_cif, atom_idx, displacement_vec): """ Reads input cif (as file name), moves atom by displacement vector (in angstroms), and writes to output_cif (as file name). Currently, doesn't take into account the symmetry operations. This is theoretically possible with PyMatGen, although I found it to be buggy so decided it might not be worth it. Useful things to look up for implementing this: pymatgen.symmetry.analyzer.SpacegroupAnalyzer.get_symmetrized_structure and its resulting method find_equivalent_sites() """ parser = CifParser(input_cif) struct = parser.get_structures()[0] lat_const = np.array(struct.lattice.abc) frac_pos = struct[atom_idx].frac_coords new_pos = frac_pos + displacement_vec / lat_const struct[atom_idx] = struct[atom_idx].species_and_occu.elements[0], new_pos writer = CifWriter(struct) writer.write_file(output_cif)
def move_atom(input_cif, output_cif, atom_idx, displacement_vec): """ Reads input cif (as file name), moves atom by displacement vector (in angstroms), and writes to output_cif (as file name). Currently, doesn't take into account the symmetry operations. This is theoretically possible with PyMatGen, although I found it to be buggy so decided it might not be worth it. Useful things to look up for implementing this: pymatgen.symmetry.analyzer.SpacegroupAnalyzer.get_symmetrized_structure and its resulting method find_equivalent_sites() """ parser = CifParser(input_cif) struct = parser.get_structures()[0] lat_const = np.array(struct.lattice.abc) frac_pos = struct[atom_idx].frac_coords new_pos = frac_pos + displacement_vec/lat_const struct[atom_idx] = struct[atom_idx].species_and_occu.elements[0], new_pos writer = CifWriter(struct) writer.write_file(output_cif)
__email__ = "*****@*****.**" __date__ = "Nov 14, 2011" import argparse from pymatgen.io.vaspio import Poscar from pymatgen.io.cifio import CifParser, CifWriter parser = argparse.ArgumentParser(description='''Convenient file format convertor. Author: Shyue Ping Ong Version: 1.0 Last updated: Oct 26 2011''') parser.add_argument('input_file', metavar='input file', type=str, nargs = 1, help='input file') parser.add_argument('output_file', metavar='output file', type=str, nargs = 1, help='output file') parser.add_argument('-c', '--conversion', dest='conversion', type=str, nargs = 1, choices=['poscar2cif','cif2poscar'], default='poscar2cif', help='Format conversion desired. ') args = parser.parse_args() try: if args.conversion[0] == 'poscar2cif': p = Poscar.from_file(args.input_file[0]) w = CifWriter(p.struct) w.write_file(args.output_file[0]) else: r = CifParser(args.input_file[0]) p = Poscar(r.get_structures()[0]) p.write_file(args.output_file[0]) except Exception as ex: print "Error converting file. Are they in the right format?" print str(ex)