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)
Exemple #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
         if self.keywords['structure'] is not None:
             my_poscar = Poscar(self.keywords['structure'])
         else:
             pf = os.path.join(os.path.dirname(name),'POSCAR_%s'%os.path.basename(name))
             if os.path.isfile(pf):
                 my_poscar = Poscar.from_file(pf)
         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)
     my_poscar.write_file(pospath)
     dirutil.unlock_directory(name)
     return my_poscar
Exemple #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
Exemple #4
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 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)
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 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)
Exemple #8
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)
Exemple #9
0
 def set_up_neb_folders(self, image_structures):
     """Set up NEB folders.
         Args:
            image_structures <list of Structure>: List
                of image structures
     """
     imct=0
     myname = self.keywords['name']
     if 'mast_coordinates' in self.keywords['program_keys'].keys():
         coordstrucs=self.get_coordinates_only_structure_from_input()
         newstrucs=list()
         sidx = 0 #ex. coordstrucs 0, 1, 2 for 3 images
         while sidx < self.keywords['program_keys']['mast_neb_settings']['images']:
             sxtend = StructureExtensions(struc_work1=image_structures[sidx+1].copy(), name=self.keywords['name'])
             newstrucs.append(sxtend.graft_coordinates_onto_structure(coordstrucs[sidx]))
             sidx = sidx + 1
     while imct < len(image_structures):
         imposcar = Poscar(image_structures[imct])
         num_str = str(imct).zfill(2)
         impath = os.path.join(myname, num_str)
         impospath = os.path.join(myname, "POSCAR_" + num_str)
         if 'mast_coordinates' in self.keywords['program_keys'].keys():
             if imct == 0: #skip endpoint
                 pass 
             elif imct == len(image_structures)-1: #skip other endpt
                 pass
             else:
                 imposcar.structure=newstrucs[imct-1].copy()
         dirutil.lock_directory(myname)
         imposcar.write_file(impospath)
         dirutil.unlock_directory(myname)
         try:
             os.makedirs(impath)
         except OSError:
             self.logger.warning("Directory at %s already exists." % impath)
             return None
         dirutil.lock_directory(impath)
         imposcar.write_file(os.path.join(impath, "POSCAR"))
         dirutil.unlock_directory(impath)
         imct = imct + 1
     return
Exemple #10
0
def produce(irreps):
    os.makedirs('irrep')
    for i, irrep in enumerate(irreps):
        poscar = Poscar(irrep)
        symbols = poscar.site_symbols
        natoms = poscar.natoms
        name_dict = {'Al': 'A', 'Ti': 'B'}
        tmp = ["{0}{1}".format(name_dict[x], y)
               for x, y in zip(symbols, natoms)]
        finder = SymmetryFinder(irrep)
        spg_num = finder.get_spacegroup_number()
        spg = "_".join(finder.get_spacegroup_symbol().split('/'))
        dirname = "No." + "{0:03d}".format(i) + "_" + spg + "_" + "".join(tmp)
        poscar.comment += "    (#" + str(spg_num) + ": " + spg + ")"

        standard = finder.get_conventional_standard_structure()
        stand_pos = Poscar(standard)
        stand_pos.comment += "    (#" + str(spg_num) + ": " + spg + ")"

        os.makedirs(os.path.join('irrep', dirname))
        poscar.write_file(os.path.join('irrep', dirname, 'POSCAR.prim'))
        stand_pos.write_file(os.path.join('irrep', dirname, 'POSCAR.std'))
Exemple #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 = 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)
Exemple #12
0
def scaleCell(path,volume):
    poscar = os.path.join(path,'POSCAR')
    refcar = os.path.join(path,'REFCAR')
    potcar = Potcar()

    assert os.path.isfile(poscar)

    struct = read_structure(poscar)
    struct.scale_lattice(volume)
    species = [ pot.element for pot in potcar.from_file('POTCAR') ]
    reprule = { old:new  for old,new in zip(struct.composition.elements,species) }
    struct.replace_species(reprule)

    p = Poscar(struct)

    with open(poscar) as f:
        poscomment = f.readline().strip()

    p.comment = poscomment
    p.write_file(poscar,vasp4_compatible=True)

    if os.path.isfile(refcar):
        tmp = os.path.join(path,'POSCARtmp')

        # copy Poscar to temporary file and refcar to poscar
        copyfile(poscar,tmp)
        copyfile(refcar,poscar)

        struct = read_structure(poscar)
        struct.scale_lattice(volume)
        species = [ pot.element for pot in potcar.from_file('POTCAR') ]
        reprule = { old:new  for old,new in zip(struct.composition.elements,species) }
        struct.replace_species(reprule)

        r = Poscar(struct)

        with open(poscar) as f:
            poscomment = f.readline().strip()

        r.comment = poscomment
        r.write_file(poscar,vasp4_compatible=True)

        with open(refcar) as f:
            poscomment = f.readline().strip()

        r.comment = poscomment
        r.write_file(refcar,vasp4_compatible=True)

        # replace poscar with its original
        move(tmp,poscar)
    else:
        print 'No REFCAR found.'
Exemple #13
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)
Exemple #14
0
                        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

    for i, image in enumerate(images):
        if i % 3 == 0:
            p = Poscar(image)
            directory = "0" + str(i / 3)
            if not os.path.exists(directory):
                os.makedirs(directory)
            p.write_file("{}/POSCAR".format(directory))
Exemple #15
0
 def write_final_structure_file(self, mystruc):
     """Write the final structure to a file.
         For VASP, this is CONTCAR.
     """
     mycontcar = Poscar(mystruc)
     mycontcar.write_file(os.path.join(self.keywords['name'],'CONTCAR'))
Exemple #16
0
__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)
    
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

    for i, image in enumerate(images):
        if i % 3 == 0:
            p = Poscar(image)
            directory = "0" + str(i/3)
            if not os.path.exists(directory):
                os.makedirs(directory)
            p.write_file("{}/POSCAR".format(directory))