Exemplo n.º 1
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
Exemplo n.º 2
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
Exemplo n.º 3
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)
Exemplo n.º 4
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
Exemplo n.º 5
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
Exemplo n.º 6
0
def pmg_surfer(mpid='', vacuum=15, mat=None, max_index=1, min_slab_size=15):
    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('size') + str(min_slab_size)
    except:
        pass
    structures.append(pos)
    mat_cvn.to(fmt='poscar',
               filename=str('POSCAR-') + str('cvn') + str('.vasp'))
    for i in indices:
        slab = SlabGenerator(initial_structure=mat_cvn,
                             miller_index=i,
                             min_slab_size=min_slab_size,
                             min_vacuum_size=vacuum,
                             lll_reduce=False,
                             center_slab=True,
                             primitive=False).get_slab()
        normal_slab = slab.get_orthogonal_c_slab()
        slab_pymatgen = Poscar(normal_slab).structure
        #ase_slab.center(vacuum=vacuum, axis=2)
        #slab_pymatgen = AseAtomsAdaptor().get_structure(ase_slab)
        xy_size = min_slab_size
        dim1 = int((float(xy_size) /
                    float(max(abs(slab_pymatgen.lattice.matrix[0]))))) + 1
        dim2 = int(
            float(xy_size) /
            float(max(abs(slab_pymatgen.lattice.matrix[1])))) + 1
        slab_pymatgen.make_supercell([dim1, dim2, 1])
        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('size') + str(
                    min_slab_size)
        except:
            pass
        pos.write_file(filename=str('POSCAR-') + str("Surf-") +
                       str(surf_name) + str('.vasp'))
        structures.append(pos)

    return structures
Exemplo n.º 7
0
def surfer(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:
        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
Exemplo n.º 8
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)
Exemplo n.º 10
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)
Exemplo n.º 11
0
    def _write_vasp_files(self, supercell, dir_name):
        import os
        cwd = os.getcwd()
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)

        os.chdir(cwd + '/' + dir_name)
        from pymatgen.io.vasp import Poscar
        Poscar(supercell.get_sorted_structure()).write_file('POSCAR')
        os.chdir(cwd)
Exemplo n.º 12
0
    def export_structure(self, filename, fileformat='poscar'):
        """export incar"""
        atomNames = self.values["name_array"]
        latt = self.values["finalpos"]["basis"]
        pos = self.values["finalpos"]["positions"]

        struc = Structure(latt, atomNames, pos)

        if fileformat == 'poscar':
            Poscar(struc).write_file(filename=filename)
        else:
            CifWriter(struc, symprec=0.01).write_file(filename)
def test_get_defect_charge_state(tmpdir):
    tmpdir.chdir()
    structure = Structure(Lattice.cubic(10), ["H", "He"],
                          [[0.0] * 3, [0.5] * 3])
    fake_potcar_str = """ PAW_PBE H 15Jun2001                    
   1.00000000000000     
 parameters from PSCTR are:
   VRHFIN =H: ultrasoft test
   LEXCH  = PE
   TITEL  = PAW_PBE H 15Jun2001
   POMASS =    1.000; ZVAL   =    1.000    mass and valenz
   ENMAX  =  250.000; ENMIN  =  200.000 eV

   END of PSCTR-controll parameters
 End of Dataset
      PAW_PBE He_pv 15Jun2001                    
   1.00000000000000     
 parameters from PSCTR are:
   VRHFIN =He: ultrasoft test
   LEXCH  = PE
   TITEL  = PAW_PBE He_pv 15Jun2001
   POMASS =    1.000; ZVAL   =    1.000    mass and valenz
   ENMAX  =  250.000; ENMIN  =  200.000 eV

   END of PSCTR-controll parameters
 End of Dataset
 """
    Path("POTCAR").write_text(fake_potcar_str)
    potcar = Potcar.from_file("POTCAR")
    incar = Incar.from_string("NELECT = 1")
    assert get_defect_charge_state(Poscar(structure), potcar, incar) == 2 - 1

    structure = Structure(Lattice.cubic(10), ["H", "He", "H", "H"],
                          [[0.0] * 3, [0.2] * 3, [0.4] * 3, [0.6] * 3])
    with pytest.raises(ValueError):
        get_defect_charge_state(Poscar(structure), potcar, incar)

    incar = Incar.from_string("")
    assert get_defect_charge_state(Poscar(structure), potcar, incar) == 0
Exemplo n.º 14
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()
Exemplo n.º 15
0
def convert_fmt(args):
    iformat = args.input_format[0]
    oformat = args.output_format[0]
    filename = args.input_filename[0]
    out_filename = args.output_filename[0]

    try:

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

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

    except Exception as ex:
        print("Error converting file. Are they in the right format?")
        print(str(ex))
Exemplo n.º 16
0
def light_weight_vol_text(volumetric_data: VolumetricData,
                          border_fractions: List[float] = None):
    data = np.zeros(prod(volumetric_data.dim), dtype=int)
    normalized_values = (volumetric_data.data["total"]
                         / np.max(volumetric_data.data["total"])) + _minor

    border_fractions = border_fractions or default_border_fractions
    for border in border_fractions:
        # transpose needed as vasp is based on column measure (Fortran)
        data += (normalized_values > border).T.flatten()

    lines = [Poscar(volumetric_data.structure).get_string(),
             " ".join([str(d) for d in volumetric_data.dim]),
             " ".join(data.astype(str))]
    return "\n".join(lines)
Exemplo n.º 17
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)
Exemplo n.º 18
0
    def energy(self, spch_config):
        """ Calculate total energy of the space charge model"""

        structure = spch_config.structure.get_sorted_structure()

        # if len(spinel_config.calc_history) >= 20:
        #    print("truncate calc_history")
        #    del spinel_config.calc_history[0:10]
        # calc_history = spinel_config.calc_history
        # if calc_history:
        #    # Try to avoid doing dft calculation for the same structure.
        #    # Assuming that calc_history is a list of ComputedStructureEntries
        #    for i in range(len(calc_history)):
        #        if self.matcher.fit(structure, calc_history[i].structure):
        #            print("match found in history")
        #            return calc_history[i].energy
        # print("before poscar")
        if self.selective_dynamics:
            seldyn_arr = [[True, True, True] for i in range(len(structure))]
            for specie in self.selective_dynamics:
                indices = structure.indices_from_symbol(specie)
                for i in indices:
                    seldyn_arr[i] = [False, False, False]
        else:
            seldyn_arr = None

        poscar = Poscar(structure=structure, selective_dynamics=seldyn_arr)
        # print("before vaspinput")
        vaspinput = self.base_vaspinput
        vaspinput.update({"POSCAR": poscar})
        exitcode = self.vasp_run.submit(vaspinput, os.getcwd() + "/output")
        # print("vasp exited with exit code", exitcode)
        if exitcode != 0:
            print("something went wrong")
            sys.exit(1)
        queen = BorgQueen(self.drone)
        # print(os.getcwd())
        queen.serial_assimilate("./output")
        # print(queen.get_data())
        # results = self.queen.get_data()[-1]
        results = queen.get_data()[-1]
        # calc_history.append(results)
        spch_config.structure = results.structure
        # print(results.energy)
        # sys.stdout.flush()

        return np.float64(results.energy)
Exemplo n.º 19
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)
         self.write_poscar_with_zero_velocities(imposcar, 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)
         self.write_poscar_with_zero_velocities(
             imposcar, os.path.join(impath, "POSCAR"))
         dirutil.unlock_directory(impath)
         imct = imct + 1
     return
Exemplo n.º 20
0
    def to_dir(self, path):
        from pymatgen.io.vasp import Poscar

        os.makedirs(path, exist_ok=True)
        Poscar(self.structure).write_file(self.poscar_path(path),
                                          significant_figures=15)

        meta = {
            'layers': self.layers,
            'masses': self.masses,
        }
        if self.layer_sc_matrices is not None:
            meta['layer-sc-matrices'] = [{
                'matrix': m,
                'repeats': r
            } for (m, r) in zip(self.layer_sc_matrices, self.layer_sc_repeats)]
        with open(self.meta_path(path), 'w') as f:
            json.dump(meta, f)
Exemplo n.º 21
0
def print_all_types(straining = False):
    from pymatgen.io.vasp import Poscar
    sclass = PerfectPerovskite()

    for stype in allowed_struct_type:

        if straining:
            strained = StrainedPerovskite.generate_random_strain(sclass, structure_type=stype,
                                                                 max_strain=0.06, perturb_amnt=None)
            s = strained.structure
            print('\n\n--->', stype)
            print('\tstrain = ', strained.strain_tensor)
            print('\tpert = ', strained.atomic_perturbations)
        else:
            s = sclass.get_struct_from_structure_type(stype)

        Poscar(s).write_file('POSCAR'+str(stype))

    return
Exemplo n.º 22
0
    def energy(self, HAp_config, save_history=False):
        """ Calculate total energy of the space charge model"""

        structure = HAp_config.structure.get_sorted_structure()
        if save_history and self.matcher != None:
            calc_history = HAp_config.calc_history
            # Try to avoid doing dft calculation for the same structure.
            # Assuming that calc_history is a list of ComputedStructureEntries
            for i in range(len(calc_history)):
                if self.matcher.fit(structure, calc_history[i].structure0):
                    print("match found in history")
                    return calc_history[i].energy

        if self.selective_dynamics:
            seldyn_arr = [[True, True, True] for i in range(len(structure))]
            for specie in self.selective_dynamics:
                indices = structure.indices_from_symbol(specie)
                for i in indices:
                    seldyn_arr[i] = [False, False, False]
        else:
            seldyn_arr = None

        poscar = Poscar(structure=structure, selective_dynamics=seldyn_arr)
        vaspinput = self.base_vaspinput
        vaspinput.update({"POSCAR": poscar})
        exitcode = self.vasp_run.submit(vaspinput, os.getcwd() + "/output")
        if exitcode != 0:
            print("something went wrong")
            sys.exit(1)
        queen = BorgQueen(self.drone)
        queen.serial_assimilate("./output")
        results = queen.get_data()[-1]

        if save_history:
            results.structure0 = HAp_config.structure
            HAp_config.calc_history.append(results)

        HAp_config.structure = results.structure
        return np.float64(results.energy)
Exemplo n.º 23
0
def constrain(structs, fnames, atom_index, in_str=" "):
    #len(structs)==1
    mlog.debug("len(structs): {} ".format(len(structs)))
    mlog.debug("fnames: {} ".format(fnames[0]))
    for struct, fname in zip(structs, fnames):
        mlog.debug(fname)
        mlog.debug(struct)
        natom = struct.num_sites
        selective_dynamics = [[True for col in range(3)]
                              for row in range(natom)]
        for i in range(natom):
            if i in atom_index:
                selective_dynamics[i] = [False, False, False]
        tmp_struct = Structure(
            struct.lattice,
            struct.species,
            struct.frac_coords,
            site_properties={'selective_dynamics': selective_dynamics})
        poscar = Poscar(tmp_struct)
        poscar.comment = poscar.comment + ' |--> ' + in_str
        filename = 'Fixed_' + fname + '.vasp'
        poscar.write_file(filename)
Exemplo n.º 24
0
        ccopy = copy.copy(trans_nomode)
        species = ccopy.species
        subs = ccopy.frac_coords

        for atom in range(0, len(subby)):
            for coord in range(0, 3):
                subs[atom][coord] = subby[atom][
                    coord] * interval * increment + nm_coords[atom][coord]

        # Add displacement to zero modes structure
        index = range(0, len(species))
        for i in index:
            ccopy.replace(i, species[i], coords=subs[i])

        # Export to POSCAR
        struct = Poscar(ccopy)
        value = increment * 100 * interval
        struct.write_file(output_path + "/%s_%s%%.vasp" %
                          (mode_filename, value))  #e.g. 'Y2+_100%'

if numberomodes == 2:
    for interval2 in range(0, intervals + 1):
        for interval in range(0, intervals + 1):
            ccopy = copy.copy(trans_nomode)
            species = ccopy.species
            subs = ccopy.frac_coords

            for atom in range(0, len(subby)):
                for coord in range(0, 3):
                    subs[atom][coord] = subby[atom][
                        coord] * interval * increment + subby2[atom][
Exemplo n.º 25
0
# This initializes the REST adaptor. Put your own API key in.
from pymatgen import MPRester
from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter
from pymatgen.io.vasp import Poscar

a = MPRester("")

# Entries are the basic unit for thermodynamic and other analyses in pymatgen.
# This gets all entries belonging to the mp-48 material.
entry = a.get_entry_by_material_id(
    "mp-48",
    inc_structure=True,
    property_data=["material_id", "energy", "energy_per_atom", "volume"])

#print(entry)

structure = entry.structure

#print(structure)

p = Poscar(structure)

print(p)
Exemplo n.º 26
0
    'ISMEAR': 0,
    'SIGMA': 0.05,
    'GGA': 'PE',
    'ENCUT': '280.00 eV',
    'MAGMOM': '6*0.0',
    'NBANDS': 24,
}

larray = array([[0,.5,.5],
                [.5,0,.5],
                [.5,.5,0]])
lattice = Lattice(larray * 6.058)
species = ['In', 'As']
coords = [[0,0,0],[.25,.25,.25]]
structure = Structure(lattice, species, coords, coords_are_cartesian=False)
poscar = Poscar(structure, 'fcc InAs').as_dict()

#~ potcar = Potcar.from_file(sys.argv[2]).as_dict()
from os.path import abspath
potcar = abspath(sys.argv[2])

kpoints = {
    'comment': 'fcc InAs - selfconsistent',
    'generation_style': 'Gamma',
    'kpoints': [[8,8,8]],
    'usershift': [0,0,0],
}

code = Code.get_from_string('vasp')
calc = code.new_calc()
Exemplo n.º 27
0
    def write_file(self,file_name,data_type,vasp4_compatible=False):
        """
        Write the VolumetricData object to a vasp compatible file.

        Args:
            file_name (str): Path to a file
            vasp4_compatible (bool): True if the format is vasp4 compatible
        """

        def _print_fortran_float(f):
            """
            Fortran codes print floats with a leading zero in scientific
            notation. When writing CHGCAR files, we adopt this convention
            to ensure written CHGCAR files are byte-to-byte identical to
            their input files as far as possible.
            :param f: float
            :return: str
            """
            s = "{:.10E}".format(f)
            if f > 0:
                return "0."+s[0]+s[2:12]+'E'+"{:+03}".format(int(s[13:])+1)
            else:
                return "-."+s[1]+s[3:13]+'E'+"{:+03}".format(int(s[14:])+1)

        with zopen(file_name, "wt") as f:
            p = Poscar(self.structure)

            # use original name if it's been set (e.g. from Chgcar)
            comment = getattr(self, 'name', p.comment)

            lines = comment + "\n"
            lines += "   1.00000000000000\n"
            latt = self.structure.lattice.matrix
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[0, :])
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[1, :])
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[2, :])
            if not vasp4_compatible:
                lines += "".join(["%5s" % s for s in p.site_symbols]) + "\n"
            lines += "".join(["%6d" % x for x in p.natoms]) + "\n"
            lines += "Direct\n"
            for site in self.structure:
                lines += "%10.6f%10.6f%10.6f\n" % tuple(site.frac_coords)
            lines += " \n"
            f.write(lines)
            a = self.dim

            def write_spin(data_type):
                lines = []
                count = 0
                f.write("   {}   {}   {}\n".format(a[0], a[1], a[2]))
                for (k, j, i) in itertools.product(list(range(a[2])),
                                                   list(range(a[1])),
                                                   list(range(a[0]))):
                    lines.append(_print_fortran_float(self.data[data_type][i, j, k]))
                    count += 1
                    if count % 5 == 0:
                        f.write(" " + "".join(lines) + "\n")
                        lines = []
                    else:
                        lines.append(" ")
                f.write(" " + "".join(lines) + " \n")
#                f.write("".join(self.data_aug.get(data_type, [])))
            write_spin(data_type)
Exemplo n.º 28
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
    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)
    prim_struct_sites = len(struct.sites)
    struct = SpacegroupAnalyzer(struct).get_conventional_standard_structure()
    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)

    struct_valrad_eval = ValenceIonicRadiusEvaluator(struct)
    val = struct_valrad_eval.valences
    rad = struct_valrad_eval.radii
    struct_val = val
    struct_rad = rad

    vac = Vacancy(struct, {}, {})
    scs = vac.make_supercells_with_defects(sc_scale)

    for i in range(len(scs)):
        sc = scs[i]
        poscar = Poscar(sc)  #mpvis.get_poscar(sc)

        interdir = mpid
        if not i:
            fin_dir = os.path.join(interdir, 'bulk')
            poscar.comment = str('bulk') + str('@') + str('cellmax') + str(
                cellmax)
            def_str.append(poscar)
            if write_file == True:
                poscar.write_file('POSCAR-' + str('bulk') + str(".vasp"))
        else:
            blk_str_sites = set(scs[0].sites)
            vac_str_sites = set(sc.sites)
            vac_sites = blk_str_sites - vac_str_sites
            vac_site = list(vac_sites)[0]
            site_mult = int(
                vac.get_defectsite_multiplicity(i - 1) / conv_prim_rat)
            vac_site_specie = vac_site.specie
            vac_symbol = vac_site.specie.symbol

            vac_dir = 'vacancy_{}_mult-{}_sitespecie-{}'.format(
                str(i), site_mult, vac_symbol)
            fin_dir = os.path.join(interdir, vac_dir)
            try:
                poscar.comment = str(vac_dir) + str('@') + str(
                    'cellmax') + str(cellmax)
            except:
                pass
            pos = poscar
            def_str.append(pos)
            if write_file == True:
                poscar.write_file('POSCAR-' + str(vac_dir) + str(".vasp"))
            struct_species = scs[0].types_of_specie
            for specie in set(struct_species) - set([vac_site_specie]):
                subspecie_symbol = specie.symbol
                anti_struct = sc.copy()
                anti_struct.append(specie, vac_site.frac_coords)

                poscar = Poscar(anti_struct)
                as_dir = 'antisite_{}_mult-{}_sitespecie-{}_subspecie-{}'.format(
                    str(i), site_mult, vac_symbol, subspecie_symbol)
                fin_dir = os.path.join(interdir, as_dir)
                poscar.comment = str(as_dir) + str('@') + str('cellmax') + str(
                    cellmax)
                pos = poscar
                def_str.append(pos)
                if write_file == True:
                    poscar.write_file('POSCAR-' + str(as_dir) + str(".vasp"))

    return def_str
Exemplo n.º 29
0
# Number of parameters (Whether it is Substitution or Remove)
num_parameter = len(sys.argv)

# devsky adds time to file name
now = datetime.datetime.now()
nowDatetime = now.strftime('%Y%m%d%H%M%S%f')

# jaesung adds error handling code
flag = True

if condition == "supercell":
    scale_array = ast.literal_eval(sys.argv[4])
    scaled_structure = structure * scale_array
    if scaled_structure.num_sites <= 200:
        poscar_structure = Poscar(scaled_structure)
    else:
        flag = False
        poscar_structure = Poscar(structure)

elif condition == "substitution":
    if num_parameter == 6:  # Substitution
        FROM = Element(str(sys.argv[4]))
        TO = Element(str(sys.argv[5]))
        FROMTO = dict()
        FROMTO[FROM] = TO
        structure.replace_species(FROMTO)

    elif num_parameter == 5:  # Remove or Add
        FROM = str(sys.argv[4])
def match_atoms(str1, invars, dist_dir):
    f = open("{}/ORDERING_OUTPUT.txt".format(invars.run_dir), 'a')
    distortion_files = os.listdir(invars.distortion_directory)
    f.write("distortion\t\tSpace group #\n")
    f.write(
        "-------------------------------------------------------------------------------------\n"
    )
    for filename in distortion_files:
        poscar = Poscar.from_file(("{}/{}").format(invars.distortion_directory,
                                                   filename))
        str2 = poscar.structure

        new_coords = []
        for i, posi1 in enumerate(str1.cart_coords):
            distance = 1e100
            coord_holder = []
            bounds = np.array(str1.lattice.abc)
            for j, posi2 in enumerate(str2.cart_coords):
                min_dists = np.min(np.dstack(
                    ((np.array(posi1) - np.array(posi2)) % bounds,
                     (np.array(posi2) - np.array(posi1)) % bounds)),
                                   axis=2)
                dists = np.sqrt(np.sum(min_dists**2, axis=1))

                if dists < distance:
                    distance = dists
                    coord_holder = str2.frac_coords[j]

            new_coords = np.append(new_coords, coord_holder)
        new_coords = new_coords.reshape(str1.num_sites, 3)
        # Arrange atoms in a list that matches the list of the a0a0a0 structure
        distorted_structure = Structure(str1.lattice, str1.species, new_coords)
        space_group = int(
            SpacegroupAnalyzer(distorted_structure,
                               invars.symprec).get_space_group_number())
        str_name = "{}-SG-{}.vasp".format(filename, space_group)
        if os.path.isfile(str_name):
            f.write("{}\t\t\t{}\n".format(filename, space_group))

        else:
            f.write("{}\t\t\t{}\n".format(filename, space_group))
            w = Poscar(distorted_structure)
            w.write_file("{}/{}".format(dist_dir, str_name))

        #f.write("\n")
    f.write(
        "-------------------------------------------------------------------------------------\n"
    )
    f.write(
        "-------------------------------------------------------------------------------------\n"
    )
    f.close()
    #lattice = Lattice.from_parameters(a=str1.basis_vectors[0][0], b=str1.basis_vectors[1][1], c=str1.basis_vectors[2][2], alpha=90,beta=90,gamma=90)

    #rot_X_new_coords = np.dot(new_coords, X_cell_rotation())
    #print "New Coords original"
    #print new_coords
    #print "rotated in X new Coords"
    #print rot_X_new_coords
    #all_permut_of_str.append(Structure(lattice, str1.species, rot_X_new_coords))

    #all_permut_of_str.append(structure_x_rot)

    #rot_Y_new_coords = np.dot(new_coords, Y_cell_rotation())
    #all_permut_of_str.append(Structure(lattice, str1.species, rot_Y_new_coords))

    #rot_Z_new_coords = np.dot(new_coords, Z_cell_rotation())

    #all_permut_of_str.append(Structure(lattice, str1.species, rot_Z_new_coords))

    #print len(all_permut_of_str)

    #all_permut_of_str = compare_structures(all_permut_of_str)
    '''