Example #1
0
def main(api="", queryid=""):
    """Get VASP inputs for Materials Project structure
        Args:
            api <str>: Materials Project API key
            queryid <str>: Materials Project ID of the structure
        Returns:
            creates a folder named with that mpid, and including
            some VASP input files.
    """
    if api == "":
        print "Must have an API key from materialsproject.org"
        return None
    if queryid == "":
        print "No MP structure ID given. Exiting."
        return None
    rest_adapter = MPRester(api)
    entries=list()
    proplist=list()
    proplist.append('pretty_formula')
    proplist.append('structure')
    proplist.append('potcar')
    proplist.append('material_id')
    
    myentry = rest_adapter.mpquery(criteria={'material_id':queryid}, properties=proplist)
    if len(myentry) == 0:
        print "Could not find entry for %s as material_id. Trying entry_id." % queryid
        myentry = rest_adapter.mpquery(criteria={'entry_id':queryid}, properties=proplist)
    if len(myentry) == 0:
        print "Could not find entry for %s" % queryid
        return None
    entries.extend(myentry)

    workdir = os.getcwd()
    from pymatgen.io.vaspio_set import MITVaspInputSet, MPVaspInputSet
    for entry in entries: 
        mpvis = MPVaspInputSet()
        myname = str(entry['pretty_formula'])
        #print entry['structure'].composition
        #print entry['structure'].formula
        #myname = entry['pretty_formula']
        myname = myname.replace("(","_").replace(")","_")
        myname = myname + "_" + entry['material_id']
        os.mkdir(myname)
        os.chdir(myname)
        mystructure = entry['structure']
        if mystructure.num_sites <= 10:
            mystructure.make_supercell([2,2,2])
        #mystructure.perturb(0.01)
        incar = mpvis.get_incar(mystructure)
        incar.write_file("INCAR")
        potcar = mpvis.get_potcar(mystructure)
        potcar.write_file("POTCAR")
        #potcar_symbols = mpvis.get_potcar_symbols(mystructure) 
        myposcar=Poscar(mystructure)
        mykpoints=mpvis.get_kpoints(mystructure)
        mykpoints.write_file("KPOINTS")


        myposcar.write_file("POSCAR")
        os.chdir(workdir)
Example #2
0
 def _vasp_poscar_setup(self):
     """Set up the POSCAR file for a single VASP run.
     """
     name = self.keywords['name']
     pospath = os.path.join(name, "POSCAR")
     if os.path.isfile(pospath):
         my_poscar = Poscar.from_file(pospath) 
         #parent should have given a structure
     else: #this is an originating run; mast should give it a structure
         my_poscar = Poscar(self.keywords['structure'])
         workdir=os.path.dirname(name)
         sdir=os.path.join(workdir,"structure_index_files")
         if os.path.exists(sdir):
             mystr=my_poscar.structure
             manname="manifest___"
             myatomindex=AtomIndex(structure_index_directory=sdir)
             newstr=myatomindex.graft_new_coordinates_from_manifest(mystr, manname, "")
             self.logger.info("Getting original coordinates from manifest.")
             new_pos=Poscar(newstr)
             my_poscar=new_pos
         self.logger.info("No POSCAR found from a parent; base structure used for %s" % self.keywords['name'])
     if 'mast_coordinates' in self.keywords['program_keys'].keys():
         sxtend = StructureExtensions(struc_work1=my_poscar.structure, name=self.keywords['name'])
         coordstrucs=self.get_coordinates_only_structure_from_input()
         newstruc = sxtend.graft_coordinates_onto_structure(coordstrucs[0])
         my_poscar.structure=newstruc.copy()
     dirutil.lock_directory(name)
     self.write_poscar_with_zero_velocities(my_poscar, pospath)
     dirutil.unlock_directory(name)
     return my_poscar
Example #3
0
 def forward_final_structure_file(self, childpath, newname="POSCAR"):
     """Forward the final structure.
         For VASP, this is the CONTCAR.
         Args:
             childpath <str>: Path of child ingredient
             newname <str>: new name (default 'POSCAR')
     """
     proceed=False
     workdir=os.path.dirname(self.keywords['name'])
     sdir=os.path.join(workdir,"structure_index_files")
     if os.path.exists(sdir):
         proceed=True
     if not proceed:
         return self.copy_a_file(childpath, "CONTCAR", newname)
     childmeta=Metadata(metafile="%s/metadata.txt" % childpath)
     child_program=childmeta.read_data("program")
     if not "vasp" in child_program: #madelung utility or another folder
         return self.copy_a_file(childpath, "CONTCAR", newname)
     child_scaling_label=childmeta.read_data("scaling_label")
     child_defect_label=childmeta.read_data("defect_label")
     child_neb_label=childmeta.read_data("neb_label")
     child_phonon_label=childmeta.read_data("phonon_label")
     if child_scaling_label == None:
         child_scaling_label = ""
     if child_defect_label == None:
         child_defect_label = ""
     if child_neb_label == None:
         child_neb_label = ""
     if child_phonon_label == None:
         child_phonon_label = ""
     parentmeta=Metadata(metafile="%s/metadata.txt" % self.keywords['name'])
     parent_defect_label=parentmeta.read_data("defect_label")
     parent_neb_label=parentmeta.read_data("neb_label")
     if parent_defect_label == None:
         parent_defect_label = ""
     if parent_neb_label == None:
         parent_neb_label = ""
     if (not (child_neb_label == "")) and (not (parent_defect_label == "")):
         child_defect_label = parent_defect_label
     if (not (child_phonon_label == "")):
         if (not (parent_defect_label == "")):
             child_defect_label = parent_defect_label
         if (not (parent_neb_label == "")):
             child_neb_label = parent_neb_label
             child_defect_label = parent_neb_label.split('-')[0].strip() # always define phonons from first endpoint
     #get child manifest
     childmanifest="manifest_%s_%s_%s" % (child_scaling_label, child_defect_label, child_neb_label)
     #build structure from atom indices using parent name_frac_coords
     ing_label=os.path.basename(self.keywords['name'])
     childmeta.write_data("parent",ing_label)
     mystr=Poscar.from_file("%s/CONTCAR" % self.keywords['name']).structure
     myatomindex=AtomIndex(structure_index_directory=sdir)
     if "inducescaling" in childpath: #initial scaled coords have no parent
         ing_label="original"
     newstr=myatomindex.graft_new_coordinates_from_manifest(mystr, childmanifest,ing_label)
     newposcar=Poscar(newstr)
     newposcar.write_file(os.path.join(childpath,newname))
     return
Example #4
0
def run_aconvasp_command(command, structure):
    """
    Helper function for calling aconvasp with different arguments
    """
    from pymatgen.io.vaspio import Poscar
    poscar = Poscar(structure)
    p = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    output = p.communicate(input=poscar.get_string())
    return output
Example #5
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 == "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 main():

    s1name = "geometry/BCC_to_FCC/POSCAR_BCC"
    s2name = "geometry/BCC_to_FCC/POSCAR_FCC"
    s1 = Poscar.from_file(s1name).structure
    s2 = Poscar.from_file(s2name).structure
    #    print s1,s2
    smatcher = StructureMatcher(primitive_cell=False)
    res = smatcher.get_transformation(s1, s2)
    print res
def primitive(src="POSCAR"):
    """
    primitiveに変換
    """
    srcpos = Poscar.from_file(src)
    finder = SpacegroupAnalyzer(srcpos.structure)
    prim = finder.get_primitive_standard_structure()
    dstpos = Poscar(prim)
    dst = "POSCAR_prim"
    Cabinet.reserve_file(dst)
    dstpos.write_file(dst)
def ConvertCifFileToPoscarFile(cifFilename,poscarFilename):
  parser = CifParser(cifFilename)
  structure = parser.get_structures()[0]
  structure_name = cif_file.split('.')[0]

  poscar_obj      = Poscar(structure=structure,comment=structure_name)
  poscar_string   = poscar_obj.to_string()
  poscar_filename = '{}/{}.poscar'.format(poscar_directory_name,structure_name)

  with open(poscar_filename,'w') as f:
    f.write(poscar_string)
def refined(src="POSCAR"):
    """
    refined poscar を 作成する
    """
    srcpos = Poscar.from_file(src)
    finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-1, angle_tolerance=8)
    std = finder.get_refined_structure()
    dstpos = Poscar(std)
    dst = "POSCAR_refined"
    Cabinet.reserve_file(dst)
    dstpos.write_file(dst)
def standard(src="POSCAR"):
    """
    standardに変換
    """
    srcpos = Poscar.from_file(src)
    finder = SpacegroupAnalyzer(srcpos.structure)
    std = finder.get_conventional_standard_structure()
    dstpos = Poscar(std)
    dst = "POSCAR_std"
    Cabinet.reserve_file(dst)
    dstpos.write_file(dst)
Example #11
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 == "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 checkrelax_single(path, src_ini="posfinal", src_fin="posfinal3"):
    dirc = path
    initial = Poscar.from_file(os.path.join(dirc, src_ini)).structure.as_dict()["lattice"]
    final = Poscar.from_file(os.path.join(dirc, src_fin)).structure.as_dict()["lattice"]
    length_a = final[u"a"] / initial[u"a"]
    length_b = final[u"b"] / initial[u"b"]
    length_c = final[u"c"] / initial[u"c"]
    delta_length = ((length_b / length_a - 1) ** 2 + (length_c / length_a - 1) ** 2) ** 0.5
    # print(delta_length)
    angle_a = final["alpha"] / initial["alpha"] - 1
    angle_b = final["beta"] / initial["beta"] - 1
    angle_c = final["gamma"] / initial["gamma"] - 1
    delta_angle = (angle_a ** 2 + angle_b ** 2 + angle_c ** 2) ** 0.5
    # print(delta_angle)
    return delta_length, delta_angle
Example #13
0
def supercell(poscar,scale,outFile=None,replace=False):
    '''Reads in a structure in VASP POSCAR format and returns one with a supercell
    of that structure

    Args:
    -------------------------------------
        poscar: location of POSCAR file to find supercell of
        scale: iterable of integer scaling factors with length 3.

    kwargs:
    -------------------------------------
        outFile: location for new poscar file with 

    modifies:
    -------------------------------------
        outFile: if replace=True
        poscar: if replace=False
    '''

    assert os.path.isfile(poscar)
    assert replace==True or not outFile is None

    p = Poscar.from_file(poscar,False)
#     with open(poscar) as f:
#         poscomment = f.readline().strip()
# 
#     p.comment = poscomment
    p.structure.make_supercell(scale)
    if replace==True:
        p.write_file(poscar,vasp4_compatible=True)
    else:
        p.write_file(outFile,vasp4_compatible=True)
Example #14
0
    def strout2poscar(src='str.out'):
        """
        str.outをposcarの記述に変換し, Poscar objをreturn
        """
        with open(src, 'r') as rfile:
            lines = rfile.readlines()
        latt_tmp = [[float(x) for x in y.split()] for y in lines[0:3]]
        trans = [[float(x) for x in y.split()] for y in lines[3:6]]
        sites_tmp = [[float(x) for x in y.split()[0:3]] for y in lines[6:]]
        elements = [x.split()[3].split('+')[0].split('-')[0] for x in lines[6:]]
        num_atoms = [elements.count(e)
                     for e in sorted(set(elements), key=elements.index)]
        latt = np.dot(np.array(trans), np.array(latt_tmp))
        sites = np.dot(np.array(sites_tmp), np.array(latt_tmp))

        posc_str = "posc_orig\n"
        posc_str += "1.00\n"
        posc_str += "\n".join(["  ".join([str(f) for f in l]) for l in latt])
        posc_str += "\n"
        posc_str += "  ".join(sorted(set(elements), key=elements.index)) + "\n"
        posc_str += "  ".join([str(d) for d in num_atoms]) + "\n"
        posc_str += "Cartesian\n"
        posc_str += "\n".join(["  ".join([str(f) for f in s]) for s in sites])

        return Poscar.from_string(posc_str)
Example #15
0
def read_structure(filename):
    """
    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:
            A filename to read from.

    Returns:
        A Structure object.
    """
    fname = os.path.basename(filename)
    if fnmatch(fname.lower(), "*.cif*"):
        parser = CifParser(filename)
        return parser.get_structures(True)[0]
    elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"):
        return Poscar.from_file(filename, False).structure
    elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"):
        return Chgcar.from_file(filename).structure
    elif fnmatch(fname, "vasprun*.xml*"):
        return Vasprun(filename).final_structure
    elif fnmatch(fname.lower(), "*.cssr*"):
        cssr = Cssr.from_file(filename)
        return cssr.structure
    elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
        with zopen(filename) as f:
            s = json.load(f, cls=PMGJSONDecoder)
            if type(s) != Structure:
                raise IOError("File does not contain a valid serialized "
                              "structure")
            return s
    raise ValueError("Unrecognized file extension!")
Example #16
0
    def test_init_from_structure(self):
        filepath = os.path.join(test_dir, "POSCAR")
        poscar = Poscar.from_file(filepath)
        struct = poscar.struct
        xyz = XYZ(struct)
        ans = """24
Fe4 P4 O16
Fe 2.277347 4.550379 2.260125
Fe 2.928536 1.516793 4.639870
Fe 7.483231 4.550379 0.119620
Fe 8.134420 1.516793 2.499364
P 0.985089 1.516793 1.990624
P 4.220794 4.550379 4.370369
P 6.190973 1.516793 0.389120
P 9.426677 4.550379 2.768865
O 0.451582 4.550379 3.365614
O 1.006219 1.516793 3.528306
O 1.725331 0.279529 1.358282
O 1.725331 2.754057 1.358282
O 3.480552 3.313115 3.738027
O 3.480552 5.787643 3.738027
O 4.199665 4.550379 1.148562
O 4.754301 1.516793 0.985870
O 5.657466 4.550379 3.773620
O 6.212102 1.516793 3.610928
O 6.931215 0.279529 1.021463
O 6.931215 2.754057 1.021463
O 8.686436 3.313115 3.401208
O 8.686436 5.787643 3.401208
O 9.405548 4.550379 1.231183
O 9.960184 1.516793 1.393875"""
        self.assertEqual(str(xyz), ans)
Example #17
0
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)
Example #18
0
 def get_structure_from_file(self, myfilepath=""):
     """Get the structure from a specified file path.
         For VASP, this is a POSCAR-type file.
         Args:
             myfilepath <str>: File path for structure.
     """
     return Poscar.from_file(myfilepath).structure
Example #19
0
def read_structure(filename):
    """
    Reads a structure based on file extension. For example, anything ending in
    a "cif" is assumed to be a Crystallographic Information Format file.

    Args:
        filename:
            A filename to read from.

    Returns:
        A Structure object.
    """
    lower_filename = os.path.basename(filename).lower()
    if re.search("\.cif", lower_filename):
        parser = CifParser(filename)
        return parser.get_structures(True)[0]
    elif lower_filename.startswith("poscar") \
            or lower_filename.startswith("contcar"):
        return Poscar.from_file(filename, False).structure
    elif lower_filename.startswith("chgcar") \
            or lower_filename.startswith("locpot"):
        return Chgcar.from_file(filename).structure
    elif re.search("vasprun", lower_filename) \
            and re.search("xml", lower_filename):
        return Vasprun(filename).final_structure
    elif re.search("\.cssr", lower_filename):
        cssr = Cssr.from_file(filename)
        return cssr.structure

    raise ValueError("Unrecognized file extension!")
Example #20
0
 def set_structure_from_inputs(self, input_options):
     """Make a pymatgen structure and update the
         structure key.
         Args:
             input_options <InputOptions>
     """
     strposfile = input_options.get_item('structure','posfile')
     if strposfile is None:
         iopscoords=input_options.get_item('structure','coordinates')
         iopslatt=input_options.get_item('structure','lattice')
         iopsatoms=input_options.get_item('structure','atom_list')
         iopsctype=input_options.get_item('structure','coord_type')
         structure = MAST2Structure(lattice=iopslatt,
             coordinates=iopscoords, atom_list=iopsatoms,
             coord_type=iopsctype)
     elif ('poscar' in strposfile.lower()):
         from pymatgen.io.vaspio import Poscar
         structure = Poscar.from_file(strposfile).structure
     elif ('cif' in strposfile.lower()):
         from pymatgen.io.cifio import CifParser
         structure = CifParser(strposfile).get_structures()[0]
     else:
         error = 'Cannot build structure from file %s' % strposfile
         raise MASTError(self.__class__.__name__, error)
     input_options.update_item('structure','structure',structure)
     if input_options.get_item('structure','use_structure_index') in ['True','true','T','t']:
         self.do_structure_indexing(input_options)
     return
Example #21
0
 def set_structure_from_inputs(self, input_options):
     """Make a pymatgen structure and update the
         structure key.
         Args:
             input_options <InputOptions>
     """
     strposfile = input_options.get_item('structure', 'posfile')
     if strposfile is None:
         iopscoords = input_options.get_item('structure', 'coordinates')
         iopslatt = input_options.get_item('structure', 'lattice')
         iopsatoms = input_options.get_item('structure', 'atom_list')
         iopsctype = input_options.get_item('structure', 'coord_type')
         structure = MAST2Structure(lattice=iopslatt,
                                    coordinates=iopscoords,
                                    atom_list=iopsatoms,
                                    coord_type=iopsctype)
     elif ('poscar' in strposfile.lower()):
         from pymatgen.io.vaspio import Poscar
         structure = Poscar.from_file(strposfile).structure
     elif ('cif' in strposfile.lower()):
         from pymatgen.io.cifio import CifParser
         structure = CifParser(strposfile).get_structures()[0]
     else:
         error = 'Cannot build structure from file %s' % strposfile
         raise MASTError(self.__class__.__name__, error)
     input_options.update_item('structure', 'structure', structure)
     if input_options.get_item('structure', 'use_structure_index') in [
             'True', 'true', 'T', 't'
     ]:
         self.do_structure_indexing(input_options)
     return
def print_spg(src="POSCAR"):
    srcpos = Poscar.from_file(src)
    finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-2, angle_tolerance=8)
    spg = finder.get_spacegroup_symbol()
    spg_num = finder.get_spacegroup_number()
    print(spg)
    print(spg_num)
def five(src="POSCAR"):
    """
    ver5 に変換
    """
    srcpos = Poscar.from_file(src)
    dst = "POSCAR_five"
    srcpos.write_file(dst)
Example #24
0
def read_structure(filename):
    """
    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.

    Returns:
        A Structure object.
    """
    fname = os.path.basename(filename)
    if fnmatch(fname.lower(), "*.cif*"):
        parser = CifParser(filename)
        return parser.get_structures(True)[0]
    elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"):
        return Poscar.from_file(filename, False).structure
    elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"):
        return Chgcar.from_file(filename).structure
    elif fnmatch(fname, "vasprun*.xml*"):
        return Vasprun(filename).final_structure
    elif fnmatch(fname.lower(), "*.cssr*"):
        cssr = Cssr.from_file(filename)
        return cssr.structure
    elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
        with zopen(filename) as f:
            s = json.load(f, cls=PMGJSONDecoder)
            if type(s) != Structure:
                raise IOError("File does not contain a valid serialized "
                              "structure")
            return s
    raise ValueError("Unrecognized file extension!")
Example #25
0
def get_symetry(lines, output):
    latt_tmp = [[float(x) for x in y.split()] for y in lines[0:3]]
    trans = [[float(x) for x in y.split()] for y in lines[3:6]]
    sites = [[float(x) for x in y.split()[0:3]] for y in lines[6:]]
    elements = [x.split()[3] for x in lines[6:]]
    latt = np.dot(np.array(trans),np.array(latt_tmp))
    latt_obj = mg.Lattice(latt)
    structure = mg.Structure(latt, elements, sites)
    finder = SymmetryFinder(structure)
    out = finder.get_spacegroup_symbol() + "\n"
    #structure = finder.find_primitive()
    #structure = finder.get_primitive_standard_structure()
    poscar = Poscar(structure)
    #cif = CifWriter(structure)
    out += poscar.__str__()
    #print(cif)
    return out
Example #26
0
 def test_get_atoms(self):
     if not aio.ase_loaded:
         raise SkipTest("ASE not present. Skipping...")
     p = Poscar.from_file(os.path.join(test_dir, 'POSCAR'))
     structure = p.struct
     atoms = aio.AseAtomsAdaptor.get_atoms(structure)
     ase_composition = Composition.from_formula(atoms.get_name())
     self.assertEqual(ase_composition, structure.composition)
Example #27
0
def get_primitive(fname):
    poscar = Poscar.from_file(fname)

    finder = SymmetryFinder(poscar.structure)
    spg_num = finder.get_spacegroup_number()

    primitive = finder.get_primitive_standard_structure()
    return spg_num, primitive
Example #28
0
def get_elements(src):
    """
    組成比を得るための method
    """
    srcpos = Poscar.from_file(src)
    elements = [x.symbol for x in srcpos.structure.species]
    elem_counter = Counter(elements)
    return elem_counter
    def test_apply_transformations_complete_ranking(self):

        module_dir = os.path.dirname(os.path.abspath(__file__))
        p = Poscar.from_file(os.path.join(module_dir, 'POSCAR.LiFePO4'))
        t1 = OxidationStateDecorationTransformation({"Li":1, "Fe":2, "P":5, "O":-2})
        s = t1.apply_transformation(p.struct)
        t = PartialRemoveSpecieTransformation("Li+", 0.5, PartialRemoveSpecieTransformation.ALGO_COMPLETE)
        self.assertEqual(len(t.apply_transformation(s, 10)), 6)
Example #30
0
    def setUp(self):
        filepath = os.path.join(test_dir, 'POSCAR')
        poscar = Poscar.from_file(filepath)
        self.struct = poscar.struct

        self.mitparamset = MITVaspInputSet()
        self.mithseparamset = MITHSEVaspInputSet()
        self.paramset = MaterialsProjectVaspInputSet()
 def test_to_from_dict(self):
     json_str = json.dumps(PartialRemoveSpecieTransformation("Li+", 0.5, PartialRemoveSpecieTransformation.ALGO_BEST_FIRST).to_dict)
     t = transformation_from_json(json_str)
     module_dir = os.path.dirname(os.path.abspath(__file__))
     p = Poscar.from_file(os.path.join(module_dir, 'POSCAR.LiFePO4'))
     t1 = OxidationStateDecorationTransformation({"Li":1, "Fe":2, "P":5, "O":-2})
     s = t1.apply_transformation(p.struct)
     self.assertEqual(len(t.apply_transformation(s)), 26)
Example #32
0
    def test_init(self):
        filepath = os.path.join(test_dir, 'POSCAR')
        poscar = Poscar.from_file(filepath)
        comp = poscar.struct.composition
        self.assertEqual(comp, Composition.from_formula("Fe4P4O16"))

        #Vasp 4 type with symbols at the end.
        poscar_string = """Test1
1.0
3.840198 0.000000 0.000000
1.920099 3.325710 0.000000
0.000000 -2.217138 3.135509
1 1
direct
0.000000 0.000000 0.000000 Si
0.750000 0.500000 0.750000 F"""
        poscar = Poscar.from_string(poscar_string)
        self.assertEqual(poscar.struct.composition, Composition.from_formula("SiF"))

        #Vasp 4 tyle file with default names, i.e. no element symbol found.
        poscar_string = """Test2
1.0
3.840198 0.000000 0.000000
1.920099 3.325710 0.000000
0.000000 -2.217138 3.135509
1 1
direct
0.000000 0.000000 0.000000
0.750000 0.500000 0.750000"""
        poscar = Poscar.from_string(poscar_string)
        self.assertEqual(poscar.struct.composition, Composition.from_formula("HHe"))

        #Vasp 4 tyle file with default names, i.e. no element symbol found.
        poscar_string = """Test3
1.0
3.840198 0.000000 0.000000
1.920099 3.325710 0.000000
0.000000 -2.217138 3.135509
1 1
Selective dynamics
direct
0.000000 0.000000 0.000000 T T T Si
0.750000 0.500000 0.750000 F F F O"""
        poscar = Poscar.from_string(poscar_string)
        self.assertEqual(poscar.selective_dynamics, [[True, True, True], [False, False, False]])
Example #33
0
 def update_atom_index_for_complete(self):
     """Update atom index files with positions for the 
         completed ingredient.
     """
     proceed=False
     mydir = self.keywords['name']
     workdir=os.path.dirname(mydir)
     sdir=os.path.join(workdir,"structure_index_files")
     if os.path.exists(sdir):
         proceed=True
     if not proceed:
         self.logger.warning("Called update atom index for ingredient %s, but no atom indices exist." % self.keywords['name'])
         return
     mymeta=Metadata(metafile="%s/metadata.txt" % mydir)
     phonon_label = mymeta.read_data("phonon_label")
     if not (phonon_label == None): #Don't update atom indices for phonons
         self.logger.debug("Skipping atom index update for phonon calculation %s" % self.keywords['name'])
         return 
     scaling_label=mymeta.read_data("scaling_label")
     defect_label=mymeta.read_data("defect_label")
     neb_label=mymeta.read_data("neb_label")
     if scaling_label == None:
         scaling_label = ""
     if defect_label == None:
         defect_label = ""
     if neb_label == None:
         neb_label = ""
     if neb_label == "":
         mystr=Poscar.from_file("%s/CONTCAR" % self.keywords["name"]).structure
         ing_label=os.path.basename(mydir)
         manname="manifest_%s_%s_%s" % (scaling_label, defect_label, neb_label)
         myatomindex=AtomIndex(structure_index_directory=sdir)
         myatomindex.update_atom_indices_from_structure(mystr, ing_label, manname)
     else:
         nebdirs = dirutil.immediate_subdirs(self.keywords["name"])
         for mysubdir in nebdirs:
             if os.path.isfile("%s/%s/CONTCAR" % (self.keywords["name"],mysubdir)):
                 mystr=Poscar.from_file("%s/%s/CONTCAR" % (self.keywords["name"], mysubdir)).structure
                 ing_label=os.path.join(os.path.basename(mydir), mysubdir)
                 for defect_label in neb_label.split("-"):
                     manname="manifest_%s_%s_%s" % (scaling_label, defect_label, neb_label)
                     myatomindex=AtomIndex(structure_index_directory=sdir)
                     myatomindex.update_atom_indices_from_structure(mystr, ing_label, manname)
             
     return
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")
Example #35
0
 def _phon_inphon_get_masses(self):
     """Get the ntypes and masses line for INPHON.
         Returns:
             nline, massline
             nline <str>: NYTPES = <number of atomic types in POSCAR>
             massline <str>: MASS = <mass1> <mass2> ...
     """
     name = self.keywords['name']
     if os.path.isfile(name + "/POSCAR_prePHON"):
         mypos = Poscar.from_file(name + "/POSCAR_prePHON")
     else:  #not yet modified to strip out the species line.
         mypos = Poscar.from_file(name + "/POSCAR")
     sitesym = mypos.site_symbols
     nline = "NTYPES=" + str(len(sitesym))
     massline = "MASS="
     for sym in sitesym:
         el = pymatgen.core.periodic_table.Element(sym)
         massline = massline + str(float(el.atomic_mass)) + " "
     return [nline, massline]
Example #36
0
def alt_volume(func, src="POSCAR"):
    """
    体積を変更した POSCAR を作成
    """
    srcpos = Poscar.from_file(src)
    elem = get_elements(src)
    ideal_v = func(elem)
    srcpos.structure.scale_lattice(ideal_v)
    dst = "POSCAR_newvol"
    srcpos.write_file(dst)
Example #37
0
 def get_coordinates_only_structure_from_input(self):
     """Get coordinates-only structures from mast_coordinates
         ingredient keyword
         Args:
             keywords <dict>: ingredient keywords
         Returns:
             coordstrucs <list>: list of Structure objects
     """
     coordposlist = self.keywords['program_keys']['mast_coordinates']
     coordstrucs = list()
     coordstruc = None
     for coordpositem in coordposlist:
         if ('poscar' in os.path.basename(coordpositem).lower()):
             coordstruc = Poscar.from_file(coordpositem).structure
         elif ('cif' in os.path.basename(coordpositem).lower()):
             coordstruc = CifParser(coordpositem).get_structures()[0]
         else:
             error = 'Cannot build structure from file %s' % coordpositem
             raise MASTError(self.__class__.__name__, error)
         coordstrucs.append(coordstruc)
     return coordstrucs
Example #38
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 False.
        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=PMGJSONDecoder)
            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
Example #39
0
 def _phon_poscar_setup(self):
     """Set up a PHON POSCAR file. Strip out the "elements" line (that is,
         use VASP version 4 format. Also strip out anything beneath the atoms
         line.
     """
     name = self.keywords['name']
     pospath = os.path.join(name, "POSCAR")
     prepath = os.path.join(name, "POSCAR_prePHON")
     if os.path.isfile(pospath): #Already done. Return.
         return
     my_poscar = Poscar.from_file(prepath) 
     my_poscar.selective_dynamics=None #unset SD if it is set
     my_poscar.velocities=None #unset velocities
     dirutil.lock_directory(name)
     my_poscar.write_file(pospath)
     dirutil.unlock_directory(name)
     #pick up a copy and strip out the elements line.
     mypfile = MASTFile(pospath)
     myline6=mypfile.get_line_number(6)
     if myline6.strip().split()[0].isalpha:
         mypfile.modify_file_by_line_number(6,"D")
     mypfile.to_file(pospath)
     return
Example #40
0
    def process_killed_run(cls, dir_name):
        """
        Process a killed vasp run.
        """
        fullpath = os.path.abspath(dir_name)
        logger.info("Processing Killed run " + fullpath)
        d = {"dir_name": fullpath, "state": "killed", "oszicar": {}}

        for f in os.listdir(dir_name):
            filename = os.path.join(dir_name, f)
            if fnmatch(f, "INCAR*"):
                try:
                    incar = Incar.from_file(filename)
                    d["incar"] = incar.to_dict
                    d["is_hubbard"] = incar.get("LDAU", False)
                    if d["is_hubbard"]:
                        us = incar.get("LDAUU", [])
                        js = incar.get("LDAUJ", [])
                        if sum(us) == 0 and sum(js) == 0:
                            d["is_hubbard"] = False
                            d["hubbards"] = {}
                    else:
                        d["hubbards"] = {}
                    if d["is_hubbard"]:
                        d["run_type"] = "GGA+U"
                    elif incar.get("LHFCALC", False):
                        d["run_type"] = "HF"
                    else:
                        d["run_type"] = "GGA"
                except Exception as ex:
                    print str(ex)
                    logger.error(
                        "Unable to parse INCAR for killed run {}.".format(
                            dir_name))
            elif fnmatch(f, "KPOINTS*"):
                try:
                    kpoints = Kpoints.from_file(filename)
                    d["kpoints"] = kpoints.to_dict
                except:
                    logger.error(
                        "Unable to parse KPOINTS for killed run {}.".format(
                            dir_name))
            elif fnmatch(f, "POSCAR*"):
                try:
                    s = Poscar.from_file(filename).structure
                    comp = s.composition
                    el_amt = s.composition.get_el_amt_dict()
                    d.update({
                        "unit_cell_formula": comp.to_dict,
                        "reduced_cell_formula": comp.to_reduced_dict,
                        "elements": list(el_amt.keys()),
                        "nelements": len(el_amt),
                        "pretty_formula": comp.reduced_formula,
                        "anonymous_formula": comp.anonymized_formula,
                        "nsites": comp.num_atoms,
                        "chemsys": "-".join(sorted(el_amt.keys()))
                    })
                    d["poscar"] = s.to_dict
                except:
                    logger.error(
                        "Unable to parse POSCAR for killed run {}.".format(
                            dir_name))
            elif fnmatch(f, "POTCAR*"):
                try:
                    potcar = Potcar.from_file(filename)
                    d["pseudo_potential"] = {
                        "functional": "pbe",
                        "pot_type": "paw",
                        "labels": potcar.symbols
                    }
                except:
                    logger.error(
                        "Unable to parse POTCAR for killed run in {}.".format(
                            dir_name))
            elif fnmatch(f, "OSZICAR"):
                try:
                    d["oszicar"]["root"] = \
                        Oszicar(os.path.join(dir_name, f)).to_dict
                except:
                    logger.error(
                        "Unable to parse OSZICAR for killed run in {}.".format(
                            dir_name))
            elif re.match("relax\d", f):
                if os.path.exists(os.path.join(dir_name, f, "OSZICAR")):
                    try:
                        d["oszicar"][f] = Oszicar(
                            os.path.join(dir_name, f, "OSZICAR")).to_dict
                    except:
                        logger.error("Unable to parse OSZICAR for killed "
                                     "run in {}.".format(dir_name))
        return d
Example #41
0
from PathFinder.pathFinder import NEBPathfinder, ChgcarPotential

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-s1', type=str, help='starting point CONTCAR')
    parser.add_argument('-s2', type=str, help='ending point CONTCAR')
    parser.add_argument('-e', type=str, help='diffusing cation')
    parser.add_argument('-n',
                        type=int,
                        default=8,
                        help='number of interpolated images')
    parser.add_argument('-chg', type=str, help='CHGCAR for pathFinder')
    arg = parser.parse_args()

    s1 = Poscar.from_file(arg.s1).structure
    s2 = Poscar.from_file(arg.s2).structure
    chg = Chgcar.from_file(arg.chg)

    relax_sites = []
    for i, site in enumerate(s1.sites):
        if site.specie == Element(arg.e):
            relax_sites.append(i)

    pf = NEBPathfinder(s1,
                       s2,
                       relax_sites=relax_sites,
                       v=ChgcarPotential(chg).get_v(),
                       n_images=(3 * arg.n))

    images = pf.images
Example #42
0
""" Get input data first """ 

parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", help="file with calculation variables",
                    required=True, metavar="FILE")

parser.add_argument("-p", "--parent", help="parent file in vasp POSCAR format",
                    required=True, metavar="FILE")  
                    
args = parser.parse_args()

invars = Conf(args.input)

''' Import initial parent structure '''

poscar = Poscar.from_file(args.parent)
parent_struct = poscar.structure
os.chdir(invars.run_dir)
if invars.restart == ".FALSE.":
    
    with open("ORDERING_OUTPUT.txt", 'a') as file:
    
        file.write("Input Structure Info:\n\n")
        file.write("-------------------------------------------------------------------------------------\n\n")
        file.write("{}\n\n".format(parent_struct))
        file.write("-------------------------------------------------------------------------------------\n\n")

def end_status(status):
    if status == 'success':
        with open("ORDERING_OUTPUT.txt", 'a') as file:
            file.write("Yor job has ended sucessfully\n")
Example #43
0
def main(api="", queryid=""):
    """Get VASP inputs for Materials Project structure
        Args:
            api <str>: Materials Project API key
            queryid <str>: Materials Project ID of the structure
        Returns:
            creates a folder named with that mpid, and including
            some VASP input files.
    """
    if api == "":
        print "Must have an API key from materialsproject.org"
        return None
    if queryid == "":
        print "No MP structure ID given. Exiting."
        return None
    rest_adapter = MPRester(api)
    entries = list()
    proplist = list()
    proplist.append('pretty_formula')
    proplist.append('structure')
    proplist.append('potcar')
    proplist.append('material_id')

    myentry = rest_adapter.mpquery(criteria={'material_id': queryid},
                                   properties=proplist)
    if len(myentry) == 0:
        print "Could not find entry for %s as material_id. Trying entry_id." % queryid
        myentry = rest_adapter.mpquery(criteria={'entry_id': queryid},
                                       properties=proplist)
    if len(myentry) == 0:
        print "Could not find entry for %s" % queryid
        return None
    entries.extend(myentry)

    workdir = os.getcwd()
    from pymatgen.io.vaspio_set import MITVaspInputSet, MPVaspInputSet
    for entry in entries:
        mpvis = MPVaspInputSet()
        myname = str(entry['pretty_formula'])
        #print entry['structure'].composition
        #print entry['structure'].formula
        #myname = entry['pretty_formula']
        myname = myname.replace("(", "_").replace(")", "_")
        myname = myname + "_" + entry['material_id']
        os.mkdir(myname)
        os.chdir(myname)
        mystructure = entry['structure']
        if mystructure.num_sites <= 10:
            mystructure.make_supercell([2, 2, 2])
        #mystructure.perturb(0.01)
        incar = mpvis.get_incar(mystructure)
        incar.write_file("INCAR")
        potcar = mpvis.get_potcar(mystructure)
        potcar.write_file("POTCAR")
        #potcar_symbols = mpvis.get_potcar_symbols(mystructure)
        myposcar = Poscar(mystructure)
        mykpoints = mpvis.get_kpoints(mystructure)
        mykpoints.write_file("KPOINTS")

        myposcar.write_file("POSCAR")
        os.chdir(workdir)
#!/usr/bin/env python

from pymatgen.io.vaspio import Poscar
import cProfile
import pstats
import os
import logging

logging.basicConfig(level=logging.DEBUG)

p = Poscar.from_file("../test_files/POSCAR.LiFePO4", check_for_POTCAR=False)
s = p.structure

def test():
    nn = s.get_all_neighbors(20)
    print len(nn)

def chgcar_test():
    from pymatgen.io.vaspio import Chgcar
    c = Chgcar.from_file("../test_files/CHGCAR.noncubic")
    print c.get_integrated_diff(1, 2.5, 3)

def vasprun_test():
    from pymatgen.io.vaspio import Vasprun
    v = Vasprun("../test_files/vasprun.xml")
    print v.final_energy

def matcher_test():
    p = Poscar.from_file("../test_files/POSCAR.Li2O")
    s = p.structure
    from pymatgen.analysis.structure_matcher import StructureMatcher
def matcher_test():
    p = Poscar.from_file("../test_files/POSCAR.Li2O")
    s = p.structure
    from pymatgen.analysis.structure_matcher import StructureMatcher
    print StructureMatcher().fit(s, s)
        ]
        if len(structures_list) == 0:
            print('no structures found')
            pass
        else:
            file_format = 'cif'
    else:
        file_format = 'poscar'

    isomer_count = {'cis': 0, 'trans': 0, 'fac': 0, 'mer': 0, 'mixed': 0}
    for entry in structures_list:
        struct_name = entry.replace("{}-".format(dictionary), '')
        struct_name = struct_name.replace('.vasp', '')
        #print struct_name
        if file_format == 'poscar':
            poscar = Poscar.from_file(entry)
            struct = poscar.structure
        elif file_format == 'cif':
            parser = CifParser(entry)
            struct = parser.get_structures()[0]
        #cations_indx = [0,3,5,6]
        if len(cations_indx) == 0:
            cations_indx = struct.indices_from_symbol(cati)

        anions_indx = struct.indices_from_symbol(ani)

        cation_neighs = dict()
        ordering_rank = []
        for cation in cations_indx:
            myneigh = []
            for anion in anions_indx: