Esempio n. 1
0
 def test_continue(self):
     # Test the continuation functionality
     with cd(os.path.join(test_dir, 'postprocess')):
         # Test default functionality
         with ScratchDir('.', copy_from_current_on_enter=True) as d:
             v = VaspJob("hello", auto_continue=True)
             v.setup()
             self.assertTrue(os.path.exists("continue.json"), "continue.json not created")
             v.setup()
             self.assertEqual(Poscar.from_file("CONTCAR").structure,
                              Poscar.from_file("POSCAR").structure)
             self.assertEqual(Incar.from_file('INCAR')['ISTART'], 1)
             v.postprocess()
             self.assertFalse(os.path.exists("continue.json"),
                              "continue.json not deleted after postprocessing")
         # Test explicit action functionality
         with ScratchDir('.', copy_from_current_on_enter=True) as d:
             v = VaspJob("hello", auto_continue=[{"dict": "INCAR",
                                                  "action": {"_set": {"ISTART": 1}}}])
             v.setup()
             v.setup()
             self.assertNotEqual(Poscar.from_file("CONTCAR").structure,
                                 Poscar.from_file("POSCAR").structure)
             self.assertEqual(Incar.from_file('INCAR')['ISTART'], 1)
             v.postprocess()
Esempio n. 2
0
    def _verify_inputs(self):
        """Validation of input files under user NEB directory."""
        user_incar = Incar.from_file(os.path.join(self.user_dir, "INCAR"))
        ref_incar = Incar.from_file(os.path.join(self.ref_dir_input, "INCAR"))

        # Check INCAR
        params_to_check = self.get("params_to_check", [])
        defaults = {"ICHAIN": 0, "LCLIMB": True}
        for p in params_to_check:
            if user_incar.get(p, defaults.get(p)) != ref_incar.get(p, defaults.get(p)):
                raise ValueError("INCAR value of {} is inconsistent!".format(p))

        # Check KPOINTS
        user_kpoints = Kpoints.from_file(os.path.join(self.user_dir, "KPOINTS"))
        ref_kpoints = Kpoints.from_file(os.path.join(self.ref_dir_input, "KPOINTS"))
        if user_kpoints.style != ref_kpoints.style or user_kpoints.num_kpts != ref_kpoints.num_kpts:
            raise ValueError("KPOINT files are inconsistent! "
                             "Paths are:\n{}\n{} with kpts = {} {}".format(
                self.user_dir, self.ref_dir_input, user_kpoints, ref_kpoints))

        # Check POTCAR
        user_potcar = Potcar.from_file(os.path.join(self.user_dir, "POTCAR"))
        ref_potcar = Potcar.from_file(os.path.join(self.ref_dir_input, "POTCAR"))
        if user_potcar.symbols != ref_potcar.symbols:
            raise ValueError("POTCAR files are inconsistent! "
                             "Paths are:\n{}\n{}".format(self.user_dir, self.ref_dir_input))

        # Check POSCARs
        for u, r in zip(self.user_sdir, self.ref_sdir_input):
            user_poscar = Poscar.from_file(os.path.join(u, "POSCAR"))
            ref_poscar = Poscar.from_file(os.path.join(r, "POSCAR"))
            if user_poscar.natoms != ref_poscar.natoms or \
                            user_poscar.site_symbols != ref_poscar.site_symbols:
                raise ValueError("POSCAR files are inconsistent! Paths are:\n{}\n{}".format(u, r))
Esempio n. 3
0
    def poscar(self):
        """   generating poscar for relaxation calculations   """
        print(
            '--------------------------------------------------------------------------------------------------------'
        )
        print("Generation of VASP files for the cell relaxation:")
        print(
            '--------------------------------------------------------------------------------------------------------'
        )

        self.symData.structure = Structure.from_file(self.args.pos[0])
        sym1 = float(self.args.sympre[0])
        sym2 = float(self.args.symang[0])
        aa = SpacegroupAnalyzer(self.symData.structure,
                                symprec=sym1,
                                angle_tolerance=sym2)
        self.symData.space_group = aa.get_space_group_number()
        print("Space group number =", self.symData.space_group)
        spg = aa.get_space_group_symbol()
        print("Space group symbol =", str(spg))
        self.symData.number_of_species = len(self.symData.structure.species)
        print("Number of atoms = {}".format(len(
            self.symData.structure.species)))

        pos_name = "POSCAR"
        structure00 = Poscar(self.symData.structure)
        structure00.write_file(filename=pos_name, significant_figures=16)

        return self.symData
def write_to_file(invars, collect_structures):
    f = open("{}/ORDERING_OUTPUT.txt".format(invars.run_dir), 'a')
    f.write("Writing new structures to disk\n")
    f.write("-------------------------------------------------------------------------------------\n\n")  
    f.close()
    for entry in collect_structures:
        f = open("{}/ORDERING_OUTPUT.txt".format(invars.run_dir), 'a')
        folder_name = "space_group-No-{}".format(entry)
        
        if os.path.isdir('{}/{}'.format(invars.run_dir, folder_name)):
            f.write("{} directory is already present\n".format(folder_name))
            f.write("Going in to look for files\n")
            current_dir = '{}/{}'.format(invars.run_dir, folder_name)
            
        else:
            f.write("Creating {} directory\n".format(folder_name))
            os.mkdir(folder_name)
            current_dir = "{}/{}".format(invars.run_dir, folder_name)
            
        f.close()
        for i, new_strt in enumerate(collect_structures[entry]):
            
            str_name = "{}-str-{}.vasp".format(folder_name, (i+1))
            
            if os.path.isfile("{}/{}".format(current_dir, str_name)):
                f = open("{}/ORDERING_OUTPUT.txt".format(invars.run_dir), 'a')
                f.write("{} file is already present\n".format(str_name))
                f.close()
                pass
            else:
                
                w = Poscar(new_strt)
                w.write_file("{}/{}".format(current_dir, str_name))
                
            if invars.calc_distort == '.FASLE.':
                pass      
            
            elif invars.calc_distort == '.TRUE.' \
            and os.path.isdir('{}/distortions-str-{}'.format(current_dir, (i+1))) is False:
                
                f = open("{}/ORDERING_OUTPUT.txt".format(invars.run_dir), 'a')
                f.write("Evaluating distortions for {}\n".format(str_name))
                f.write("-------------------------------------------------------------------------------------\n")
                f.write('creating distortions-{} directory\n\n'.format(i+1))
                os.mkdir('{}/distortions-str-{}'.format(current_dir,(i+1)))
                 
                dist_dir = '{}/distortions-str-{}'.format(current_dir,(i+1))
                f.close()                                     
                
                #print distortion_files
                match_atoms(new_strt, invars, dist_dir)
                
            elif invars.calc_distort == '.TRUE.' \
            and os.path.isdir('{}/distortions-str-{}'.format(current_dir, (i+1))) is True:
                f = open("{}/ORDERING_OUTPUT.txt".format(invars.run_dir), 'a')
                f.write('distortions-str-{} directory already present\nGoing in...\n\n'.format(i+1))
                
                dist_dir = '{}/distortions-str-{}'.format(current_dir, (i+1))               
                f.close()
                match_atoms(new_strt, invars, dist_dir)
Esempio n. 5
0
 def test_run_scale(self):
     #raise SkipTest
     ingdir = "%s/writedir/single_label1" % testdir
     recipedir = "%s/writedir" % testdir
     topmetad = MASTFile("files/top_metadata_single")
     topmetad.data.append("origin_dir = %s/files\n" %
                          testdir)  #give origin directory
     topmetad.to_file("writedir/metadata.txt")
     metad = MASTFile("files/metadata_single")
     metad.data.append("defect_label = label1\n")
     metad.data.append("scaling_size = [2,2,2]\n")
     metad.to_file("%s/metadata.txt" % ingdir)
     kdict = dict()
     kdict['mast_program'] = 'vasp'
     my_structure = Poscar.from_file("files/POSCAR_perfect").structure
     myperf = MASTFile("files/POSCAR_perfect")
     myperf.to_file("%s/POSCAR" % ingdir)
     myri = ChopIngredient(name=ingdir,
                           program_keys=kdict,
                           structure=my_structure)
     myri.run_scale()
     my_scaled = Poscar.from_file("%s/CONTCAR" %
                                  ingdir).structure.get_sorted_structure()
     scaled_compare = Poscar.from_file(
         "files/POSCAR_scaled").structure.get_sorted_structure()
     self.assertEquals(my_scaled, scaled_compare)
Esempio n. 6
0
    def test_image_num(self):
        os.path.dirname(os.path.abspath(__file__))
        test_file_dir = os.path.join(PymatgenTest.TEST_FILES_DIR,
                                     "path_finder")
        start_s = Poscar.from_file(os.path.join(test_file_dir,
                                                "LFP_POSCAR_s")).structure
        end_s = Poscar.from_file(os.path.join(test_file_dir,
                                              "LFP_POSCAR_e")).structure
        chg = Chgcar.from_file(os.path.join(test_file_dir, "LFP_CHGCAR.gz"))
        moving_cation_specie = Element("Li")
        relax_sites = []
        for site_i, site in enumerate(start_s.sites):
            if site.specie == moving_cation_specie:
                relax_sites.append(site_i)
        pf = NEBPathfinder(
            start_s,
            end_s,
            relax_sites=relax_sites,
            v=ChgcarPotential(chg).get_v(),
            n_images=(8 * 3),
        )
        images = []
        for i, image in enumerate(pf.images):
            if i % 3 == 0:
                images.append(image)
        self.assertEqual(len(images), 9)

        moving_site = relax_sites[0]
        dists = [
            s1.sites[moving_site].distance(s2.sites[moving_site])
            for s1, s2 in zip(pf.images[:-1], pf.images[1:])
        ]
        # check that all the small distances are about equal
        self.assertTrue(abs(min(dists) - max(dists)) / mean(dists) < 0.02)
Esempio n. 7
0
def vac_antisite_def_struct_gen(c_size=15,
                                mpid="",
                                struct=None,
                                write_file=True):
    """
    Vacancy, antisite generator

    Args:
         c_size: cell size
         struct: Structure object or
         mpid: materials project id
    Returns:
            def_str: defect structures in Poscar object format
    """
    def_str = []
    if struct == None:
        with MPRester() as mp:
            struct = mp.get_structure_by_material_id(mpid)
        if mpid == "":
            print("Provide structure")
    c_size = c_size
    prim_struct_sites = len(struct.sites)
    struct = SpacegroupAnalyzer(struct).get_conventional_standard_structure()
    dim1 = int((float(c_size) / float(max(abs(struct.lattice.matrix[0]))))) + 1
    dim2 = int(float(c_size) / float(max(abs(struct.lattice.matrix[1])))) + 1
    dim3 = int(float(c_size) / float(max(abs(struct.lattice.matrix[2])))) + 1
    cellmax = max(dim1, dim2, dim3)
    conv_struct_sites = len(struct.sites)
    conv_prim_rat = int(conv_struct_sites / prim_struct_sites)
    sc_scale = [dim1, dim2, dim3]
    print("sc_scale", sc_scale)

    tmp = struct.copy()
    tmp.make_supercell(sc_scale)
    sc_tmp = tmp  # Poscar(tmp).structure .make_supercell(list(sc_scale))
    scs = list(VacancyGenerator(struct))
    supercell = Poscar(sc_tmp)
    supercell.comment = str("bulk") + str("@") + str("cellmax") + str(cellmax)
    def_str.append(supercell)
    if write_file == True:
        supercell.write_file("POSCAR-" + str("bulk") + str(".vasp"))

    for i in range(len(scs)):
        sc = scs[i].generate_defect_structure(sc_scale)
        poscar = Poscar(sc)  # mpvis.get_poscar(sc)
        pmg_name = str(scs[i].name).split("_")
        sitespecie = pmg_name[1]
        mult = pmg_name[2].split("mult")[1]
        name = (str("vacancy_") + str(i + 1) + str("_mult-") + str(mult) +
                str("_sitespecie-") + str(sitespecie) + str("@cellmax") +
                str(cellmax))
        poscar.comment = str(name)
        def_str.append(poscar)
        if write_file == True:
            filename = (str("POSCAR-") + str("vacancy_") + str(i + 1) +
                        str("_mult-") + str(mult) + str("_sitespecie-") +
                        str(sitespecie) + str(".vasp"))
            poscar.write_file(filename)

    return def_str
Esempio n. 8
0
    def _verify_inputs(self):
        user_incar = Incar.from_file(os.path.join(os.getcwd(), "INCAR"))
        ref_incar = Incar.from_file(os.path.join(self["ref_dir"], "inputs", "INCAR"))

        # perform some BASIC tests

        # check INCAR
        params_to_check = self.get("params_to_check", [])
        defaults = {"ISPIN": 1, "ISMEAR": 1, "SIGMA": 0.2}
        for p in params_to_check:
            if user_incar.get(p, defaults.get(p)) != ref_incar.get(p, defaults.get(p)):
                raise ValueError("INCAR value of {} is inconsistent!".format(p))

        # check KPOINTS
        user_kpoints = Kpoints.from_file(os.path.join(os.getcwd(), "KPOINTS"))
        ref_kpoints = Kpoints.from_file(os.path.join(self["ref_dir"], "inputs", "KPOINTS"))
        if user_kpoints.style != ref_kpoints.style or user_kpoints.num_kpts != ref_kpoints.num_kpts:
            raise ValueError("KPOINT files are inconsistent! Paths are:\n{}\n{}".format(
                os.getcwd(), os.path.join(self["ref_dir"], "inputs")))

        # check POSCAR
        user_poscar = Poscar.from_file(os.path.join(os.getcwd(), "POSCAR"))
        ref_poscar = Poscar.from_file(os.path.join(self["ref_dir"], "inputs", "POSCAR"))
        if user_poscar.natoms != ref_poscar.natoms or user_poscar.site_symbols != ref_poscar.site_symbols:
            raise ValueError("POSCAR files are inconsistent! Paths are:\n{}\n{}".format(
                os.getcwd(), os.path.join(self["ref_dir"], "inputs")))

        # check POTCAR
        user_potcar = Potcar.from_file(os.path.join(os.getcwd(), "POTCAR"))
        ref_potcar = Potcar.from_file(os.path.join(self["ref_dir"], "inputs", "POTCAR"))
        if user_potcar.symbols != ref_potcar.symbols:
            raise ValueError("POTCAR files are inconsistent! Paths are:\n{}\n{}".format(
                os.getcwd(), os.path.join(self["ref_dir"], "inputs")))
        logger.info("RunVaspFake: verified inputs successfully")
Esempio n. 9
0
    def _verify_inputs(self):
        """Validation of input files under user NEB directory."""
        user_incar = Incar.from_file(os.path.join(self.user_dir, "INCAR"))
        ref_incar = Incar.from_file(os.path.join(self.ref_dir_input, "INCAR"))

        # Check INCAR
        params_to_check = self.get("params_to_check", [])
        defaults = {"ICHAIN": 0, "LCLIMB": True}
        for p in params_to_check:
            if user_incar.get(p, defaults.get(p)) != ref_incar.get(p, defaults.get(p)):
                raise ValueError("INCAR value of {} is inconsistent!".format(p))

        # Check KPOINTS
        user_kpoints = Kpoints.from_file(os.path.join(self.user_dir, "KPOINTS"))
        ref_kpoints = Kpoints.from_file(os.path.join(self.ref_dir_input, "KPOINTS"))
        if user_kpoints.style != ref_kpoints.style or user_kpoints.num_kpts != ref_kpoints.num_kpts:
            raise ValueError("KPOINT files are inconsistent! "
                             "Paths are:\n{}\n{} with kpts = {} {}".format(
                self.user_dir, self.ref_dir_input, user_kpoints, ref_kpoints))

        # Check POTCAR
        user_potcar = Potcar.from_file(os.path.join(self.user_dir, "POTCAR"))
        ref_potcar = Potcar.from_file(os.path.join(self.ref_dir_input, "POTCAR"))
        if user_potcar.symbols != ref_potcar.symbols:
            raise ValueError("POTCAR files are inconsistent! "
                             "Paths are:\n{}\n{}".format(self.user_dir, self.ref_dir_input))

        # Check POSCARs
        for u, r in zip(self.user_sdir, self.ref_sdir_input):
            user_poscar = Poscar.from_file(os.path.join(u, "POSCAR"))
            ref_poscar = Poscar.from_file(os.path.join(r, "POSCAR"))
            if user_poscar.natoms != ref_poscar.natoms or \
                            user_poscar.site_symbols != ref_poscar.site_symbols:
                raise ValueError("POSCAR files are inconsistent! Paths are:\n{}\n{}".format(u, r))
Esempio n. 10
0
def write_structures(structures, file_name):
    import tempfile
    import zipfile
    from os.path import basename, join
    import os
    if len(structures) > 1:
        result_archive = zipfile.ZipFile(join(os.getcwd(),
                                              basename(file_name) + '.zip'),
                                         mode='w')
        for name, structure in structures.items():
            sorted_sites = list(
                sorted(structure.sites.copy(),
                       key=lambda site: site.specie.symbol))
            sorted_structure = Structure.from_sites(sorted_sites)
            with tempfile.NamedTemporaryFile() as tmpfile:
                Poscar(structure=sorted_structure).write_file(tmpfile.name)
                result_archive.write(tmpfile.name,
                                     arcname=basename(file_name) + '-' + name)
        result_archive.close()
        write_message('Archive file: {0}'.format(
            join(os.getcwd(),
                 basename(file_name) + '.zip')),
                      level=DEBUG)
    else:
        #There is just one file write only that one
        structure_key = list(structures.keys())[0]
        sorted_sites = list(
            sorted(structures[structure_key].sites.copy(),
                   key=lambda site: site.specie.symbol))
        sorted_structure = Structure.from_sites(sorted_sites)
        p = Poscar(structure=sorted_structure)
        fname = join(os.getcwd(),
                     basename(file_name) + structure_key + '.vasp')
        p.write_file(fname)
        write_message('Output file: {0}'.format(fname), level=DEBUG)
Esempio n. 11
0
    def test_image_num(self):
        module_dir = os.path.dirname(os.path.abspath(__file__))
        test_file_dir = os.path.join(module_dir, "..", "..", "..", "test_files",
                                     "path_finder")
        start_s = Poscar.from_file(os.path.join(test_file_dir, 'LFP_POSCAR_s')).structure
        end_s = Poscar.from_file(os.path.join(test_file_dir, 'LFP_POSCAR_e')).structure
        mid_s = start_s.interpolate(end_s, nimages=2,
                                       interpolate_lattices=False)[1]
        chg = Chgcar.from_file(os.path.join(test_file_dir, 'LFP_CHGCAR.gz'))
        moving_cation_specie = Element('Li')
        relax_sites = []
        for site_i, site in enumerate(start_s.sites):
            if site.specie == moving_cation_specie:
                relax_sites.append(site_i)
        pf = NEBPathfinder(start_s, end_s, relax_sites=relax_sites,
                           v=ChgcarPotential(chg).get_v(), n_images=(8 * 3))
        images = []
        for i, image in enumerate(pf.images):
            if i % 3 == 0:
                images.append(image)
        self.assertEqual(len(images), 9)

        pf_mid = NEBPathfinder(start_s, end_s, relax_sites=relax_sites,
                           v=ChgcarPotential(chg).get_v(), n_images=10, mid_struct=mid_s)
        moving_site = relax_sites[0]
        dists = [s1.sites[moving_site].distance(s2.sites[moving_site]) 
            for s1, s2 in zip(pf.images[:-1], pf.images[1:])]
        # check that all the small distances are about equal
        self.assertTrue(abs(min(dists)-max(dists))/mean(dists) < 0.02)
Esempio n. 12
0
def mp_id(mpid):
    """
    materials project の ID から POSCAR を作成
    """
    mpr = MPRester("WTxsDhRV7g2Mcbqw")
    strctr = mpr.get_structure_by_material_id(mpid)
    poscar = Poscar(strctr)
    poscar.write_file('POSCAR_{0}'.format(mpid))
Esempio n. 13
0
 def set_up_program_input(self):
     image_structures = self.keywords['program_keys']['mast_neb_settings'][
         'image_structures']
     self.set_up_neb_folders(image_structures)
     self._vasp_kpoints_setup()
     mypotcar = self._vasp_potcar_setup(Poscar(image_structures[0]))
     self._vasp_incar_setup(mypotcar, Poscar(image_structures[0]))
     self._vasp_neb_incar_modify()
     return
Esempio n. 14
0
def std(src='POSCAR'):
    """
    conventional standard cell に変換
    """
    srcpos = Poscar.from_file(src)
    finder = SpacegroupAnalyzer(srcpos.structure)
    std_str = finder.get_conventional_standard_structure()
    dstpos = Poscar(std_str)
    dst = 'POSCAR_std'
    Cabinet.reserve_file(dst)
    dstpos.write_file(dst)
Esempio n. 15
0
def refined(src):
    """
    refined poscar を 作成する
    """
    srcpos = Poscar.from_file(src)
    finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-1, angle_tolerance=8)
    scr_std = finder.get_refined_structure()
    dstpos = Poscar(scr_std)
    dst = "POSCAR_refined"
    Cabinet.reserve_file(dst)
    dstpos.write_file(dst)
Esempio n. 16
0
def prim(src):
    """
    primitive cell に変換
    """
    srcpos = Poscar.from_file(src)
    finder = SpacegroupAnalyzer(srcpos.structure)
    prim_str = finder.get_primitive_standard_structure()
    dstpos = Poscar(prim_str)
    dst = 'POSCAR_prim'
    Cabinet.reserve_file(dst)
    dstpos.write_file(dst)
Esempio n. 17
0
def vac_intl(cellmax=2, mpid='', struct=None):
    """
    Vacancy and interstitial generator

    Args:
        cellmax: maximum cell size
        struct: Structure object
    Returns:
            def_str: defect structures
    """

    if struct == None:
        with MPRester() as mp:
            struct = mp.get_structure_by_material_id(mpid)
        if mpid == '':
            print("Provide structure")
    sg_mat = SpacegroupAnalyzer(struct)
    struct = sg_mat.get_conventional_standard_structure()
    def_str = []
    count = 0
    cell_arr = [cellmax, cellmax, cellmax]
    vac = Vacancy(struct, {}, {})
    for el in list(struct.symbol_set):

        scs = vac.make_supercells_with_defects(cell_arr, el)
        for i in range(len(scs)):
            if i == 0:
                pos = Poscar(scs[i])
                pos.comment = str('bulk') + str('.') + str('cellmax') + str(
                    cellmax)
                if count == 0:
                    def_str.append(pos)
                    count = count + 1
            else:
                pos = Poscar(scs[i])
                pos.comment = str('vac') + str('cellmax') + str(cellmax) + str(
                    '@') + str(vac.get_defectsite_multiplicity(i)) + str(
                        'Element') + str(el)
                if pos not in def_str:
                    def_str.append(pos)
    struct_valrad_eval = ValenceIonicRadiusEvaluator(struct)
    val = struct_valrad_eval.valences
    rad = struct_valrad_eval.radii
    struct_val = val
    struct_rad = rad
    intl = Interstitial(struct, val, rad)

    for el in struct.composition.elements:
        scs = intl.make_supercells_with_defects(cell_arr, el)
        for i in range(1, len(scs)):
            pos = Poscar(scs[i])
            pos.comment = str('intl') + str('cellmax') + str(cellmax) + str(
                '@') + str(intl.get_defectsite_coordination_number(
                    i - 1)) + str('Element') + str(el)
            if pos not in def_str:
                def_str.append(pos)
    print(len(def_str))
    return def_str
Esempio n. 18
0
def refined(src='POSCAR'):
    """
    refined cell を 作成する
    """
    srcpos = Poscar.from_file(src)
    finder = SpacegroupAnalyzer(srcpos.structure,
                                symprec=5e-1, angle_tolerance=8)
    std_str = finder.get_refined_structure()
    dstpos = Poscar(std_str)
    dst = 'POSCAR_refined'
    Cabinet.reserve_file(dst)
    dstpos.write_file(dst)
Esempio n. 19
0
    def _verify_inputs(self):
        user_incar = Incar.from_file(os.path.join(os.getcwd(), "INCAR"))

        # Carry out some BASIC tests.

        # Check INCAR
        if self.get("check_incar", True):
            ref_incar = Incar.from_file(
                os.path.join(self["ref_dir"], "inputs", "INCAR"))
            params_to_check = self.get("params_to_check", [])
            defaults = {"ISPIN": 1, "ISMEAR": 1, "SIGMA": 0.2}
            for p in params_to_check:
                if user_incar.get(p, defaults.get(p)) != ref_incar.get(
                        p, defaults.get(p)):
                    raise ValueError(
                        "INCAR value of {} is inconsistent!".format(p))

        # Check KPOINTS
        if self.get("check_kpoints", True):
            user_kpoints = Kpoints.from_file(
                os.path.join(os.getcwd(), "KPOINTS"))
            ref_kpoints = Kpoints.from_file(
                os.path.join(self["ref_dir"], "inputs", "KPOINTS"))
            if user_kpoints.style != ref_kpoints.style or \
                            user_kpoints.num_kpts != ref_kpoints.num_kpts:
                raise ValueError(
                    "KPOINT files are inconsistent! Paths are:\n{}\n{} with kpoints {} and {}"
                    .format(os.getcwd(), os.path.join(self["ref_dir"],
                                                      "inputs"), user_kpoints,
                            ref_kpoints))

        # Check POSCAR
        if self.get("check_poscar", True):
            user_poscar = Poscar.from_file(os.path.join(os.getcwd(), "POSCAR"))
            ref_poscar = Poscar.from_file(
                os.path.join(self["ref_dir"], "inputs", "POSCAR"))
            if user_poscar.natoms != ref_poscar.natoms or user_poscar.site_symbols != \
                    ref_poscar.site_symbols:
                raise ValueError(
                    "POSCAR files are inconsistent! Paths are:\n{}\n{}".format(
                        os.getcwd(), os.path.join(self["ref_dir"], "inputs")))

        # Check POTCAR
        if self.get("check_potcar", True):
            user_potcar = Potcar.from_file(os.path.join(os.getcwd(), "POTCAR"))
            ref_potcar = Potcar.from_file(
                os.path.join(self["ref_dir"], "inputs", "POTCAR"))
            if user_potcar.symbols != ref_potcar.symbols:
                raise ValueError(
                    "POTCAR files are inconsistent! Paths are:\n{}\n{}".format(
                        os.getcwd(), os.path.join(self["ref_dir"], "inputs")))

        logger.info("RunVaspFake: verified inputs successfully")
Esempio n. 20
0
    def run_task(self, fw_spec):
        structure_dict = fw_spec["structure"]

        if self.get("rescale_volume", False):
            spec_structure = Structure.from_dict(structure_dict)
            scaling_volume = spec_structure.volume * self["rescale_volume"]

            spec_structure.scale_lattice(scaling_volume)
            structure_dict = spec_structure.as_dict()

        _poscar = Poscar(structure_dict)
        _poscar.write_file("POSCAR")
        return FWAction()
Esempio n. 21
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))
Esempio n. 22
0
def surfer(mpid='',
           vacuum=15,
           layers=2,
           mat=None,
           max_index=1,
           write_file=True):
    """
    ASE surface bulder

    Args:
        vacuum: vacuum region
        mat: Structure object
        max_index: maximum miller index
        min_slab_size: minimum slab size

    Returns:
           structures: list of surface Structure objects
    """

    if mat == None:
        with MPRester() as mp:
            mat = mp.get_structure_by_material_id(mpid)
        if mpid == '':
            print('Provide structure')

    sg_mat = SpacegroupAnalyzer(mat)
    mat_cvn = sg_mat.get_conventional_standard_structure()
    mat_cvn.sort()
    indices = get_symmetrically_distinct_miller_indices(mat_cvn, max_index)
    ase_atoms = AseAtomsAdaptor().get_atoms(mat_cvn)

    structures = []
    pos = Poscar(mat_cvn)
    try:
        pos.comment = str('sbulk') + str('@') + str('vac') + str(vacuum) + str(
            '@') + str('layers') + str(layers)
    except:
        pass
    structures.append(pos)
    if write_file == True:
        mat_cvn.to(fmt='poscar',
                   filename=str('POSCAR-') + str('cvn') + str('.vasp'))
    for i in indices:
        ase_slab = surface(ase_atoms, i, layers)
        ase_slab.center(vacuum=vacuum, axis=2)
        slab_pymatgen = AseAtomsAdaptor().get_structure(ase_slab)
        slab_pymatgen.sort()
        surf_name = '_'.join(map(str, i))
        pos = Poscar(slab_pymatgen)
        try:
            pos.comment = str("Surf-") + str(surf_name) + str('@') + str(
                'vac') + str(vacuum) + str('@') + str('layers') + str(layers)
        except:
            pass
        if write_file == True:
            pos.write_file(filename=str('POSCAR-') + str("Surf-") +
                           str(surf_name) + str('.vasp'))
        structures.append(pos)

    return structures
Esempio n. 23
0
 def poscar_direct_to_cart(self,
                           inputFilePath,
                           outputFilePath,
                           vasp4Compatible=False):
     """
     TODO: replace default python file io with monty.io
     """
     noDecimals = 6
     direct = False
     crystalStruc = Structure.from_file(inputFilePath)
     poscarFile = Poscar(crystalStruc)
     poscarString = poscarFile.get_string(direct, vasp4Compatible,
                                          noDecimals)
     with open(outputFilePath, "w") as f:
         f.write(poscarString)
Esempio n. 24
0
    def setUpClass(cls):
        if not os.environ.get("VASP_PSP_DIR"):
            os.environ["VASP_PSP_DIR"] = os.path.join(module_dir,
                                                      "reference_files")
            print(
                'Note: This system is not set up to run VASP jobs. '
                'Please set your VASP_PSP_DIR environment variable.')

        cls.struct_si = PymatgenTest.get_structure("Si")

        cls.ref_incar = Incar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test", "INCAR"))
        cls.ref_poscar = Poscar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "POSCAR"))
        cls.ref_potcar = Potcar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "POTCAR"))
        cls.ref_kpoints = Kpoints.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "KPOINTS"))
        cls.ref_incar_preserve = Incar.from_file(os.path.join(module_dir,
                                                              "reference_files",
                                                              "preserve_incar",
                                                              "INCAR"))
Esempio n. 25
0
    def run_task(self, fw_spec):

        transformations = []
        transformation_params = self.get("transformation_params",
                                         [{} for i in range(len(self["transformations"]))])
        for t in self["transformations"]:
            found = False
            for m in ["advanced_transformations", "defect_transformations",
                      "site_transformations", "standard_transformations"]:
                mod = import_module("pymatgen.transformations.{}".format(m))
                try:
                    t_cls = getattr(mod, t)
                except AttributeError:
                    continue
                t_obj = t_cls(**transformation_params.pop(0))
                transformations.append(t_obj)
                found = True
            if not found:
                raise ValueError("Could not find transformation: {}".format(t))
        
        # TODO: @matk86 - should prev_calc_dir use CONTCAR instead of POSCAR? Note that if
        # current dir, maybe it is POSCAR indeed best ... -computron
        structure = self['structure'] if not self.get('prev_calc_dir', None) else \
                Poscar.from_file(os.path.join(self['prev_calc_dir'], 'POSCAR')).structure
        ts = TransformedStructure(structure)
        transmuter = StandardTransmuter([ts], transformations)
        final_structure = transmuter.transformed_structures[-1].final_structure.copy()
        vis_orig = self["vasp_input_set"]
        vis_dict = vis_orig.as_dict()
        vis_dict["structure"] = final_structure.as_dict()
        vis_dict.update(self.get("override_default_vasp_params", {}) or {})
        vis = vis_orig.__class__.from_dict(vis_dict)
        vis.write_input(".")
Esempio n. 26
0
 def __init__(self,
              user_input,
              make_supercell=False,
              supercell_matrix=None,
              isdope=False,
              dopant=None):
     """
     Args:
         input: the POSCAR file of initial structure, or the material_id
     """
     self.make_supercell = make_supercell
     self.supercell_matrix = supercell_matrix
     self.isdope = isdope
     self.dopant = dopant
     # if user_input is a path where store the POSCAR file
     if (os.path.isfile(user_input)):
         pos = Poscar.from_file(user_input)
         struc = SpacegroupAnalyzer(pos.structure)
         self.init_struc = struc.get_conventional_standard_structure()
     # user_input is a mp_id
     else:
         prim_struc = mpr.get_structure_by_material_id(user_input)
         struc = SpacegroupAnalyzer(prim_struc)
         self.init_struc = struc.get_conventional_standard_structure()
     self.formula = str(self.init_struc.composition.reduced_formula)
     logging.info("self.formula: {}".format(self.formula))
Esempio n. 27
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'Rotate a bond (Stone-Wales defect) of a fullerene stored in a POSCAR file.',
    )
    parser.add_argument(
        'INPUT',
        help='POSCAR where all atoms use an image from the same molecule.')
    parser.add_argument('ATOM1',
                        type=int,
                        help='0-based index of first bonded atom')
    parser.add_argument('ATOM2',
                        type=int,
                        help='0-based index of second bonded atom')
    args = parser.parse_args()

    from pymatgen.io.vasp import Poscar
    from pymatgen.core import Structure
    poscar = Poscar.from_file(args.INPUT)
    structure = poscar.structure

    cart_coords = structure.cart_coords
    cart_coords = rotate_bond(cart_coords, args.ATOM1, args.ATOM2)
    poscar.structure = Structure(structure.lattice,
                                 structure.species,
                                 cart_coords,
                                 coords_are_cartesian=True)

    print(poscar.get_string(significant_figures=16), end='')
Esempio n. 28
0
    def setUp(self):
        struc = PymatgenTest.get_structure("VO2")
        struc.make_supercell(3)
        struc = struc
        self.vac = Vacancy(struc, struc.sites[0], charge=-3)

        abc = self.vac.bulk_structure.lattice.abc
        axisdata = [np.arange(0.0, lattval, 0.2) for lattval in abc]
        bldata = [np.array([1.0 for u in np.arange(0.0, lattval, 0.2)]) for lattval in abc]
        dldata = [
            np.array([(-1 - np.cos(2 * np.pi * u / lattval)) for u in np.arange(0.0, lattval, 0.2)]) for lattval in abc
        ]
        self.frey_params = {
            "axis_grid": axisdata,
            "bulk_planar_averages": bldata,
            "defect_planar_averages": dldata,
            "dielectric": 15,
            "initial_defect_structure": struc.copy(),
            "defect_frac_sc_coords": struc.sites[0].frac_coords[:],
        }

        kumagai_bulk_struc = Poscar.from_file(
            os.path.join(PymatgenTest.TEST_FILES_DIR, "defect", "CONTCAR_bulk")
        ).structure
        bulk_out = Outcar(os.path.join(PymatgenTest.TEST_FILES_DIR, "defect", "OUTCAR_bulk.gz"))
        defect_out = Outcar(os.path.join(PymatgenTest.TEST_FILES_DIR, "defect", "OUTCAR_vac_Ga_-3.gz"))
        self.kumagai_vac = Vacancy(kumagai_bulk_struc, kumagai_bulk_struc.sites[0], charge=-3)
        kumagai_defect_structure = self.kumagai_vac.generate_defect_structure()
        self.kumagai_params = {
            "bulk_atomic_site_averages": bulk_out.electrostatic_potential,
            "defect_atomic_site_averages": defect_out.electrostatic_potential,
            "site_matching_indices": [[ind, ind - 1] for ind in range(len(kumagai_bulk_struc))],
            "defect_frac_sc_coords": [0.0, 0.0, 0.0],
            "initial_defect_structure": kumagai_defect_structure,
            "dielectric": 18.118 * np.identity(3),
            "gamma": 0.153156,  # not neccessary to load gamma, but speeds up unit test
        }

        v = Vasprun(os.path.join(PymatgenTest.TEST_FILES_DIR, "vasprun.xml"))
        eigenvalues = v.eigenvalues.copy()
        kptweights = v.actual_kpoints_weights
        potalign = -0.1
        vbm = v.eigenvalue_band_properties[2]
        cbm = v.eigenvalue_band_properties[1]
        self.bandfill_params = {
            "eigenvalues": eigenvalues,
            "kpoint_weights": kptweights,
            "potalign": potalign,
            "vbm": vbm,
            "cbm": cbm,
        }

        self.band_edge_params = {
            "hybrid_cbm": 1.0,
            "hybrid_vbm": -1.0,
            "vbm": -0.5,
            "cbm": 0.6,
            "num_hole_vbm": 1.0,
            "num_elec_cbm": 1.0,
        }
Esempio n. 29
0
 def test_run_subfolders(self):
     #raise SkipTest
     ingdir="%s/writedir/single_label1" % testdir
     recipedir="%s/writedir" % testdir
     topmetad = MASTFile("files/top_metadata_single")
     topmetad.data.append("origin_dir = %s/files\n" % testdir) #give origin directory
     topmetad.to_file("writedir/metadata.txt")
     metad = MASTFile("files/metadata_single")
     metad.to_file("%s/metadata.txt" % ingdir)
     kdict=dict()
     kdict['mast_program'] = 'vasp'
     kdict['mast_kpoints'] = [2,2,2,"M"]
     kdict['mast_xc'] = 'pw91'
     my_structure = Poscar.from_file("files/perfect_structure").structure
     for subfolder in ['sub1','sub2','sub3','sub4']:
         subname = "%s/%s" % (ingdir, subfolder)
         os.mkdir(subname)
         shutil.copy("files/metadata_single","%s/metadata.txt" % subname)
         mywr = ChopIngredient(name=subname, program_keys = kdict, structure=my_structure)
         mywr.write_singlerun()
     myri = ChopIngredient(name=ingdir,program_keys=kdict, structure=my_structure)
     myri.run_subfolders()
     self.assertFalse(myri.checker.is_ready_to_run())
     for subfolder in ['sub1','sub2','sub3','sub4']:
         subname = "%s/%s" % (ingdir, subfolder)
         myri.checker.keywords['name'] = subname
         self.assertTrue(myri.checker.is_ready_to_run())
     mysubmit = MASTFile("%s/submitlist" % self.test_control)
     self.assertEquals(mysubmit.data[0], "%s/sub1\n" % ingdir)
     self.assertEquals(mysubmit.data[1], "%s/sub2\n" % ingdir)
     self.assertEquals(mysubmit.data[2], "%s/sub3\n" % ingdir)
     self.assertEquals(mysubmit.data[3], "%s/sub4\n" % ingdir)
Esempio n. 30
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, "wt") as f:
            f.write(str2unicode(json.dumps(structure, cls=MontyEncoder)))
            return
    else:
        raise ValueError("Unrecognized file extension!")

    writer.write_file(filename)
Esempio n. 31
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)
Esempio n. 32
0
    def run_task(self, fw_spec):

        transformations = []
        transformation_params = self.get("transformation_params", [{} for i in range(len(self["transformations"]))])
        for t in self["transformations"]:
            for m in [
                "advanced_transformations",
                "defect_transformations",
                "site_transformations",
                "standard_transformations",
            ]:
                mod = import_module("pymatgen.transformations.{}".format(m))
                try:
                    t_cls = getattr(mod, t)
                except AttributeError:
                    continue
                t_obj = t_cls(**transformation_params.pop(0))
                transformations.append(t_obj)

        structure = (
            self["structure"]
            if "prev_calc_dir" not in self
            else Poscar.from_file(os.path.join(self["prev_calc_dir"], "POSCAR")).structure
        )
        ts = TransformedStructure(structure)
        transmuter = StandardTransmuter([ts], transformations)
        final_structure = transmuter.transformed_structures[-1].final_structure.copy()

        vis_orig = self["vasp_input_set"]
        vis_dict = vis_orig.as_dict()
        vis_dict["structure"] = final_structure.as_dict()
        vis_dict.update(self.get("override_default_vasp_params", {}) or {})
        vis = vis_orig.__class__.from_dict(vis_dict)
        vis.write_input(".")
Esempio n. 33
0
 def test_run_singlerun(self):
     #raise SkipTest
     ingdir = "%s/writedir/single_label1" % testdir
     recipedir = "%s/writedir" % testdir
     topmetad = MASTFile("files/top_metadata_single")
     topmetad.data.append("origin_dir = %s/files\n" %
                          testdir)  #give origin directory
     topmetad.to_file("writedir/metadata.txt")
     metad = MASTFile("files/metadata_single")
     metad.to_file("%s/metadata.txt" % ingdir)
     kdict = dict()
     kdict['mast_program'] = 'vasp'
     kdict['mast_kpoints'] = [2, 2, 2, "M"]
     kdict['mast_xc'] = 'pw91'
     my_structure = Poscar.from_file("files/perfect_structure").structure
     mywr = ChopIngredient(name=ingdir,
                           program_keys=kdict,
                           structure=my_structure)
     mywr.write_singlerun()
     myri = ChopIngredient(name=ingdir,
                           program_keys=kdict,
                           structure=my_structure)
     myri.run_singlerun()
     self.assertTrue(myri.checker.is_ready_to_run())
     mysubmit = MASTFile("%s/submitlist" % self.test_control)
     self.assertEquals(mysubmit.data[0], "%s\n" % ingdir)
Esempio n. 34
0
def parse_wf_for_latt_constants(wf_id):
    lpad = LaunchPad().from_file(lpad_file_path)

    wf = lpad.get_wf_by_fw_id(wf_id)

    lattdata = {}
    print('{} workflow retrieved with {} fws in it'.format(
        wf.name, len(wf.fws)))
    for fw in wf.fws:
        print('\t{}'.format(fw.name))
        if 'structure optimization' not in fw.name:
            raise ValueError("Not a recognized firework!")
        elif fw.state != 'COMPLETED':
            print('\t\tstatus = {}, so skipping'.format(fw.state))
            continue

        pat = fw.launches[-1].launch_dir
        s = Poscar.from_file(os.path.join(pat, 'CONTCAR.relax2.gz')).structure
        nom = s.composition.reduced_formula
        if nom in lattdata:
            raise ValueError("{} already exists in lattdata??".format(nom))
        elif (max(s.lattice.abc) - min(s.lattice.abc)) > 0.00001 or (
                max(s.lattice.angles) - min(s.lattice.angles)) > 0.00001:
            raise ValueError("Error occured with lattice relaxation??".format(
                s.lattice))
        else:
            lattdata.update({nom: s.lattice.abc[0]})

    print('\nFinalized lattice constant set:\n{}'.format(lattdata))

    return lattdata
Esempio n. 35
0
def hacky_struct2pmg(struct):
   """ convert ASE structure to pymatgen structure 
       this is not natively implemented in ASE
   """
   from ase.io import write
   from pymatgen.io.cif import CifParser # this didn't give supercell structure
   from pymatgen.io.vasp import Poscar
   write("POSCAR.tmp",struct,format="vasp")
  
   # fix formatting of the outputted vasp format, which has misplaced species labels
   # this is a hacky way to insert it in the right line
   f = open("POSCAR.tmp","r")
   lines = []
   for i,line in enumerate(f):
      if i == 0:
        species_line = line
      elif i == 5:
        lines.append(species_line)
      lines.append(line)
   f.close()
   with open("POSCAR",'w') as f:
     f.writelines(lines)  


   poscar = Poscar.from_file("POSCAR")
   structure = poscar.structure
   subprocess.call(["rm", "POSCAR","POSCAR.tmp"])

   return structure   
Esempio n. 36
0
    def testEntry(self):
        entries = []
        for i, f in enumerate(self.iter_path):
            vi = VaspInput.from_directory(f)
            ls = LabeledSystem(os.path.join(f, 'OUTCAR'))
            attrib = loadfn(os.path.join(f, 'job.json'))
            comp = vi['POSCAR'].structure.composition
            entry = Entry(comp,
                          'vasp',
                          vi.as_dict(),
                          ls.as_dict(),
                          entry_id='pku-' + str(i),
                          attribute=attrib)
            entries.append(entry)
        self.assertEqual(len(entries), len(self.ref_entries))
        ret0 = entries[0]
        r0 = self.ref_entries[0]
        self.assertEqual(Incar.from_dict(ret0.inputs['INCAR']),
                         Incar.from_dict(r0.inputs['INCAR']))
        self.assertEqual(str(r0.inputs['KPOINTS']),
                         str(Kpoints.from_dict(ret0.inputs['KPOINTS'])))

        self.assertEqual(ret0.inputs['POTCAR'], r0.inputs['POTCAR'].as_dict())
        self.assertEqual(
            Poscar.from_dict(ret0.inputs['POSCAR']).structure,
            r0.inputs['POSCAR'].structure)
        self.assertEqual(ret0.entry_id, 'pku-0')
Esempio n. 37
0
    def run_task(self, fw_spec):

        transformations = []
        transformation_params = self.get(
            "transformation_params",
            [{} for i in range(len(self["transformations"]))])
        for t in self["transformations"]:
            for m in [
                    "advanced_transformations", "defect_transformations",
                    "site_transformations", "standard_transformations"
            ]:
                mod = __import__("pymatgen.transformations." + m, globals(),
                                 locals(), [t], -1)
                try:
                    t_cls = getattr(mod, t)
                except AttributeError:
                    continue
                t_obj = t_cls(**transformation_params.pop(0))
                transformations.append(t_obj)

        structure = self['structure'] if 'prev_calc_dir' not in self else \
                Poscar.from_file(os.path.join(self['prev_calc_dir'], 'POSCAR')).structure
        ts = TransformedStructure(structure)
        transmuter = StandardTransmuter([ts], transformations)
        final_structure = transmuter.transformed_structures[
            -1].final_structure.copy()

        vis_orig = self["vasp_input_set"]
        vis_dict = vis_orig.as_dict()
        vis_dict["structure"] = final_structure.as_dict()
        vis_dict.update(self.get("override_default_vasp_params", {}) or {})
        vis = vis_orig.__class__.from_dict(vis_dict)
        vis.write_input(".")
Esempio n. 38
0
 def test_arrhenius(self):
     poscar = Poscar.from_file(os.path.join(test_dir, 'arrhenius/POSCAR'))
     struct = poscar.structure
     aa = ArreheniusAnalyzer.from_csv(
         os.path.join(test_dir, 'arrhenius/D_T.csv'))
     temperature = 300
     specie_string = 'Li+'
     self.assertAlmostEqual(get_conversion_factor(struct, specie_string,
                                                  temperature),
                            158701249.73192352,
                            places=5)
     self.assertAlmostEqual(aa.Ea, 0.258128283041, places=5)
     self.assertAlmostEqual(aa.Ea_error, 0.0168320198494, places=5)
     self.assertAlmostEqual(aa.predict_conductivity(temperature, struct,
                                                    specie_string)[0],
                            1.08036514392,
                            places=5)
     self.assertAlmostEqual(aa.predict_conductivity(temperature, struct,
                                                    specie_string)[1][0],
                            0.54509683117599272,
                            places=5)
     self.assertAlmostEqual(aa.predict_conductivity(temperature, struct,
                                                    specie_string)[1][1],
                            2.1412504667878154,
                            places=5)
     self.assertAlmostEqual(aa.predict_diffusivity(temperature)[0],
                            6.80754024147e-09,
                            places=5)
Esempio n. 39
0
    def run_task(self, fw_spec):

        transformations = []
        transformation_params = self.get("transformation_params",
                                         [{} for i in range(len(self["transformations"]))])
        for t in self["transformations"]:
            found = False
            for m in ["advanced_transformations", "defect_transformations",
                      "site_transformations", "standard_transformations"]:
                mod = import_module("pymatgen.transformations.{}".format(m))
                try:
                    t_cls = getattr(mod, t)
                except AttributeError:
                    continue
                t_obj = t_cls(**transformation_params.pop(0))
                transformations.append(t_obj)
                found = True
            if not found:
                raise ValueError("Could not find transformation: {}".format(t))

        # TODO: @matk86 - should prev_calc_dir use CONTCAR instead of POSCAR? Note that if
        # current dir, maybe it is POSCAR indeed best ... -computron
        structure = self['structure'] if not self.get('prev_calc_dir', None) else \
            Poscar.from_file(os.path.join(self['prev_calc_dir'], 'POSCAR')).structure
        ts = TransformedStructure(structure)
        transmuter = StandardTransmuter([ts], transformations)
        final_structure = transmuter.transformed_structures[-1].final_structure.copy()
        vis_orig = self["vasp_input_set"]
        vis_dict = vis_orig.as_dict()
        vis_dict["structure"] = final_structure.as_dict()
        vis_dict.update(self.get("override_default_vasp_params", {}) or {})
        vis = vis_orig.__class__.from_dict(vis_dict)
        vis.write_input(".")

        dumpfn(transmuter.transformed_structures[-1], "transformations.json")
Esempio n. 40
0
    def full_opt_run(cls, vasp_cmd, auto_npar=True, vol_change_tol=0.05,
                     max_steps=10):
        """
        Returns a generator of jobs for a full optimization run. Basically,
        this runs an infinite series of geometry optimization jobs until the
        % vol change in a particular optimization is less than vol_change_tol.

        Args:
            vasp_cmd (str): Command to run vasp as a list of args. For example,
                if you are using mpirun, it can be something like
                ["mpirun", "pvasp.5.2.11"]
            auto_npar (bool): Whether to automatically tune NPAR to be sqrt(
                number of cores) as recommended by VASP for DFT calculations.
                Generally, this results in significant speedups. Defaults to
                True. Set to False for HF, GW and RPA calculations.
            vol_change_tol (float): The tolerance at which to stop a run.
                Defaults to 0.05, i.e., 5%.
            max_steps (int): The maximum number of runs. Defaults to 10 (
                highly unlikely that this limit is ever reached).

        Returns:
            Generator of jobs.
        """
        for i in xrange(max_steps):
            if i == 0:
                settings = None
                backup = True
            else:
                backup = False
                initial = Poscar.from_file("POSCAR").structure
                final = Poscar.from_file("CONTCAR").structure
                vol_change = (final.volume - initial.volume) / initial.volume

                logging.info("Vol change = %.1f %%!" % (vol_change * 100))
                if abs(vol_change) < vol_change_tol:
                    logging.info("Stopping optimization!")
                    break
                else:
                    settings = [
                        {"dict": "INCAR",
                         "action": {"_set": {"ISTART": 1}}},
                        {"file": "CONTCAR",
                         "action": {"_file_copy": {"dest": "POSCAR"}}}]
            logging.info("Generating job = %d!" % (i+1))
            yield VaspJob(vasp_cmd, final=False, backup=backup,
                          suffix=".relax%d" % (i+1), auto_npar=auto_npar,
                          settings_override=settings)
Esempio n. 41
0
def data_from_outcars_in_folder(folder):
    initLogging()
    if not os.path.exists(config['data_load_file']):
        different_energies = []
        different_structures = []
        poscar = Poscar.from_file(folder + '/POSCAR')
        logging.info('Assigned Spin values Energy Unique energy FilePath')
        for outcar_file in sorted(glob.glob(folder + '/OUTCAR*')):
            structure = poscar.structure.copy()
            magnetic_element_index = [
                n for n, e in enumerate(structure)
                if e.species_string in config['magnetic_elements']
            ]
            magnetic_substructure = Structure.from_sites([
                e for e in structure
                if e.species_string in config['magnetic_elements']
            ])
            outcar = Outcar(outcar_file)
            try:
                magnetization = np.array([
                    entry['tot'] for entry in outcar.magnetization
                ])[magnetic_element_index]
            except IndexError:
                logging.info(f'Bad OUTCAR: {outcar_file}')
                continue
            spins = np.zeros_like(magnetization)
            for i, m in enumerate(magnetization):
                spins[i] = np.sign(m) * config['spin_values'][i]
                #if abs(m) > config['spin_threshold']:
                #    spins[i] = config['spin_value'] * np.sign(m)
            magnetic_substructure.add_spin_by_site(spins)
            magnetic_substructure.vasp_energy = outcar.final_energy
            magnetic_substructure.name = outcar_file.split('/')[-1]
            isUnique = False
            if is_unique(different_energies, magnetic_substructure.vasp_energy,
                         1e-15):
                different_energies.append(magnetic_substructure.vasp_energy)
                isUnique = True
                different_structures.append(magnetic_substructure)
            #energy_checked = np.round(magnetic_substructure.vasp_energy, decimals=3)
            #if not np.in1d(energy_checked, different_energies).any():
            #    different_energies.append(energy_checked)
            #    isUnique = True
            #    different_structures.append(magnetic_substructure)
            logging.info((spins, magnetic_substructure.vasp_energy, isUnique,
                          outcar_file))
        logging.info(
            f'Data reading complete, saving to {config["data_load_file"]}')
        with open(config['data_load_file'], 'wb') as f:
            pickle.dump(different_structures, f)
        logging.info('Data load complete. Rerun script')
        import sys
        sys.exit()
    else:
        with open(config['data_load_file'], 'rb') as f:
            different_structures = pickle.load(f)
            for s in different_structures:
                logging.info(s.vasp_energy)
    return different_structures
Esempio n. 42
0
def five(src):
    """
    VASP ver.5 のフォーマットに変換
    元素名を 5 行目に追加
    """
    srcpos = Poscar.from_file(src)
    dst = "POSCAR_five"
    srcpos.write_file(dst)
Esempio n. 43
0
def ver5(src='POSCAR'):
    """
    ver 5 の形式に変換
    (POTCAR を読んで元素名を追加)
    """
    srcpos = Poscar.from_file(src)
    dst = 'POSCAR_five'
    srcpos.write_file(dst)
Esempio n. 44
0
    def setUpClass(cls):
        cls.struct_si = PymatgenTest.get_structure("Si")

        cls.ref_incar = Incar.from_file(p_setup_test / "INCAR")
        cls.ref_poscar = Poscar.from_file(p_setup_test / "POSCAR")
        cls.ref_potcar = Potcar.from_file(p_setup_test / "POTCAR")
        cls.ref_kpoints = Kpoints.from_file(p_setup_test / "KPOINTS")
        cls.ref_incar_preserve = Incar.from_file(p_preserve_incar / "INCAR")
Esempio n. 45
0
 def _verify_files(self):
     self.assertEqual(Incar.from_file(os.path.join(module_dir, "INCAR")), self.ref_incar)
     self.assertEqual(str(Poscar.from_file(os.path.join(module_dir, "POSCAR"))),
                      str(self.ref_poscar))
     self.assertEqual(Potcar.from_file(os.path.join(module_dir, "POTCAR")).symbols,
                      self.ref_potcar.symbols)
     self.assertEqual(str(Kpoints.from_file(os.path.join(module_dir, "KPOINTS"))),
                      str(self.ref_kpoints))
Esempio n. 46
0
def get_elements(src):
    """
    元素ラベルを出力
    """
    srcpos = Poscar.from_file(src)
    elements = [x.symbol for x in srcpos.structure.species]
    elem_counter = Counter(elements)
    return elem_counter
Esempio n. 47
0
 def _parse_structure(self, structure_schema):
     data = structure_schema['data']
     format = structure_schema['format']
     if format == 'cif':
         structure = (CifParser.from_string(data)).get_structures()[0]
     elif format == 'POSCAR':
         structure = (Poscar.from_string(data)).structure
     return structure
Esempio n. 48
0
 def check(self):
     try:
         oszicar = Oszicar(self.output_filename)
         n = len(Poscar.from_file(self.input_filename).structure)
         max_dE = max([s['dE'] for s in oszicar.ionic_steps[1:]]) / n
         if max_dE > self.dE_threshold:
             return True
     except:
         return False
 def _verify_files(self, skip_kpoints=False, preserve_incar=False):
     if not preserve_incar:
         self.assertEqual(Incar.from_file(os.path.join(module_dir, "INCAR")), self.ref_incar)
         self.assertEqual(str(Poscar.from_file(os.path.join(module_dir, "POSCAR"))), str(self.ref_poscar))
         self.assertEqual((Potcar.from_file(os.path.join(module_dir, "POTCAR"))).symbols, self.ref_potcar.symbols)
         if not skip_kpoints:
             self.assertEqual(str(Kpoints.from_file(os.path.join(module_dir, "KPOINTS"))), str(self.ref_kpoints))
     else:
         self.assertEqual(Incar.from_file(os.path.join(module_dir, "INCAR")), self.ref_incar_preserve)
Esempio n. 50
0
def cif(src):
    """
    cifファイルを作成
    """
    srcpos = Poscar.from_file(src)
    finder = SpacegroupAnalyzer(srcpos.structure)
    std_str = finder.get_conventional_standard_structure()
    std_cif = CifWriter(std_str, symprec=0.1)
    std_cif.write_file("poscar.cif")
Esempio n. 51
0
def checkrelax_single(path, src_ini="posfinal", src_fin="posfinal3"):
    """
    緩和で構造が歪んでいないかを check
    """
    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
Esempio n. 52
0
def get_structure(filename):
    if filename.lower().endswith('.cif'):
        structure = CifParser(filename).get_structures()[0]
        lattice = pmg.Lattice.from_parameters(*structure.lattice.abc, *structure.lattice.angles)
        return pmg.Structure(lattice, structure.species, structure.frac_coords, coords_are_cartesian=False)
    elif filename.lower().endswith('poscar'):
        return Poscar.from_file(filename).structure
    else:
        raise ValueError('Cannot determine file type from filename [.cif, poscar]')
Esempio n. 53
0
def cif(src='POSCAR'):
    """
    cifファイルを作成
    """
    srcpos = Poscar.from_file(src)
    finder = SpacegroupAnalyzer(srcpos.structure)
    std_str = finder.get_conventional_standard_structure()
    cif_obj = CifWriter(std_str, symprec=0.1)
    cif_obj.write_file('poscar.cif')
Esempio n. 54
0
def print_spg(src):
    """
    space group を表示する
    """
    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)
Esempio n. 55
0
 def print_spg(src='POSCAR'):
     """
     space group を return
     """
     srcpos = Poscar.from_file(src)
     finder = SpacegroupAnalyzer(srcpos.structure,
                                 symprec=5e-2, angle_tolerance=8)
     spg = finder.get_space_group_symbol()
     spg_num = finder.get_space_group_number()
     return spg, spg_num
Esempio n. 56
0
 def test_image_num(self):
     module_dir = os.path.dirname(os.path.abspath(__file__))
     test_file_dir = os.path.join(module_dir, "..", "..", "..", "test_files",
                                  "path_finder")
     start_s = Poscar.from_file(os.path.join(test_file_dir, 'LFP_POSCAR_s')).structure
     end_s = Poscar.from_file(os.path.join(test_file_dir, 'LFP_POSCAR_e')).structure
     chg = Chgcar.from_file(os.path.join(test_file_dir, 'LFP_CHGCAR.gz'))
     moving_cation_specie = Element('Li')
     relax_sites = []
     for site_i, site in enumerate(start_s.sites):
         if site.specie == moving_cation_specie:
             relax_sites.append(site_i)
     pf = NEBPathfinder(start_s, end_s, relax_sites=relax_sites,
                        v=ChgcarPotential(chg).get_v(), n_images=(8 * 3))
     images = []
     for i, image in enumerate(pf.images):
         if i % 3 == 0:
             images.append(image)
     self.assertEqual(len(images), 9)
Esempio n. 57
0
    def of_poscar(cls, poscar_path, initial_pressure=0.0, initial_temperature=1000.0,
                         target_pressure=0.0, target_temperature=1000.0,
                         alpha=10e-5, beta=10e-7):
        """
        Convenience constructor that accepts a poscar file as input

        """
        poscar = Poscar.from_file(poscar_path)
        return cls(poscar.structure, initial_pressure=initial_pressure, initial_temperature=initial_temperature,
                         target_pressure=target_pressure, target_temperature=target_temperature,
                         alpha=alpha, beta=beta, poscar=poscar)
Esempio n. 58
0
 def test_run_neb_subfolders(self):
     #raise SkipTest
     ingdir="%s/writedir/neb_labelinit-labelfin_stat" % testdir
     recipedir="%s/writedir" % testdir
     topmetad = MASTFile("files/top_metadata_neb")
     topmetad.data.append("origin_dir = %s/files\n" % testdir) #give origin directory
     topmetad.to_file("writedir/metadata.txt")
     metad = MASTFile("files/metadata_neb")
     metad.to_file("%s/metadata.txt" % ingdir)
     kdict=dict()
     kdict['mast_program'] = 'vasp'
     kdict['mast_kpoints'] = [2,2,2,"M"]
     kdict['mast_xc'] = 'pw91'
     neblines = list()
     neblines.append(["Cr","0.0 0.9 0.8","0.0 0.8 0.7"])
     neblines.append(["Cr","0.4 0.2 0.1","0.3 0.3 0.2"])
     neblines.append(["Cr","0.29 0.05 0.05","0.01 0.01 0.98"])
     neblines.append(["Ni","0.61 0.99 0.98","0.25 0.01 0.97"])
     kdict['mast_neb_settings']=dict()
     kdict['mast_neb_settings']['lines']=neblines
     kdict['mast_neb_settings']['images']=3
     str_00 = MASTFile("files/POSCAR_00")
     str_00.to_file("%s/parent_structure_labelinit" % ingdir) 
     str_04 = MASTFile("files/POSCAR_04")
     str_04.to_file("%s/parent_structure_labelfin" % ingdir) 
     str_01 = MASTFile("files/POSCAR_01")
     str_01.to_file("%s/parent_structure_labelinit-labelfin_01" % ingdir) 
     str_02 = MASTFile("files/POSCAR_02")
     str_02.to_file("%s/parent_structure_labelinit-labelfin_02" % ingdir) 
     str_03 = MASTFile("files/POSCAR_03")
     str_03.to_file("%s/parent_structure_labelinit-labelfin_03" % ingdir) 
     en_00 = MASTFile("files/OSZICAR_00")
     en_00.to_file("%s/parent_energy_labelinit" % ingdir) 
     en_04 = MASTFile("files/OSZICAR_04")
     en_04.to_file("%s/parent_energy_labelfin" % ingdir) 
     my_structure = Poscar.from_file("files/perfect_structure").structure
     mywr = ChopIngredient(name=ingdir, program_keys = kdict, structure=my_structure)
     mywr.write_neb_subfolders()
     myri = ChopIngredient(name=ingdir,program_keys=kdict, structure=my_structure)
     myri.run_neb_subfolders()
     mysubmit = MASTFile("%s/submitlist" % self.test_control)
     myri.checker.keywords['name'] = "%s/00" % ingdir
     self.assertFalse(myri.checker.is_ready_to_run()) #do not run endpoints again
     myri.checker.keywords['name'] = "%s/01" % ingdir
     self.assertTrue(myri.checker.is_ready_to_run())
     myri.checker.keywords['name'] = "%s/02" % ingdir
     self.assertTrue(myri.checker.is_ready_to_run())
     myri.checker.keywords['name'] = "%s/03" % ingdir
     self.assertTrue(myri.checker.is_ready_to_run())
     myri.checker.keywords['name'] = "%s/04" % ingdir
     self.assertFalse(myri.checker.is_ready_to_run()) #do not run endpoints again
     self.assertEquals(mysubmit.data[0], "%s/01\n" % ingdir)
     self.assertEquals(mysubmit.data[1], "%s/02\n" % ingdir)
     self.assertEquals(mysubmit.data[2], "%s/03\n" % ingdir)
Esempio n. 59
0
 def _parse_structure(self, structure_schema):
     data = structure_schema['data']
     format = structure_schema['format']
     if format == 'cif':
         # cif lattice can be weird non standard shape
         structure = (CifParser.from_string(data)).get_structures()[0]
         lattice = pmg.Lattice.from_parameters(*structure.lattice.abc, *structure.lattice.angles)
         structure = pmg.Structure(lattice, structure.species, structure.frac_coords, coords_are_cartesian=False)
     elif format == 'POSCAR':
         structure = (Poscar.from_string(data)).structure
     return structure