示例#1
0
 def test_to_dict_from_dict(self):
     k = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0])
     d = k.to_dict
     k2 = Kpoints.from_dict(d)
     self.assertEqual(k.kpts, k2.kpts)
     self.assertEqual(k.style, k2.style)
     self.assertEqual(k.kpts_shift, k2.kpts_shift)
示例#2
0
 def test_to_dict_from_dict(self):
     k = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0])
     d = k.to_dict
     k2 = Kpoints.from_dict(d)
     self.assertEqual(k.kpts, k2.kpts)
     self.assertEqual(k.style, k2.style)
     self.assertEqual(k.kpts_shift, k2.kpts_shift)
示例#3
0
 def test_kpt_bands_to_dict_from_dict(self):
     file_name = os.path.join(test_dir, 'KPOINTS.band')
     k = Kpoints.from_file(file_name)
     d = k.to_dict
     import json
     json.dumps(d)
     #This doesn't work
     k2 = Kpoints.from_dict(d)
     self.assertEqual(k.kpts, k2.kpts)
     self.assertEqual(k.style, k2.style)
     self.assertEqual(k.kpts_shift, k2.kpts_shift)
     self.assertEqual(k.num_kpts, k2.num_kpts)
示例#4
0
 def test_kpt_bands_to_dict_from_dict(self):
     file_name = os.path.join(test_dir, 'KPOINTS.band')
     k = Kpoints.from_file(file_name)
     d = k.to_dict
     import json
     json.dumps(d)
     #This doesn't work
     k2 = Kpoints.from_dict(d)
     self.assertEqual(k.kpts, k2.kpts)
     self.assertEqual(k.style, k2.style)
     self.assertEqual(k.kpts_shift, k2.kpts_shift)
     self.assertEqual(k.num_kpts, k2.num_kpts)
示例#5
0
 def get_kpoints(self, structure):
     """
     Writes out a KPOINTS file using the automated gamma grid method.
     VASP crashes GW calculations on none gamma centered meshes.
     """
     if self.sort_structure:
         structure = structure.get_sorted_structure()
     dens = int(self.kpoints_settings['grid_density'])
     if dens == 1:
         return Kpoints.gamma_automatic()
     else:
         return Kpoints.automatic_gamma_density(structure, dens)
示例#6
0
 def get_kpoints(self, structure):
     """
     Writes out a KPOINTS file using the automated gamma grid method.
     VASP crashes GW calculations on none gamma centered meshes.
     """
     if self.sort_structure:
         structure = structure.get_sorted_structure()
     dens = int(self.kpoints_settings['grid_density'])
     if dens == 1:
         return Kpoints.gamma_automatic()
     else:
         return Kpoints.automatic_gamma_density(structure, dens)
示例#7
0
 def test_static_constructors(self):
     kpoints = Kpoints.gamma_automatic([3, 3, 3], [0, 0, 0])
     self.assertEqual(kpoints.style, "Gamma")
     self.assertEqual(kpoints.kpts, [[3, 3, 3]])
     kpoints = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0])
     self.assertEqual(kpoints.style, "Monkhorst")
     self.assertEqual(kpoints.kpts, [[2, 2, 2]])
     kpoints = Kpoints.automatic(100)
     self.assertEqual(kpoints.style, "Automatic")
     self.assertEqual(kpoints.kpts, [[100]])
     filepath = os.path.join(test_dir, 'POSCAR')
     poscar = Poscar.from_file(filepath)
     kpoints = Kpoints.automatic_density(poscar.structure, 500)
     self.assertEqual(kpoints.kpts, [[2, 3, 4]])
示例#8
0
 def test_static_constructors(self):
     kpoints = Kpoints.gamma_automatic([3, 3, 3], [0, 0, 0])
     self.assertEqual(kpoints.style, "Gamma")
     self.assertEqual(kpoints.kpts, [[3, 3, 3]])
     kpoints = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0])
     self.assertEqual(kpoints.style, "Monkhorst")
     self.assertEqual(kpoints.kpts, [[2, 2, 2]])
     kpoints = Kpoints.automatic(100)
     self.assertEqual(kpoints.style, "Automatic")
     self.assertEqual(kpoints.kpts, [[100]])
     filepath = os.path.join(test_dir, "POSCAR")
     poscar = Poscar.from_file(filepath)
     kpoints = Kpoints.automatic_density(poscar.structure, 500)
     self.assertEqual(kpoints.kpts, [[2, 3, 4]])
示例#9
0
    def get_kpoints(self, structure):
        """
        Get a KPOINTS file for NonSCF calculation. In "Line" mode, kpoints are
        generated along high symmetry lines. In "Uniform" mode, kpoints are
        Gamma-centered mesh grid. Kpoints are written explicitly in both cases.

        Args:
            structure (Structure/IStructure): structure to get Kpoints
        """
        if self.mode == "Line":
            kpath = HighSymmKpath(structure)
            cart_k_points, k_points_labels = kpath.get_kpoints()
            frac_k_points = [kpath._prim_rec.get_fractional_coords(k)
                             for k in cart_k_points]
            return Kpoints(comment="Non SCF run along symmetry lines",
                           style="Reciprocal", num_kpts=len(frac_k_points),
                           kpts=frac_k_points, labels=k_points_labels,
                           kpts_weights=[1] * len(cart_k_points))
        else:
            num_kpoints = self.kpoints_settings["kpoints_density"] * \
                structure.lattice.reciprocal_lattice.volume
            kpoints = Kpoints.automatic_density(
                structure, num_kpoints * structure.num_sites)
            mesh = kpoints.kpts[0]
            ir_kpts = SymmetryFinder(structure, symprec=self.sym_prec) \
                .get_ir_reciprocal_mesh(mesh)
            kpts = []
            weights = []
            for k in ir_kpts:
                kpts.append(k[0])
                weights.append(int(k[1]))
            return Kpoints(comment="Non SCF run on uniform grid",
                           style="Reciprocal", num_kpts=len(ir_kpts),
                           kpts=kpts, kpts_weights=weights)
示例#10
0
    def test_static_constructors(self):
        kpoints = Kpoints.gamma_automatic([3, 3, 3], [0, 0, 0])
        self.assertEqual(kpoints.style, "Gamma")
        self.assertEqual(kpoints.kpts, [[3, 3, 3]])
        kpoints = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0])
        self.assertEqual(kpoints.style, "Monkhorst")
        self.assertEqual(kpoints.kpts, [[2, 2, 2]])
        kpoints = Kpoints.automatic(100)
        self.assertEqual(kpoints.style, "Automatic")
        self.assertEqual(kpoints.kpts, [[100]])
        filepath = os.path.join(test_dir, 'POSCAR')
        poscar = Poscar.from_file(filepath)
        kpoints = Kpoints.automatic_density(poscar.structure, 500)
        self.assertEqual(kpoints.kpts, [[2, 4, 4]])
        self.assertEqual(kpoints.style, "Monkhorst")
        kpoints = Kpoints.automatic_density(poscar.structure, 500, True)
        self.assertEqual(kpoints.style, "Gamma")
        kpoints = Kpoints.automatic_density_by_vol(poscar.structure, 1000)
        self.assertEqual(kpoints.kpts, [[6, 11, 13]])
        self.assertEqual(kpoints.style, "Gamma")

        s = poscar.structure
        s.make_supercell(3)
        kpoints = Kpoints.automatic_density(s, 500)
        self.assertEqual(kpoints.kpts, [[1, 1, 1]])
        self.assertEqual(kpoints.style, "Gamma")
示例#11
0
    def get_kpoints(self, structure, kpoints_density=1000):
        """
        Get a KPOINTS file for NonSCF calculation. In "Line" mode, kpoints are
        generated along high symmetry lines. In "Uniform" mode, kpoints are
        Gamma-centered mesh grid. Kpoints are written explicitly in both cases.

        Args:
            kpoints_density:
                kpoints density for the reciprocal cell of structure.
                Suggest to use a large kpoints_density.
                Might need to increase the default value when calculating
                metallic materials.
        """
        if self.mode == "Line":
            kpath = HighSymmKpath(structure)
            cart_k_points, k_points_labels = kpath.get_kpoints()
            frac_k_points = [
                kpath._prim_rec.get_fractional_coords(k) for k in cart_k_points
            ]
            return Kpoints(comment="Non SCF run along symmetry lines",
                           style="Reciprocal",
                           num_kpts=len(frac_k_points),
                           kpts=frac_k_points,
                           labels=k_points_labels,
                           kpts_weights=[1] * len(cart_k_points))
        else:
            num_kpoints = kpoints_density * \
                structure.lattice.reciprocal_lattice.volume
            kpoints = Kpoints.automatic_density(
                structure, num_kpoints * structure.num_sites)
            mesh = kpoints.kpts[0]
            ir_kpts = SymmetryFinder(structure, symprec=0.01)\
                .get_ir_reciprocal_mesh(mesh)
            kpts = []
            weights = []
            for k in ir_kpts:
                kpts.append(k[0])
                weights.append(int(k[1]))
            return Kpoints(comment="Non SCF run on uniform grid",
                           style="Reciprocal",
                           num_kpts=len(ir_kpts),
                           kpts=kpts,
                           kpts_weights=weights)
示例#12
0
    def get_kpoints(self, structure):
        """
        Writes out a KPOINTS file using the fully automated grid method. Uses
        Gamma centered meshes  for hexagonal cells and Monk grids otherwise.

        Algorithm:
            Uses a simple approach scaling the number of divisions along each
            reciprocal lattice vector proportional to its length.
        """
        dens = int(self.kpoints_settings['grid_density'])
        return Kpoints.automatic_density(structure, dens)
示例#13
0
    def get_kpoints(self, structure):
        """
        Writes out a KPOINTS file using the fully automated grid method. Uses
        Gamma centered meshes  for hexagonal cells and Monk grids otherwise.

        Algorithm:
            Uses a simple approach scaling the number of divisions along each
            reciprocal lattice vector proportional to its length.
        """
        dens = int(self.kpoints_settings['grid_density'])
        return Kpoints.automatic_density(structure, dens)
示例#14
0
    def get_kpoints(self, structure):
        """
        Get a KPOINTS file for NonSCF calculation.  kpoints are
        Gamma-centered mesh grid. 

        Args:
            structure (Structure/IStructure): structure to get Kpoints
        """
        kppa = self.kpoints_settings["kpoints_density"]
        kpoints = Kpoints.automatic_gamma_density(structure, kppa)

        return kpoints
示例#15
0
    def test_init(self):
        filepath = os.path.join(test_dir, 'KPOINTS.auto')
        kpoints = Kpoints.from_file(filepath)
        self.assertEqual(kpoints.kpts, [[10]], "Wrong kpoint lattice read")
        filepath = os.path.join(test_dir, 'KPOINTS.cartesian')
        kpoints = Kpoints.from_file(filepath)
        self.assertEqual(kpoints.kpts,
                         [[0.25, 0, 0], [0, 0.25, 0], [0, 0, 0.25]],
                         "Wrong kpoint lattice read")
        self.assertEqual(kpoints.kpts_shift, [0.5, 0.5, 0.5],
                         "Wrong kpoint shift read")

        filepath = os.path.join(test_dir, 'KPOINTS')
        kpoints = Kpoints.from_file(filepath)
        self.assertEqual(kpoints.kpts, [[2, 4, 6]])

        filepath = os.path.join(test_dir, 'KPOINTS.band')
        kpoints = Kpoints.from_file(filepath)
        self.assertIsNotNone(kpoints.labels)
        self.assertEqual(kpoints.style, "Line_mode")

        filepath = os.path.join(test_dir, 'KPOINTS.explicit')
        kpoints = Kpoints.from_file(filepath)
        self.assertIsNotNone(kpoints.kpts_weights)

        filepath = os.path.join(test_dir, 'KPOINTS.explicit_tet')
        kpoints = Kpoints.from_file(filepath)
        self.assertEqual(kpoints.tet_connections, [(6, [1, 2, 3, 4])])
示例#16
0
    def test_init(self):
        filepath = os.path.join(test_dir, "KPOINTS.auto")
        kpoints = Kpoints.from_file(filepath)
        self.assertEqual(kpoints.kpts, [[10]], "Wrong kpoint lattice read")
        filepath = os.path.join(test_dir, "KPOINTS.cartesian")
        kpoints = Kpoints.from_file(filepath)
        self.assertEqual(kpoints.kpts, [[0.25, 0, 0], [0, 0.25, 0], [0, 0, 0.25]], "Wrong kpoint lattice read")
        self.assertEqual(kpoints.kpts_shift, [0.5, 0.5, 0.5], "Wrong kpoint shift read")

        filepath = os.path.join(test_dir, "KPOINTS")
        kpoints = Kpoints.from_file(filepath)
        self.assertEqual(kpoints.kpts, [[2, 4, 6]])

        filepath = os.path.join(test_dir, "KPOINTS.band")
        kpoints = Kpoints.from_file(filepath)
        self.assertIsNotNone(kpoints.labels)
        self.assertEqual(kpoints.style, "Line_mode")

        filepath = os.path.join(test_dir, "KPOINTS.explicit")
        kpoints = Kpoints.from_file(filepath)
        self.assertIsNotNone(kpoints.kpts_weights)

        filepath = os.path.join(test_dir, "KPOINTS.explicit_tet")
        kpoints = Kpoints.from_file(filepath)
        self.assertEqual(kpoints.tet_connections, [(6, [1, 2, 3, 4])])
示例#17
0
 def setUp(self):
     filepath = os.path.join(test_dir, "INCAR")
     incar = Incar.from_file(filepath)
     filepath = os.path.join(test_dir, "POSCAR")
     poscar = Poscar.from_file(filepath)
     if "VASP_PSP_DIR" not in os.environ:
         test_potcar_dir = os.path.abspath(
             os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "test_files")
         )
         os.environ["VASP_PSP_DIR"] = test_potcar_dir
     filepath = os.path.join(test_dir, "POTCAR")
     potcar = Potcar.from_file(filepath)
     filepath = os.path.join(test_dir, "KPOINTS.auto")
     kpoints = Kpoints.from_file(filepath)
     self.vinput = VaspInput(incar, kpoints, poscar, potcar)
示例#18
0
 def setUp(self):
     filepath = os.path.join(test_dir, 'INCAR')
     incar = Incar.from_file(filepath)
     filepath = os.path.join(test_dir, 'POSCAR')
     poscar = Poscar.from_file(filepath)
     if "VASP_PSP_DIR" not in os.environ:
         test_potcar_dir = os.path.abspath(
             os.path.join(os.path.dirname(__file__), "..", "..", "..", "..",
                          "test_files"))
         os.environ["VASP_PSP_DIR"] = test_potcar_dir
     filepath = os.path.join(test_dir, 'POTCAR')
     potcar = Potcar.from_file(filepath)
     filepath = os.path.join(test_dir, 'KPOINTS.auto')
     kpoints = Kpoints.from_file(filepath)
     self.vinput = VaspInput(incar, kpoints, poscar, potcar)
示例#19
0
    def get_kpoints(self, structure, kpoints_density=1000):
        """
        Get a KPOINTS file for NonSCF calculation. In "Line" mode, kpoints are
        generated along high symmetry lines. In "Uniform" mode, kpoints are
        Gamma-centered mesh grid. Kpoints are written explicitly in both cases.

        Args:
            kpoints_density:
                kpoints density for the reciprocal cell of structure.
                Suggest to use a large kpoints_density.
                Might need to increase the default value when calculating
                metallic materials.
        """
        if self.mode == "Line":
            kpath = HighSymmKpath(structure)
            cart_k_points, k_points_labels = kpath.get_kpoints()
            frac_k_points = [kpath._prim_rec.get_fractional_coords(k)
                             for k in cart_k_points]
            return Kpoints(comment="Non SCF run along symmetry lines",
                           style="Reciprocal", num_kpts=len(frac_k_points),
                           kpts=frac_k_points, labels=k_points_labels,
                           kpts_weights=[1]*len(cart_k_points))
        else:
            num_kpoints = kpoints_density * \
                structure.lattice.reciprocal_lattice.volume
            kpoints = Kpoints.automatic_density(
                structure, num_kpoints * structure.num_sites)
            mesh = kpoints.kpts[0]
            ir_kpts = SymmetryFinder(structure, symprec=0.01)\
                .get_ir_reciprocal_mesh(mesh)
            kpts = []
            weights = []
            for k in ir_kpts:
                kpts.append(k[0])
                weights.append(int(k[1]))
            return Kpoints(comment="Non SCF run on uniform grid",
                           style="Reciprocal", num_kpts=len(ir_kpts),
                           kpts=kpts, kpts_weights=weights)
示例#20
0
def substitute_def_struct_gen(mpid, solute, mapi_key, cellmax):
    print(mpid, solute, mapi_key, cellmax)
    if not mpid:
        print("============\nERROR: Provide an mpid\n============")
        return
    if not solute:
        print("============\nERROR: Provide solute atom\n============")
        return

    if not mapi_key:
        with MPRester() as mp:
            struct = mp.get_structure_by_material_id(mpid)
    else:
        with MPRester(mapi_key) as mp:
            struct = mp.get_structure_by_material_id(mpid)

    print(struct.formula)

    mpvis = MPGGAVaspInputSet()

    # Begin defaults: All default settings.
    blk_vasp_incar_param = {
        'IBRION': -1,
        'EDIFF': 1e-4,
        'EDIFFG': 0.001,
        'NSW': 0,
    }
    def_vasp_incar_param = {
        'ISIF': 2,
        'NELM': 99,
        'IBRION': 2,
        'EDIFF': 1e-6,
        'EDIFFG': 0.001,
        'NSW': 40,
    }
    kpoint_den = 6000
    # End defaults

    # Check if POTCAR file can be geneated
    ptcr_flag = True
    try:
        potcar = mpvis.get_potcar(struct)
    except:
        print ("VASP POTCAR folder not detected.\n" \
              "Only INCAR, POSCAR, KPOINTS are generated.\n" \
              "If you have VASP installed on this system, \n" \
              "refer to pymatgen documentation for configuring the settings.")
        ptcr_flag = False

    print(ptcr_flag)

    vac = Vacancy(struct, {}, {})
    sc_scale = get_sc_scale(struct, cellmax)
    scs = vac.make_supercells_with_defects(sc_scale)
    site_no = scs[0].num_sites
    if site_no > cellmax:
        max_sc_dim = max(sc_scale)
        i = sc_scale.index(max_sc_dim)
        sc_scale[i] -= 1
        scs = vac.make_supercells_with_defects(sc_scale)
    print len(scs)

    interdir = mpid
    blk_str_sites = set(scs[0].sites)
    for i in range(1, len(scs)):
        sc = scs[i]
        vac_str_sites = set(sc.sites)
        vac_sites = blk_str_sites - vac_str_sites
        vac_site = list(vac_sites)[0]
        site_mult = vac.get_defectsite_multiplicity(i - 1)
        vac_site_specie = vac_site.specie
        vac_specie = vac_site.specie.symbol

        # Solute substitution defect generation at all vacancy sites
        struct_species = scs[0].types_of_specie
        solute_struct = sc.copy()
        solute_struct.append(solute, vac_site.frac_coords)

        incar = mpvis.get_incar(solute_struct)
        incar.update(def_vasp_incar_param)
        poscar = mpvis.get_poscar(solute_struct)
        kpoints = Kpoints.automatic_density(solute_struct, kpoint_den)
        if ptcr_flag:
            potcar = mpvis.get_potcar(solute_struct)

        sub_def_dir = 'solute_{}_mult-{}_sitespecie-{}_subspecie-{}'.format(
            str(i), site_mult, vac_specie, solute)
        fin_dir = os.path.join(interdir, sub_def_dir)
        try:
            os.makedirs(fin_dir)
        except:
            pass
        poscar.write_file(os.path.join(fin_dir, 'POSCAR'))
        incar.write_file(os.path.join(fin_dir, 'INCAR'))
        kpoints.write_file(os.path.join(fin_dir, 'KPOINTS'))
        if ptcr_flag:
            potcar.write_file(os.path.join(fin_dir, 'POTCAR'))
示例#21
0
 def test_kpt_bands_to_dict_from_dict(self):
     file_name = os.path.join(test_dir, 'KPOINTS.band')
     k = Kpoints.from_file(file_name)
     d = k.to_dict
示例#22
0
 def run_task(self, fw_spec):
     Incar.from_dict(fw_spec['vasp']['incar']).write_file('INCAR')
     Poscar.from_dict(fw_spec['vasp']['poscar']).write_file('POSCAR')
     Potcar.from_dict(fw_spec['vasp']['potcar']).write_file('POTCAR')
     Kpoints.from_dict(fw_spec['vasp']['kpoints']).write_file('KPOINTS')
def get_calibration_task(structure, phase="CalibrateBulk", \
                         slab_interface_params={'hkl':[1,0,0], 'ligand': None},\
                         turn_knobs={}, incar_params={}, other_params={}):
    """
    returns general calibration task for a structure
    
    Args:
        structure    : pymatgen structure to be calibrated (can be a bulk, ligand, slab
                       or interface)  
        phase        : calibration type, viz. CalibrateBulk, CalibrateMolecule,
                       CalibrateSlab, CalibrateInterface
        hkl          : in case of Slab and Interface miller indices of facet 
        turn_knobs   : specifies the parameters to be calibrated 
        incar_params : dictionary of additional incar parameters, refer defined 
                       incar_dict for defaults 
        other_params : other parameters for calibration, viz. job_dir, is_matrix, etc. 
                       described in the calibrate module
    """
    #structure definition 
    
    poscar = Poscar(structure)
    incar_dict = { 'SYSTEM': 'slab',
                   'ENCUT': 500, 
                   'ISIF': 2, 
                   'IBRION': 2, 
                   'ISMEAR': 1, 
                   'EDIFF': 1e-05, 
                   'NPAR': 4, 
                   'SIGMA': 0.1, 
                   'PREC': 'Accurate'
                 }
    if incar_params: 
        incar_dict.update(incar_params)
    incar = Incar.from_dict(incar_dict)
    kpoints = Kpoints.monkhorst_automatic(kpts=(8, 8, 1))
    que  = { 'nnodes':1,
             'nprocs':16,
             'walltime':'48:00:00',
             'job_bin': '/home/km468/Software/VASP/vaspsol_kappa.5.3.5/vasp'             
            }
    # calibration task: relax hkl
    calparams = {}
    calparams['calibrate'] = phase
    calparams['incar'] = incar.as_dict()
    calparams['poscar'] = poscar.as_dict()
    calparams['kpoints'] = kpoints.as_dict()
    calparams['que_params'] = que
    calparams['turn_knobs'] = turn_knobs
    if phase == 'CalibrateSlab':
         calparams['system'] = {'hkl':slab_interface_params['hkl'],
                                'ligand':slab_interface_params['ligand']
                               }
    elif phase == 'CalibrateInterface':
         calparams['system'] = {'hkl':hkl,
                                'ligand':structure.ligand.reduced_formula
                               }
    calparams['other_params'] = {
        'is_matrix':False,
        'from_ase':True,
        'Grid_type':'M'
        }
    if other_params:
        calparams['other_params'].update(other_params)
    return MPINTCalibrateTask(calparams)
示例#24
0
def vac_antisite_def_struct_gen(mpid, mapi_key, cellmax):
    if not mpid:
        print ("============\nERROR: Provide an mpid\n============")
        return

    if not mapi_key:
        with MPRester() as mp:
            struct = mp.get_structure_by_material_id(mpid)
    else:
        with MPRester(mapi_key) as mp:
            struct = mp.get_structure_by_material_id(mpid)

    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 = get_sc_scale(struct,cellmax)

    mpvis = MPGGAVaspInputSet()

    # Begin defaults: All default settings.
    blk_vasp_incar_param = {'IBRION':-1,'EDIFF':1e-4,'EDIFFG':0.001,'NSW':0,}
    def_vasp_incar_param = {'ISIF':2,'NELM':99,'IBRION':2,'EDIFF':1e-6, 
                            'EDIFFG':0.001,'NSW':40,}
    kpoint_den = 6000
    # End defaults
    
    ptcr_flag = True
    try:
        potcar = mpvis.get_potcar(struct)
    except:
        print ("VASP POTCAR folder not detected.\n" \
              "Only INCAR, POSCAR, KPOINTS are generated.\n" \
              "If you have VASP installed on this system, \n" \
              "refer to pymatgen documentation for configuring the settings.")
        ptcr_flag = False


    vac = Vacancy(struct, {}, {})
    scs = vac.make_supercells_with_defects(sc_scale)
    site_no = scs[0].num_sites
    if site_no > cellmax:
        max_sc_dim = max(sc_scale)
        i = sc_scale.index(max_sc_dim)
        sc_scale[i] -= 1
        scs = vac.make_supercells_with_defects(sc_scale)

    for i in range(len(scs)):
        sc = scs[i]
        poscar = mpvis.get_poscar(sc)
        kpoints = Kpoints.automatic_density(sc,kpoint_den)
        incar = mpvis.get_incar(sc)
        if ptcr_flag:
            potcar = mpvis.get_potcar(sc)

        interdir = mpid
        if not i:
            fin_dir = os.path.join(interdir,'bulk')
            try:
                os.makedirs(fin_dir)
            except:
                pass
            incar.update(blk_vasp_incar_param)
            incar.write_file(os.path.join(fin_dir,'INCAR'))
            poscar.write_file(os.path.join(fin_dir,'POSCAR'))
            if ptcr_flag:
                potcar.write_file(os.path.join(fin_dir,'POTCAR'))
            kpoints.write_file(os.path.join(fin_dir,'KPOINTS'))
        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:
                os.makedirs(fin_dir)
            except:
                pass
            incar.update(def_vasp_incar_param)
            poscar.write_file(os.path.join(fin_dir,'POSCAR'))
            incar.write_file(os.path.join(fin_dir,'INCAR'))
            if ptcr_flag:
                potcar.write_file(os.path.join(fin_dir,'POTCAR'))
            kpoints.write_file(os.path.join(fin_dir,'KPOINTS'))

            # Antisite generation at all vacancy sites
            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 = mpvis.get_poscar(anti_struct)
                incar = mpvis.get_incar(anti_struct)
                incar.update(def_vasp_incar_param)
                as_dir ='antisite_{}_mult-{}_sitespecie-{}_subspecie-{}'.format(
                        str(i), site_mult, vac_symbol, subspecie_symbol)
                fin_dir = os.path.join(interdir,as_dir)
                try:
                    os.makedirs(fin_dir)
                except:
                    pass
                poscar.write_file(os.path.join(fin_dir,'POSCAR'))
                incar.write_file(os.path.join(fin_dir,'INCAR'))
                if ptcr_flag:
                        potcar.write_file(os.path.join(fin_dir,'POTCAR'))
                kpoints.write_file(os.path.join(fin_dir,'KPOINTS'))
示例#25
0
# read structure
if os.path.exists(fstruct):
    struct = mg.read_structure(fstruct)
else:
    print("File %s does not exist" % fstruct)
    exit(1)

# symmetry information
struct_sym = SymmetryFinder(struct)
print("lattice type : {0}".format(struct_sym.get_lattice_type()))
print("space group  : {0} ({1})".format(struct_sym.get_spacegroup_symbol(),
                                     struct_sym.get_spacegroup_number()))

# Compute first brillouin zone
ibz = HighSymmKpath(struct)
ibz.get_kpath_plot(savefig="path.png")
print("ibz type     : {0}".format(ibz.name))

# print specific kpoints in the first brillouin zone
for key, val in ibz.kpath["kpoints"].items():
    print("%8s %s" % (key, str(val)))
 
# suggested path for the band structure
print("paths in first brillouin zone :")
for path in ibz.kpath["path"]:
    print(path)

# write the KPOINTS file
Kpoints.automatic_linemode(ndiv, ibz).write_file("KPOINTS")
示例#26
0
 def get_kpoints(self, structure):
     return Kpoints.gamma_automatic()
示例#27
0
def get_VASP_inputs(structure, workdir, job_name, nproc=64, kppa=500, extra_incar_dict = None):

    if os.path.exists(workdir):
        print 'WORKDIR ALREADY EXISTS. DELETE TO LAUNCH NEW JOB'
        return -1

    poscar  = Poscar(structure)

    list_potcar_singles, potcar= get_POTCAR(poscar)

    kpoints = Kpoints.automatic_density(structure, kppa=kppa)

    # Default values
    incar_dict = dict(  SYSTEM  =   structure.formula, # Name of job
                        LREAL   =   'Auto',     # Should projections be done in real space? Let VASP decide
                        ENCUT   =   520.,       # 520. eV, just like Ceder
                        IBRION  =   2,          # Controls ionic relataxion: 1-> DISS, 2 -> CG, 3-> MD
                        EDIFF   =   1E-7,       # criterion to stop SCF loop, in eV
                        EDIFFG  =  -1E-3,       # criterion to stop ionic relaxations. Negative means FORCES < |EDIFFG|
                        PREC    =   'HIGH',     # level of precision
                        AMIX    =   0.2,
                        AMIX_MAG=   0.8,
                        BMIX    =   0.001,
                        BMIX_MAG=   0.001,
                        NSW     =   150,        # Maximum number of ionic steps
                        ISMEAR  =   0,          # smearing scheme. Use 0 for insulators, as suggested by VASPWIKI
                        ISPIN   =   2,          # spin polarized 
                        NPAR    =   8,          # VASPWIKI recommends sqrt(ncore)
                        LSCALU  =   False,      # Don't use scalapack. Probably a can of worms.
                        ALGO    =   'NORMAL',   # what ionic relaxation scheme to use? 
                        LORBIT  =   11,         # 11 prints out the DOS
                        ISIF    =   3,          # Controls the computation of stress tensor. 3 computes everything
                        NSIM    =   4,          # how many bands to treat in parallel? Default is 4, probably fine.
                        SIGMA   =   0.025,      # smearing in eV
                        LMAXMIX =   4,          # Description: LMAXMIX controls up to which l-quantum number the one-center PAW charge densities are passed through the charge density mixer. MaterialsProject uses 4.
                        LCHARG  =   False,      # Write charge densities?
                        LWAVE   =   False,      # write out the wavefunctions?
                        LPLANE  =   True,       # Plane distribution of FFT coefficients. Reduces communications in FFT.
                        NELM    =   100,        # maximum number of SCF cycles.
                        NELMDL  =  -10,         # since initial orbitals may be random, fixes hamiltonian for |NELM| SCF cycles to give wf a chance to simmer down.
                        ISTART  =   0,          # begin from scratch!
                        ISYM    =   2)          # use symmetry 

    if extra_incar_dict  != None:
        incar_dict.update( extra_incar_dict  )

    incar   = Incar.from_dict(incar_dict )


    incar.write_file(workdir+'INCAR')
    poscar.write_file(workdir+'POSCAR', vasp4_compatible = True)
    kpoints.write_file(workdir+'KPOINTS')
    potcar.write_file(workdir+'POTCAR')


    potcar.sort()
    hack_potcar_file(workdir,list_potcar_singles)
    

    with open(workdir+'job.sh','w') as f:
        f.write(submit_template.format(job_name,nproc))

    with open(workdir+'clean.sh','w') as f:
        f.write(clean_template)

    return 0
示例#28
0
    def from_previous_vasp_run(previous_vasp_dir, output_dir='.',
                               user_incar_settings=None,
                               make_dir_if_not_present=True):
        """
        Generate a set of Vasp input files for static calculations from a
        directory of previous Vasp run.

        Args:
            previous_vasp_dir:
                The directory contains the outputs(vasprun.xml and OUTCAR) of
                previous vasp run.
            output_dir:
                The directory to write the VASP input files for the static
                calculations. Default to write in the current directory.
            make_dir_if_not_present:
                Set to True if you want the directory (and the whole path) to
                be created if it is not present.
        """

        try:
            vasp_run = Vasprun(os.path.join(previous_vasp_dir, "vasprun.xml"),
                               parse_dos=False, parse_eigen=None)
            outcar = Outcar(os.path.join(previous_vasp_dir, "OUTCAR"))
            previous_incar = Incar.from_file(os.path.join(previous_vasp_dir,
                                                          "INCAR"))
            kpoints = Kpoints.from_file(os.path.join(previous_vasp_dir,
                                                     "KPOINTS"))
        except:
            traceback.format_exc()
            raise RuntimeError("Can't get valid results from previous run")

        structure = MPStaticVaspInputSet.get_structure(
            vasp_run, outcar)
        mpsvip = MPStaticVaspInputSet()
        mpsvip.write_input(structure, output_dir, make_dir_if_not_present)
        new_incar = Incar.from_file(os.path.join(output_dir, "INCAR"))

        # Use previous run INCAR and override necessary parameters
        previous_incar.update({"IBRION": -1, "ISMEAR": -5, "LAECHG": True,
                               "LCHARG": True, "LORBIT": 11, "LVHAR": True,
                               "LWAVE": False, "NSW": 0, "ICHARG": 0})

        # Compare ediff between previous and staticinputset values,
        # choose the tigher ediff
        previous_incar.update({"EDIFF": min(previous_incar["EDIFF"],
                                            new_incar["EDIFF"])})

        # add user settings
        if user_incar_settings:
            previous_incar.update(user_incar_settings)
        previous_incar.write_file(os.path.join(output_dir, "INCAR"))

        # Prefer to use k-point scheme from previous run
        kpoints_out = Kpoints.from_file(os.path.join(output_dir, "KPOINTS"))
        if kpoints.style != kpoints_out.style and \
                SymmetryFinder(structure, 0.01).get_lattice_type() != \
                "hexagonal":
            k_div = (kp + 1 if kp % 2 == 1 else kp
                     for kp in kpoints_out.kpts[0])
            Kpoints.monkhorst_automatic(k_div).write_file(
                os.path.join(output_dir, "KPOINTS"))
示例#29
0
 def get_kpoints(self, structure):
     return Kpoints.gamma_automatic()
示例#30
0
    def from_previous_vasp_run(previous_vasp_dir, output_dir='.',
                               user_incar_settings=None,
                               make_dir_if_not_present=True,
                               kpoints_density=90, sym_prec=0.1):
        """
        Generate a set of Vasp input files for static calculations from a
        directory of previous Vasp run.

        Args:
            previous_vasp_dir (str): Directory containing the outputs(
                vasprun.xml and OUTCAR) of previous vasp run.
            output_dir (str): Directory to write the VASP input files for
                the static calculations. Defaults to current directory.
            make_dir_if_not_present (bool): Set to True if you want the
                directory (and the whole path) to be created if it is not
                present.
            kpoints_density (int): kpoints density for the reciprocal cell
                of structure. Might need to increase the default value when
                calculating metallic materials.
            sym_prec (float): Tolerance for symmetry finding
        """
        # Read input and output from previous run
        try:
            vasp_run = Vasprun(os.path.join(previous_vasp_dir, "vasprun.xml"),
                               parse_dos=False, parse_eigen=None)
            outcar = Outcar(os.path.join(previous_vasp_dir, "OUTCAR"))
            previous_incar = vasp_run.incar
            previous_kpoints = vasp_run.kpoints
        except:
            traceback.format_exc()
            raise RuntimeError("Can't get valid results from previous run")

        mpsvip = MPStaticVaspInputSet(kpoints_density=kpoints_density,
                                      sym_prec=sym_prec)
        structure = mpsvip.get_structure(vasp_run, outcar)

        mpsvip.write_input(structure, output_dir, make_dir_if_not_present)
        new_incar = mpsvip.get_incar(structure)

        # Use previous run INCAR and override necessary parameters
        previous_incar.update({"IBRION": -1, "ISMEAR": -5, "LAECHG": True,
                               "LCHARG": True, "LORBIT": 11, "LVHAR": True,
                               "LWAVE": False, "NSW": 0, "ICHARG": 0})

        for incar_key in ["MAGMOM", "NUPDOWN"]:
            if new_incar.get(incar_key, None):
                previous_incar.update({incar_key: new_incar[incar_key]})
            else:
                previous_incar.pop(incar_key, None)

        # use new LDAUU when possible b/c the Poscar might have changed
        # representation
        if previous_incar.get('LDAU'):
            u = previous_incar.get('LDAUU', [])
            j = previous_incar.get('LDAUJ', [])
            if sum([u[x] - j[x] for x, y in enumerate(u)]) > 0:
                for tag in ('LDAUU', 'LDAUL', 'LDAUJ'):
                    previous_incar.update({tag: new_incar[tag]})
            # ensure to have LMAXMIX for GGA+U static run
            if "LMAXMIX" not in previous_incar:
                previous_incar.update({"LMAXMIX": new_incar["LMAXMIX"]})

        # Compare ediff between previous and staticinputset values,
        # choose the tighter ediff
        previous_incar.update({"EDIFF": min(previous_incar.get("EDIFF", 1),
                                            new_incar["EDIFF"])})

        # add user settings
        if user_incar_settings:
            previous_incar.update(user_incar_settings)
        previous_incar.write_file(os.path.join(output_dir, "INCAR"))

        # Perform checking on INCAR parameters
        if any([previous_incar.get("NSW", 0) != 0, previous_incar["IBRION"] != -1,
               previous_incar["LCHARG"] != True,
               any([sum(previous_incar["LDAUU"])<=0, previous_incar["LMAXMIX"]<4])
               if previous_incar.get("LDAU") else False]):
            raise ValueError("Incompatible INCAR parameters!")

        # Prefer to use k-point scheme from previous run
        new_kpoints = mpsvip.get_kpoints(structure)
        if previous_kpoints.style[0] != new_kpoints.style[0]:
            if previous_kpoints.style[0] == "M" and \
                    SymmetryFinder(structure, 0.1).get_lattice_type() != \
                    "hexagonal":
                k_div = (kp + 1 if kp % 2 == 1 else kp
                         for kp in new_kpoints.kpts[0])
                Kpoints.monkhorst_automatic(k_div). \
                    write_file(os.path.join(output_dir, "KPOINTS"))
            else:
                Kpoints.gamma_automatic(new_kpoints.kpts[0]). \
                    write_file(os.path.join(output_dir, "KPOINTS"))
        else:
            new_kpoints.write_file(os.path.join(output_dir, "KPOINTS"))
示例#31
0
def substitute_def_struct_gen(mpid, solute, mapi_key, cellmax):
    print (mpid, solute, mapi_key, cellmax)
    if not mpid:
        print ("============\nERROR: Provide an mpid\n============")
        return
    if not solute:
        print ("============\nERROR: Provide solute atom\n============")
        return

    if not mapi_key:
        with MPRester() as mp:
            struct = mp.get_structure_by_material_id(mpid)
    else:
        with MPRester(mapi_key) as mp:
            struct = mp.get_structure_by_material_id(mpid)

    print (struct.formula)

    mpvis = MPGGAVaspInputSet()

    # Begin defaults: All default settings.
    blk_vasp_incar_param = {'IBRION':-1,'EDIFF':1e-4,'EDIFFG':0.001,'NSW':0,}
    def_vasp_incar_param = {'ISIF':2,'NELM':99,'IBRION':2,'EDIFF':1e-6, 
                            'EDIFFG':0.001,'NSW':40,}
    kpoint_den = 6000
    # End defaults
    
    # Check if POTCAR file can be geneated
    ptcr_flag = True
    try:
        potcar = mpvis.get_potcar(struct)
    except:
        print ("VASP POTCAR folder not detected.\n" \
              "Only INCAR, POSCAR, KPOINTS are generated.\n" \
              "If you have VASP installed on this system, \n" \
              "refer to pymatgen documentation for configuring the settings.")
        ptcr_flag = False

    print (ptcr_flag)

    vac = Vacancy(struct, {}, {})
    sc_scale = get_sc_scale(struct,cellmax)
    scs = vac.make_supercells_with_defects(sc_scale)
    site_no = scs[0].num_sites
    if site_no > cellmax:
            max_sc_dim = max(sc_scale)
            i = sc_scale.index(max_sc_dim)
            sc_scale[i] -= 1
            scs = vac.make_supercells_with_defects(sc_scale)
    print len(scs)

    interdir = mpid
    blk_str_sites = set(scs[0].sites)
    for i in range(1,len(scs)):
        sc = scs[i]
        vac_str_sites = set(sc.sites)
        vac_sites = blk_str_sites - vac_str_sites
        vac_site = list(vac_sites)[0]
        site_mult = vac.get_defectsite_multiplicity(i-1)
        vac_site_specie = vac_site.specie
        vac_specie = vac_site.specie.symbol

        # Solute substitution defect generation at all vacancy sites
        struct_species = scs[0].types_of_specie
        solute_struct = sc.copy()
        solute_struct.append(solute, vac_site.frac_coords)

        incar = mpvis.get_incar(solute_struct)
        incar.update(def_vasp_incar_param)
        poscar = mpvis.get_poscar(solute_struct)
        kpoints = Kpoints.automatic_density(solute_struct,kpoint_den)
        if ptcr_flag:
            potcar = mpvis.get_potcar(solute_struct)

        sub_def_dir ='solute_{}_mult-{}_sitespecie-{}_subspecie-{}'.format(
                str(i), site_mult, vac_specie, solute)
        fin_dir = os.path.join(interdir,sub_def_dir)
        try:
            os.makedirs(fin_dir)
        except:
            pass
        poscar.write_file(os.path.join(fin_dir,'POSCAR'))
        incar.write_file(os.path.join(fin_dir,'INCAR'))
        kpoints.write_file(os.path.join(fin_dir,'KPOINTS'))
        if ptcr_flag:
            potcar.write_file(os.path.join(fin_dir,'POTCAR'))
示例#32
0
slab_potcar.write_file("./Slab_with_vdw/POTCAR")

#set the common INCAR file and KPOINTS
incar_dict = {
                 'SYSTEM': 'ligand_PbS', 
                 'ENCUT': 600, 
                 'ISIF': 2, 
                 'IBRION': 2, 
                 'ALGO': 'Normal', 
                 'ISMEAR': 1, 
                 'ISPIN': 1, 
                 'EDIFF': 1e-06, 
                 'EDIFFG': -0.005, 
                 'NPAR': 8, 
                 'SIGMA': 0.1, 
                 'PREC': 'Accurate',
		 'IVDW': 2,
		 'NSW': 1000
    }

incar = Incar.from_dict(incar_dict)
kpoints = Kpoints.monkhorst_automatic(kpts= (8, 8, 1), shift= (0, 0, 0))

#write the files in appropriate directory
incar.write_file("./Interface_with_vdw/INCAR")
incar.write_file("./Slab_with_vdw/INCAR")
kpoints.write_file("./Interface_with_vdw/KPOINTS")
kpoints.write_file("./Slab_with_vdw/KPOINTS")
shu.copy("./submit_job", "./Interface_with_vdw/")
shu.copy("./submit_job", "./Slab_with_vdw")
示例#33
0
def vac_antisite_def_struct_gen(mpid, mapi_key, cellmax):
    if not mpid:
        print("============\nERROR: Provide an mpid\n============")
        return

    if not mapi_key:
        with MPRester() as mp:
            struct = mp.get_structure_by_material_id(mpid)
    else:
        with MPRester(mapi_key) as mp:
            struct = mp.get_structure_by_material_id(mpid)

    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 = get_sc_scale(struct, cellmax)

    mpvis = MPGGAVaspInputSet()

    # Begin defaults: All default settings.
    blk_vasp_incar_param = {
        'IBRION': -1,
        'EDIFF': 1e-4,
        'EDIFFG': 0.001,
        'NSW': 0,
    }
    def_vasp_incar_param = {
        'ISIF': 2,
        'NELM': 99,
        'IBRION': 2,
        'EDIFF': 1e-6,
        'EDIFFG': 0.001,
        'NSW': 40,
    }
    kpoint_den = 6000
    # End defaults

    ptcr_flag = True
    try:
        potcar = mpvis.get_potcar(struct)
    except:
        print ("VASP POTCAR folder not detected.\n" \
              "Only INCAR, POSCAR, KPOINTS are generated.\n" \
              "If you have VASP installed on this system, \n" \
              "refer to pymatgen documentation for configuring the settings.")
        ptcr_flag = False

    vac = Vacancy(struct, {}, {})
    scs = vac.make_supercells_with_defects(sc_scale)
    site_no = scs[0].num_sites
    if site_no > cellmax:
        max_sc_dim = max(sc_scale)
        i = sc_scale.index(max_sc_dim)
        sc_scale[i] -= 1
        scs = vac.make_supercells_with_defects(sc_scale)

    for i in range(len(scs)):
        sc = scs[i]
        poscar = mpvis.get_poscar(sc)
        kpoints = Kpoints.automatic_density(sc, kpoint_den)
        incar = mpvis.get_incar(sc)
        if ptcr_flag:
            potcar = mpvis.get_potcar(sc)

        interdir = mpid
        if not i:
            fin_dir = os.path.join(interdir, 'bulk')
            try:
                os.makedirs(fin_dir)
            except:
                pass
            incar.update(blk_vasp_incar_param)
            incar.write_file(os.path.join(fin_dir, 'INCAR'))
            poscar.write_file(os.path.join(fin_dir, 'POSCAR'))
            if ptcr_flag:
                potcar.write_file(os.path.join(fin_dir, 'POTCAR'))
            kpoints.write_file(os.path.join(fin_dir, 'KPOINTS'))
        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:
                os.makedirs(fin_dir)
            except:
                pass
            incar.update(def_vasp_incar_param)
            poscar.write_file(os.path.join(fin_dir, 'POSCAR'))
            incar.write_file(os.path.join(fin_dir, 'INCAR'))
            if ptcr_flag:
                potcar.write_file(os.path.join(fin_dir, 'POTCAR'))
            kpoints.write_file(os.path.join(fin_dir, 'KPOINTS'))

            # Antisite generation at all vacancy sites
            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 = mpvis.get_poscar(anti_struct)
                incar = mpvis.get_incar(anti_struct)
                incar.update(def_vasp_incar_param)
                as_dir = 'antisite_{}_mult-{}_sitespecie-{}_subspecie-{}'.format(
                    str(i), site_mult, vac_symbol, subspecie_symbol)
                fin_dir = os.path.join(interdir, as_dir)
                try:
                    os.makedirs(fin_dir)
                except:
                    pass
                poscar.write_file(os.path.join(fin_dir, 'POSCAR'))
                incar.write_file(os.path.join(fin_dir, 'INCAR'))
                if ptcr_flag:
                    potcar.write_file(os.path.join(fin_dir, 'POTCAR'))
                kpoints.write_file(os.path.join(fin_dir, 'KPOINTS'))
示例#34
0
 def test_kpt_bands_to_dict_from_dict(self):
     file_name = os.path.join(test_dir, "KPOINTS.band")
     k = Kpoints.from_file(file_name)
     d = k.to_dict
示例#35
0
 def run_task(self, fw_spec):
     Incar.from_dict(fw_spec['vasp']['incar']).write_file('INCAR')
     Poscar.from_dict(fw_spec['vasp']['poscar']).write_file('POSCAR')
     Potcar.from_dict(fw_spec['vasp']['potcar']).write_file('POTCAR')
     Kpoints.from_dict(fw_spec['vasp']['kpoints']).write_file('KPOINTS')
示例#36
0
for line in id_expgap:
    words=line.split()
    print words
    id_line=words[0]
    os.mkdir(id_line)
    os.chdir(id_line)
    s = mpr.get_structure_by_material_id(id_line)
    # obtain structural information from Materials Project database
    #print json.dumps(s.to_dict)
    # convert structural infomation into a dictionary and then dump to a json file

    user_incar_settings={"ALGO":'Normal',"EDIFF":1E-8,"ENCUT":500,"NSW":0,"LWAVE":True}
    mpvis = MPVaspInputSet(user_incar_settings=user_incar_settings)

    mpvis.get_incar(s).write_file('INCAR')
    # from the GW input set, get the incar parameters, generate INCAR
    print mpvis.get_incar(s)
    #
    kp_density = mpvis.get_kpoints(s).kpts[0]
    # from the GW input set, get the k-point density
    kpoints = Kpoints.gamma_automatic(kp_density)
    # generate Gamma centered k-point mesh
    kpoints.write_file('KPOINTS')
    # generate KPOINTS file
    mpvis.get_poscar(s).write_file('POSCAR')
    # generate POSCAR file
    mpvis.get_potcar(s).write_file('POTCAR')
    # generate POTCAR file
    os.chdir('..')
id_expgap.close()
示例#37
0
    def from_previous_vasp_run(previous_vasp_dir, output_dir='.',
                               user_incar_settings=None,
                               make_dir_if_not_present=True):
        """
        Generate a set of Vasp input files for static calculations from a
        directory of previous Vasp run.

        Args:
            previous_vasp_dir:
                The directory contains the outputs(vasprun.xml and OUTCAR) of
                previous vasp run.
            output_dir:
                The directory to write the VASP input files for the static
                calculations. Default to write in the current directory.
            make_dir_if_not_present:
                Set to True if you want the directory (and the whole path) to
                be created if it is not present.
        """

        try:
            vasp_run = Vasprun(os.path.join(previous_vasp_dir, "vasprun.xml"),
                               parse_dos=False, parse_eigen=None)
            outcar = Outcar(os.path.join(previous_vasp_dir, "OUTCAR"))
            previous_incar = vasp_run.incar
            previous_kpoints = vasp_run.kpoints
            previous_final_structure = vasp_run.final_structure
        except:
            traceback.format_exc()
            raise RuntimeError("Can't get valid results from previous run")
        structure = MPStaticVaspInputSet.get_structure(vasp_run, outcar)
        mpsvip = MPStaticVaspInputSet()
        mpsvip.write_input(structure, output_dir, make_dir_if_not_present)
        #new_incar = Incar.from_file(os.path.join(output_dir, "INCAR"))
        new_incar = mpsvip.get_incar(structure)

        # Use previous run INCAR and override necessary parameters
        previous_incar.update({"IBRION": -1, "ISMEAR": -5, "LAECHG": True,
                               "LCHARG": True, "LORBIT": 11, "LVHAR": True,
                               "LWAVE": False, "NSW": 0, "ICHARG": 0})

        for incar_key in ["MAGMOM", "NUPDOWN"]:
            if new_incar.get(incar_key, None):
                previous_incar.update({incar_key: new_incar[incar_key]})
            else:
                previous_incar.pop(incar_key, None)

        # use new LDAUU when possible b/c the Poscar might have changed
        # representation
        if previous_incar.get('LDAU'):
            u = previous_incar.get('LDAUU', [])
            j = previous_incar.get('LDAUJ', [])
            if sum([u[x] - j[x] for x, y in enumerate(u)]) > 0:
                for tag in ('LDAUU', 'LDAUL', 'LDAUJ'):
                    previous_incar.update({tag: new_incar[tag]})

        # Compare ediff between previous and staticinputset values,
        # choose the tighter ediff
        previous_incar.update({"EDIFF": min(previous_incar.get("EDIFF", 1),
                                            new_incar["EDIFF"])})

        # add user settings
        if user_incar_settings:
            previous_incar.update(user_incar_settings)
        previous_incar.write_file(os.path.join(output_dir, "INCAR"))

        # Prefer to use k-point scheme from previous run
        previous_kpoints_density = np.prod(previous_kpoints.kpts[0]) / \
            previous_final_structure.lattice.reciprocal_lattice.volume
        new_kpoints_density = max(previous_kpoints_density, 90)
        new_kpoints = mpsvip.get_kpoints(structure,
                                         kpoints_density=new_kpoints_density)
        if previous_kpoints.style[0] != new_kpoints.style[0]:
            if previous_kpoints.style[0] == "M" and \
                    SymmetryFinder(structure, 0.01).get_lattice_type() != \
                    "hexagonal":
                k_div = (kp + 1 if kp % 2 == 1 else kp
                         for kp in new_kpoints.kpts[0])
                Kpoints.monkhorst_automatic(k_div). \
                    write_file(os.path.join(output_dir, "KPOINTS"))
            else:
                Kpoints.gamma_automatic(new_kpoints.kpts[0]). \
                    write_file(os.path.join(output_dir, "KPOINTS"))
        else:
            new_kpoints.write_file(os.path.join(output_dir, "KPOINTS"))