コード例 #1
0
ファイル: vaspio_set.py プロジェクト: brendaneng1/pymatgen
    def get_incar(self, structure):
        incar = Incar()
        if self.sort_structure:
            structure = structure.get_sorted_structure()
        comp = structure.composition
        elements = sorted([el for el in comp.elements if comp[el] > 0],
                          key=lambda e: e.X)
        most_electroneg = elements[-1].symbol
        poscar = Poscar(structure)
        for key, setting in self.incar_settings.items():
            if key == "MAGMOM":
                mag = []
                for site in structure:
                    if hasattr(site, 'magmom'):
                        mag.append(site.magmom)
                    elif hasattr(site.specie, 'spin'):
                        mag.append(site.specie.spin)
                    elif str(site.specie) in setting:
                        mag.append(setting.get(str(site.specie)))
                    else:
                        mag.append(setting.get(site.specie.symbol, 0.6))
                incar[key] = mag
            elif key in ('LDAUU', 'LDAUJ', 'LDAUL'):
                if most_electroneg in setting.keys():
                    incar[key] = [setting[most_electroneg].get(sym, 0)
                                  for sym in poscar.site_symbols]
                else:
                    incar[key] = [0] * len(poscar.site_symbols)
            elif key == "EDIFF":
                if self.ediff_per_atom:
                    incar[key] = float(setting) * structure.num_sites
                else:
                    incar[key] = float(setting)
            else:
                incar[key] = setting

        has_u = ("LDAUU" in incar and sum(incar['LDAUU']) > 0)
        if has_u:
            # modify LMAXMIX if LSDA+U and you have d or f electrons
            # note that if the user explicitly sets LMAXMIX in settings it will
            # override this logic.
            if 'LMAXMIX' not in self.incar_settings.keys():
                # contains f-electrons
                if any([el.Z > 56 for el in structure.composition]):
                    incar['LMAXMIX'] = 6
                # contains d-electrons
                elif any([el.Z > 20 for el in structure.composition]):
                    incar['LMAXMIX'] = 4
        else:
            for key in incar.keys():
                if key.startswith('LDAU'):
                    del incar[key]

        if self.set_nupdown:
            nupdown = sum([mag if abs(mag) > 0.6 else 0
                           for mag in incar['MAGMOM']])
            incar['NUPDOWN'] = nupdown

        return incar
コード例 #2
0
    def get_incar(self, structure):
        incar = Incar()
        if self.sort_structure:
            structure = structure.get_sorted_structure()
        comp = structure.composition
        elements = sorted([el for el in comp.elements if comp[el] > 0],
                          key=lambda el: el.X)
        most_electroneg = elements[-1].symbol
        poscar = Poscar(structure)
        for key, setting in self.incar_settings.items():
            if key == "MAGMOM":
                mag = []
                for site in structure:
                    if hasattr(site, 'magmom'):
                        mag.append(site.magmom)
                    elif hasattr(site.specie, 'spin'):
                        mag.append(site.specie.spin)
                    elif str(site.specie) in setting:
                        mag.append(setting.get(str(site.specie)))
                    else:
                        mag.append(setting.get(site.specie.symbol, 0.6))
                incar[key] = mag
            elif key in ('LDAUU', 'LDAUJ', 'LDAUL'):
                if most_electroneg in setting.keys():
                    incar[key] = [
                        setting[most_electroneg].get(sym, 0)
                        for sym in poscar.site_symbols
                    ]
                else:
                    incar[key] = [0] * len(poscar.site_symbols)
            elif key == "EDIFF":
                incar[key] = float(setting) * structure.num_sites
            else:
                incar[key] = setting

        has_u = ("LDAUU" in incar and sum(incar['LDAUU']) > 0)
        if has_u:
            # modify LMAXMIX if LSDA+U and you have d or f electrons
            # note that if the user explicitly sets LMAXMIX in settings it will
            # override this logic.
            if 'LMAXMIX' not in self.incar_settings.keys():
                # contains f-electrons
                if any([el.Z > 56 for el in structure.composition]):
                    incar['LMAXMIX'] = 6
                # contains d-electrons
                elif any([el.Z > 20 for el in structure.composition]):
                    incar['LMAXMIX'] = 4
        else:
            for key in incar.keys():
                if key.startswith('LDAU'):
                    del incar[key]

        if self.set_nupdown:
            nupdown = sum([mag if mag > 0.6 else 0 for mag in incar['MAGMOM']])
            incar['NUPDOWN'] = nupdown

        return incar
コード例 #3
0
ファイル: test_vasp_input.py プロジェクト: sikisis/pymatgen
 def test_init(self):
     filepath = os.path.join(test_dir, "INCAR")
     incar = Incar.from_file(filepath)
     incar["LDAU"] = "T"
     self.assertEqual(incar["ALGO"], "Damped", "Wrong Algo")
     self.assertEqual(float(incar["EDIFF"]), 1e-4, "Wrong EDIFF")
     self.assertEqual(type(incar["LORBIT"]), int)
コード例 #4
0
ファイル: custodian_task.py プロジェクト: ctoher/MPWorks
def check_incar(task_type):
    errors = []
    incar = Incar.from_file("INCAR")

    if 'static' in task_type or 'Uniform' in task_type or 'band structure' in task_type:
        if incar["IBRION"] != -1:
            errors.append("IBRION should be -1 for non structure optimization runs")

        if "NSW" in incar and incar["NSW"] != 0:
            errors.append("NSW must be 0 for non structure optimization runs")

    if 'static' in task_type and not incar["LCHARG"]:
            errors.append("LCHARG must be True for static runs")

    if 'Uniform' in task_type and incar["ICHARG"]!=11:
            errors.append("ICHARG must be 11 for Uniform runs")

    if 'band structure' in task_type and incar["ICHARG"]!=11:
            errors.append("ICHARG must be 11 for band structure runs")

    if 'GGA+U' in task_type:
        # check LDAU
        if not incar["LDAU"]:
            errors.append("GGA+U requires LDAU parameter")

        if not incar["LMAXMIX"] >= 4:
            errors.append("GGA+U requires LMAXMIX >= 4")

        if not sum(incar["LDAUU"]) > 0:
            errors.append("GGA+U requires sum(LDAUU)>0")

    return errors
コード例 #5
0
 def test_init(self):
     filepath = os.path.join(test_dir, 'INCAR')
     incar = Incar.from_file(filepath)
     incar["LDAU"] = "T"
     self.assertEqual(incar["ALGO"], "Damped", "Wrong Algo")
     self.assertEqual(float(incar["EDIFF"]), 1e-4, "Wrong EDIFF")
     self.assertEqual(type(incar["LORBIT"]), int)
コード例 #6
0
def check_incar(task_type):
    errors = []
    incar = Incar.from_file("INCAR")

    if 'static' in task_type or 'Uniform' in task_type or 'band structure' in task_type:
        if incar["IBRION"] != -1:
            errors.append(
                "IBRION should be -1 for non structure optimization runs")

        if "NSW" in incar and incar["NSW"] != 0:
            errors.append("NSW must be 0 for non structure optimization runs")

    if 'static' in task_type and not incar["LCHARG"]:
        errors.append("LCHARG must be True for static runs")

    if 'Uniform' in task_type and incar["ICHARG"] != 11:
        errors.append("ICHARG must be 11 for Uniform runs")

    if 'band structure' in task_type and incar["ICHARG"] != 11:
        errors.append("ICHARG must be 11 for band structure runs")

    if 'GGA+U' in task_type:
        # check LDAU
        if not incar["LDAU"]:
            errors.append("GGA+U requires LDAU parameter")

        if not incar["LMAXMIX"] >= 4:
            errors.append("GGA+U requires LMAXMIX >= 4")

        if not sum(incar["LDAUU"]) > 0:
            errors.append("GGA+U requires sum(LDAUU)>0")

    return errors
コード例 #7
0
    def run_task(self, fw_spec):
        chgcar_start = False
        # read the VaspInput from the previous run

        poscar = Poscar.from_file(zpath('POSCAR'))
        incar = Incar.from_file(zpath('INCAR'))

        # figure out what GGA+U values to use and override them
        # LDAU values to use
        mpvis = MPVaspInputSet()
        ggau_incar = mpvis.get_incar(poscar.structure).to_dict
        incar_updates = {
            k: ggau_incar[k]
            for k in ggau_incar.keys() if 'LDAU' in k
        }

        for k in ggau_incar:
            # update any parameters not set explicitly in previous INCAR
            if k not in incar and k in ggau_incar:
                incar_updates[k] = ggau_incar[k]

        incar.update(incar_updates)  # override the +U keys

        # start from the CHGCAR of previous run
        if os.path.exists('CHGCAR'):
            incar['ICHARG'] = 1
            chgcar_start = True

        # write back the new INCAR to the current directory
        incar.write_file('INCAR')
        return FWAction(stored_data={'chgcar_start': chgcar_start})
コード例 #8
0
ファイル: vasp_setup_tasks.py プロジェクト: matk86/MPWorks
    def run_task(self, fw_spec):
        chgcar_start = False
        # read the VaspInput from the previous run

        poscar = Poscar.from_file(zpath('POSCAR'))
        incar = Incar.from_file(zpath('INCAR'))

        # figure out what GGA+U values to use and override them
        # LDAU values to use
        mpvis = MPVaspInputSet()
        ggau_incar = mpvis.get_incar(poscar.structure).to_dict
        incar_updates = {k: ggau_incar[k] for k in ggau_incar.keys() if 'LDAU' in k}

        for k in ggau_incar:
            # update any parameters not set explicitly in previous INCAR
            if k not in incar and k in ggau_incar:
                incar_updates[k] = ggau_incar[k]

        incar.update(incar_updates)  # override the +U keys


        # start from the CHGCAR of previous run
        if os.path.exists('CHGCAR'):
            incar['ICHARG'] = 1
            chgcar_start = True

        # write back the new INCAR to the current directory
        incar.write_file('INCAR')
        return FWAction(stored_data={'chgcar_start': chgcar_start})
コード例 #9
0
ファイル: test_vasp_input.py プロジェクト: ychaojia/pymatgen
    def test_write(self):
        tmp_dir = "VaspInput.testing"
        self.vinput.write_input(tmp_dir)

        filepath = os.path.join(tmp_dir, "INCAR")
        incar = Incar.from_file(filepath)
        self.assertEqual(incar["NSW"], 99)

        for name in ("INCAR", "POSCAR", "POTCAR", "KPOINTS"):
            os.remove(os.path.join(tmp_dir, name))

        os.rmdir(tmp_dir)
コード例 #10
0
 def test_diff(self):
     incar = self.incar
     filepath1 = os.path.join(test_dir, 'INCAR')
     incar1 = Incar.from_file(filepath1)
     filepath2 = os.path.join(test_dir, 'INCAR.2')
     incar2 = Incar.from_file(filepath2)
     self.assertEqual(
         incar1.diff(incar2),
         {'Different': {
             'NELM': {'INCAR1': None, 'INCAR2': 100},
             'ISPIND': {'INCAR1': 2, 'INCAR2': None},
             'LWAVE': {'INCAR1': True, 'INCAR2': False},
             'LDAUPRINT': {'INCAR1': None, 'INCAR2': 1},
             'MAGMOM': {'INCAR1': [6, -6, -6, 6, 0.6, 0.6, 0.6,
                                   0.6, 0.6, 0.6, 0.6, 0.6,
                                   0.6, 0.6, 0.6, 0.6, 0.6,
                                   0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6],
                        'INCAR2': None},
             'NELMIN': {'INCAR1': None, 'INCAR2': 3},
             'ENCUTFOCK': {'INCAR1': 0.0, 'INCAR2': None},
             'HFSCREEN': {'INCAR1': 0.207, 'INCAR2': None},
             'LSCALU': {'INCAR1': False, 'INCAR2': None},
             'ENCUT': {'INCAR1': 500, 'INCAR2': None},
             'NSIM': {'INCAR1': 1, 'INCAR2': None},
             'ICHARG': {'INCAR1': None, 'INCAR2': 1},
             'NSW': {'INCAR1': 99, 'INCAR2': 51},
             'NKRED': {'INCAR1': 2, 'INCAR2': None},
             'NUPDOWN': {'INCAR1': 0, 'INCAR2': None},
             'LCHARG': {'INCAR1': True, 'INCAR2': None},
             'LPLANE': {'INCAR1': True, 'INCAR2': None},
             'ISMEAR': {'INCAR1': 0, 'INCAR2': -5},
             'NPAR': {'INCAR1': 8, 'INCAR2': 1},
             'SYSTEM': {'INCAR1': 'Id=[0] dblock_code=[97763-icsd] formula=[li mn (p o4)] sg_name=[p n m a]',
                        'INCAR2': 'Id=[91090] dblock_code=[20070929235612linio-59.53134651-vasp] formula=[li3 ni3 o6] sg_name=[r-3m]'},
             'ALGO': {'INCAR1': 'Damped', 'INCAR2': 'Fast'},
             'LHFCALC': {'INCAR1': True, 'INCAR2': None},
             'TIME': {'INCAR1': 0.4, 'INCAR2': None}},
          'Same': {'IBRION': 2, 'PREC': 'Accurate', 'ISIF': 3, 'LMAXMIX': 4,
                   'LREAL': 'Auto', 'ISPIN': 2, 'EDIFF': 0.0001,
                   'LORBIT': 11, 'SIGMA': 0.05}})
コード例 #11
0
ファイル: test_vaspio_set.py プロジェクト: bcbwilla/pymatgen
    def test_optics(self):
        if "VASP_PSP_DIR" not in os.environ:
            os.environ["VASP_PSP_DIR"] = test_dir
        self.mpopticsparamset = MPOpticsNonSCFVaspInputSet.from_previous_vasp_run(
            '{}/static_silicon'.format(test_dir), output_dir='optics_test_dir',
            nedos=1145)
        self.assertTrue(os.path.exists('optics_test_dir/CHGCAR'))
        incar = Incar.from_file('optics_test_dir/INCAR')
        self.assertTrue(incar['LOPTICS'])
        self.assertEqual(incar['NEDOS'], 1145)

        #Remove the directory in which the inputs have been created
        shutil.rmtree('optics_test_dir')
コード例 #12
0
    def test_optics(self):
        if "VASP_PSP_DIR" not in os.environ:
            os.environ["VASP_PSP_DIR"] = test_dir
        self.mpopticsparamset = MPOpticsNonSCFVaspInputSet.from_previous_vasp_run(
            '{}/static_silicon'.format(test_dir), output_dir='optics_test_dir',
            nedos=1145)
        self.assertTrue(os.path.exists('optics_test_dir/CHGCAR'))
        incar = Incar.from_file('optics_test_dir/INCAR')
        self.assertTrue(incar['LOPTICS'])
        self.assertEqual(incar['NEDOS'], 1145)

        #Remove the directory in which the inputs have been created
        shutil.rmtree('optics_test_dir')
コード例 #13
0
 def test_diff(self):
     filepath1 = os.path.join(test_dir, 'INCAR')
     incar1 = Incar.from_file(filepath1)
     filepath2 = os.path.join(test_dir, 'INCAR.2')
     incar2 = Incar.from_file(filepath2)
     self.assertEqual(
         incar1.diff(incar2),
         {'Different': {
             'NELM': {'INCAR1': None, 'INCAR2': 100},
             'ISPIND': {'INCAR1': 2, 'INCAR2': None},
             'LWAVE': {'INCAR1': True, 'INCAR2': False},
             'LDAUPRINT': {'INCAR1': None, 'INCAR2': 1},
             'MAGMOM': {'INCAR1': [6, -6, -6, 6, 0.6, 0.6, 0.6,
                                   0.6, 0.6, 0.6, 0.6, 0.6,
                                   0.6, 0.6, 0.6, 0.6, 0.6,
                                   0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6],
                        'INCAR2': None},
             'NELMIN': {'INCAR1': None, 'INCAR2': 3},
             'ENCUTFOCK': {'INCAR1': 0.0, 'INCAR2': None},
             'HFSCREEN': {'INCAR1': 0.207, 'INCAR2': None},
             'LSCALU': {'INCAR1': False, 'INCAR2': None},
             'ENCUT': {'INCAR1': 500, 'INCAR2': None},
             'NSIM': {'INCAR1': 1, 'INCAR2': None},
             'ICHARG': {'INCAR1': None, 'INCAR2': 1},
             'NSW': {'INCAR1': 99, 'INCAR2': 51},
             'NKRED': {'INCAR1': 2, 'INCAR2': None},
             'NUPDOWN': {'INCAR1': 0, 'INCAR2': None},
             'LCHARG': {'INCAR1': True, 'INCAR2': None},
             'LPLANE': {'INCAR1': True, 'INCAR2': None},
             'ISMEAR': {'INCAR1': 0, 'INCAR2': -5},
             'NPAR': {'INCAR1': 8, 'INCAR2': 1},
             'SYSTEM': {'INCAR1': 'Id=[0] dblock_code=[97763-icsd] formula=[li mn (p o4)] sg_name=[p n m a]',
                        'INCAR2': 'Id=[91090] dblock_code=[20070929235612linio-59.53134651-vasp] formula=[li3 ni3 o6] sg_name=[r-3m]'},
             'ALGO': {'INCAR1': 'Damped', 'INCAR2': 'Fast'},
             'LHFCALC': {'INCAR1': True, 'INCAR2': None},
             'TIME': {'INCAR1': 0.4, 'INCAR2': None}},
          'Same': {'IBRION': 2, 'PREC': 'Accurate', 'ISIF': 3, 'LMAXMIX': 4,
                   'LREAL': 'Auto', 'ISPIN': 2, 'EDIFF': 0.0001,
                   'LORBIT': 11, 'SIGMA': 0.05}})
コード例 #14
0
ファイル: jobs.py プロジェクト: cnk118/custodian
    def setup(self):
        """
        Performs initial setup for VaspJob, including overriding any settings
        and backing up.
        """
        files = os.listdir(".")
        num_structures = 0
        if not set(files).issuperset(VASP_INPUT_FILES):
            for f in files:
                try:
                    struct = read_structure(f)
                    num_structures += 1
                except:
                    pass
            if num_structures != 1:
                raise RuntimeError("{} structures found. Unable to continue."
                                   .format(num_structures))
            else:
                self.default_vis.write_input(struct, ".")

        if self.backup:
            for f in VASP_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))

        if self.auto_npar:
            try:
                incar = Incar.from_file("INCAR")
                #Only optimized NPAR for non-HF and non-RPA calculations.
                if not (incar.get("LHFCALC") or incar.get("LRPA") or
                        incar.get("LEPSILON")):
                    if incar.get("IBRION") in [5, 6, 7, 8]:
                        # NPAR should not be set for Hessian matrix
                        # calculations, whether in DFPT or otherwise.
                        del incar["NPAR"]
                    else:
                        import multiprocessing
                        # try sge environment variable first
                        # (since multiprocessing counts cores on the current machine only)
                        ncores = os.environ.get('NSLOTS') or multiprocessing.cpu_count()
                        ncores = int(ncores)
                        for npar in range(int(round(math.sqrt(ncores))),
                                          ncores):
                            if ncores % npar == 0:
                                incar["NPAR"] = npar
                                break
                    incar.write_file("INCAR")
            except:
                pass

        if self.settings_override is not None:
            VaspModder().apply_actions(self.settings_override)
コード例 #15
0
ファイル: test_vasp_input.py プロジェクト: sikisis/pymatgen
 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)
コード例 #16
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)
コード例 #17
0
ファイル: handlers.py プロジェクト: image-tester/custodian
 def check(self):
     incar = Incar.from_file("INCAR")
     self.errors = set()
     with open(self.output_filename, "r") as f:
         for line in f:
             l = line.strip()
             for err, msgs in VaspErrorHandler.error_msgs.items():
                 for msg in msgs:
                     if l.find(msg) != -1:
                         # this checks if we want to run a charged
                         # computation (e.g., defects) if yes we don't
                         # want to kill it because there is a change in e-
                         # density (brmix error)
                         if err == "brmix" and 'NELECT' in incar:
                             continue
                         self.errors.add(err)
     return len(self.errors) > 0
コード例 #18
0
ファイル: jobs.py プロジェクト: image-tester/custodian
    def postprocess(self):
        """
        Postprocessing includes renaming and gzipping where necessary.
        Also copies the magmom to the incar if necessary
        """
        for f in VASP_OUTPUT_FILES + [self.output_file]:
            if os.path.exists(f):
                if self.final and self.suffix != "":
                    shutil.move(f, "{}{}".format(f, self.suffix))
                elif self.suffix != "":
                    shutil.copy(f, "{}{}".format(f, self.suffix))

        if self.copy_magmom and not self.final:
            try:
                outcar = Outcar("OUTCAR")
                magmom = [m['tot'] for m in outcar.magnetization]
                incar = Incar.from_file("INCAR")
                incar['MAGMOM'] = magmom
                incar.write_file("INCAR")
            except:
                logging.error('MAGMOM copy from OUTCAR to INCAR failed')

        if self.gzipped:
            gzip_dir(".")
コード例 #19
0
ファイル: vasp_io_tasks.py プロジェクト: matk86/MPWorks
 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')
コード例 #20
0
ファイル: phonon_tasks.py プロジェクト: miaoliu/MPWorks
 def run_task(self, fw_spec):
     incar = Incar.from_file("INCAR")
     incar.update({"ISIF": 2})
     incar.write_file("INCAR")
     return FWAction()
コード例 #21
0
ファイル: hive.py プロジェクト: jesuansito/pymatgen
    def assimilate(self, path):
        files = os.listdir(path)
        try:
            files_to_parse = {}
            if "relax1" in files and "relax2" in files:
                for filename in ("INCAR", "POTCAR", "POSCAR"):
                    search_str = os.path.join(path, "relax1", filename + "*")
                    files_to_parse[filename] = glob.glob(search_str)[0]
                for filename in ("CONTCAR", "OSZICAR"):
                    search_str = os.path.join(path, "relax2", filename + "*")
                    files_to_parse[filename] = glob.glob(search_str)[-1]
            else:
                files_to_parse["INCAR"] = glob.glob(os.path.join(path,
                                                                 "INCAR*"))[0]
                files_to_parse["POTCAR"] = glob.glob(
                    os.path.join(path, "POTCAR*"))[-1]

                for filename in ("CONTCAR", "OSZICAR", "POSCAR"):
                    files = glob.glob(os.path.join(path, filename + "*"))
                    if len(files) == 1:
                        files_to_parse[filename] = files[0]
                    elif len(files) > 1:
                        """
                        This is a bit confusing, since there maybe be
                        multiple steps. By default, assimilate will try to find
                        a file simply named filename, filename.bz2, or
                        filename.gz.  Failing which it will try to get a relax2
                        from an aflow style run if possible. Or else, a
                        randomly chosen file is chosen.
                        """
                        for fname in files:
                            if fnmatch.fnmatch(os.path.basename(fname),
                                               "{}(\.gz|\.bz2)*"
                                               .format(filename)):
                                files_to_parse[filename] = fname
                                break
                            if fname == "POSCAR" and \
                                    re.search("relax1", fname):
                                files_to_parse[filename] = fname
                                break
                            if (fname in ("CONTCAR", "OSZICAR") and
                                    re.search("relax2", fname)):
                                files_to_parse[filename] = fname
                                break
                            files_to_parse[filename] = fname

            poscar = Poscar.from_file(files_to_parse["POSCAR"])
            contcar = Poscar.from_file(files_to_parse["CONTCAR"])

            param = {}

            incar = Incar.from_file(files_to_parse["INCAR"])
            if "LDAUU" in incar:
                param["hubbards"] = dict(zip(poscar.site_symbols,
                                             incar["LDAUU"]))
            else:
                param["hubbards"] = {}
            param["is_hubbard"] = \
                incar.get("LDAU", False) and sum(param["hubbards"].values()) > 0
            param["run_type"] = "GGA+U" if param["is_hubbard"] else "GGA"
            potcar = Potcar.from_file(files_to_parse["POTCAR"])
            param["potcar_symbols"] = potcar.symbols
            oszicar = Oszicar(files_to_parse["OSZICAR"])
            energy = oszicar.final_energy
            structure = contcar.structure
            initial_vol = poscar.structure.volume
            final_vol = contcar.structure.volume
            delta_volume = (final_vol / initial_vol - 1)
            data = {"filename": path, "delta_volume": delta_volume}
            if self._inc_structure:
                entry = ComputedStructureEntry(structure, energy,
                                               parameters=param,
                                               data=data)
            else:
                entry = ComputedEntry(structure.composition, energy,
                                      parameters=param, data=data)
            return entry

        except Exception as ex:
            logger.debug("error in {}: {}".format(path, ex))
            return None
コード例 #22
0
ファイル: phonon_tasks.py プロジェクト: matk86/MPWorks
 def run_task(self, fw_spec):
     incar = Incar.from_file(zpath("INCAR"))
     incar.update({"ISIF": 2})
     incar.write_file("INCAR")
     return FWAction()
コード例 #23
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")
コード例 #24
0
ファイル: vasp_io_tasks.py プロジェクト: matk86/MPWorks
 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')
コード例 #25
0
ファイル: hive.py プロジェクト: ATNDiaye/pymatgen
    def assimilate(self, path):
        files = os.listdir(path)
        try:
            files_to_parse = {}
            if "relax1" in files and "relax2" in files:
                for filename in ("INCAR", "POTCAR", "POSCAR"):
                    search_str = os.path.join(path, "relax1", filename + "*")
                    files_to_parse[filename] = glob.glob(search_str)[0]
                for filename in ("CONTCAR", "OSZICAR"):
                    search_str = os.path.join(path, "relax2", filename + "*")
                    files_to_parse[filename] = glob.glob(search_str)[-1]
            else:
                for filename in (
                    "INCAR", "POTCAR", "CONTCAR", "OSZICAR", "POSCAR", "DYNMAT"
                ):
                    files = glob.glob(os.path.join(path, filename + "*"))
                    if len(files) < 1:
                        continue
                    if len(files) == 1 or filename == "INCAR" or \
                       filename == "POTCAR" or filename == "DYNMAT":
                        files_to_parse[filename] = files[-1]\
                            if filename == "POTCAR" else files[0]
                    elif len(files) > 1:
                        """
                        This is a bit confusing, since there maybe be
                        multiple steps. By default, assimilate will try to find
                        a file simply named filename, filename.bz2, or
                        filename.gz.  Failing which it will try to get a relax2
                        from a custodian double relaxation style run if
                        possible. Or else, a random file is chosen.
                        """
                        for fname in files:
                            if fnmatch.fnmatch(os.path.basename(fname),
                                               "{}(\.gz|\.bz2)*"
                                               .format(filename)):
                                files_to_parse[filename] = fname
                                break
                            if fname == "POSCAR" and \
                                    re.search("relax1", fname):
                                files_to_parse[filename] = fname
                                break
                            if (fname in ("CONTCAR", "OSZICAR") and
                                    re.search("relax2", fname)):
                                files_to_parse[filename] = fname
                                break
                            files_to_parse[filename] = fname

            poscar, contcar, incar, potcar, oszicar, dynmat = [None]*6
            if 'POSCAR' in files_to_parse:
                poscar = Poscar.from_file(files_to_parse["POSCAR"])
            if 'CONTCAR' in files_to_parse:
                contcar = Poscar.from_file(files_to_parse["CONTCAR"])
            if 'INCAR' in files_to_parse:
                incar = Incar.from_file(files_to_parse["INCAR"])
            if 'POTCAR' in files_to_parse:
                potcar = Potcar.from_file(files_to_parse["POTCAR"])
            if 'OSZICAR' in files_to_parse:
                oszicar = Oszicar(files_to_parse["OSZICAR"])
            if 'DYNMAT' in files_to_parse:
                dynmat = Dynmat(files_to_parse["DYNMAT"])

            param = {"hubbards":{}}
            if poscar is not None and incar is not None and "LDAUU" in incar:
                param["hubbards"] = dict(zip(poscar.site_symbols,
                                             incar["LDAUU"]))
            param["is_hubbard"] = (
                incar.get("LDAU", False) and sum(param["hubbards"].values()) > 0
            ) if incar is not None else False
            param["run_type"] = None
            if incar is not None:
                param["run_type"] = "GGA+U" if param["is_hubbard"] else "GGA"
            param["history"] = _get_transformation_history(path)
            param["potcar_spec"] = potcar.spec if potcar is not None else None
            energy = oszicar.final_energy if oszicar is not None else 1e10
            structure = contcar.structure if contcar is not None\
                else poscar.structure
            initial_vol = poscar.structure.volume if poscar is not None else \
                None
            final_vol = contcar.structure.volume if contcar is not None else \
                None
            delta_volume = None
            if initial_vol is not None and final_vol is not None:
                delta_volume = (final_vol / initial_vol - 1)
            data = {"filename": path, "delta_volume": delta_volume}
            if dynmat is not None:
                data['phonon_frequencies'] = dynmat.get_phonon_frequencies()
            if self._inc_structure:
                entry = ComputedStructureEntry(
                    structure, energy, parameters=param, data=data
                )
            else:
                entry = ComputedEntry(
                  structure.composition, energy, parameters=param, data=data
                )
            return entry

        except Exception as ex:
            logger.debug("error in {}: {}".format(path, ex))
            return None
コード例 #26
0
ファイル: hive.py プロジェクト: bkappes/pymatgen
    def assimilate(self, path):
        files = os.listdir(path)
        try:
            files_to_parse = {}
            if "relax1" in files and "relax2" in files:
                for filename in ("INCAR", "POTCAR", "POSCAR"):
                    search_str = os.path.join(path, "relax1", filename + "*")
                    files_to_parse[filename] = glob.glob(search_str)[0]
                for filename in ("CONTCAR", "OSZICAR"):
                    search_str = os.path.join(path, "relax2", filename + "*")
                    files_to_parse[filename] = glob.glob(search_str)[-1]
            else:
                files_to_parse["INCAR"] = glob.glob(
                    os.path.join(path, "INCAR*"))[0]
                files_to_parse["POTCAR"] = glob.glob(
                    os.path.join(path, "POTCAR*"))[-1]

                for filename in ("CONTCAR", "OSZICAR", "POSCAR"):
                    files = glob.glob(os.path.join(path, filename + "*"))
                    if len(files) == 1:
                        files_to_parse[filename] = files[0]
                    elif len(files) > 1:
                        """
                        This is a bit confusing, since there maybe be
                        multiple steps. By default, assimilate will try to find
                        a file simply named filename, filename.bz2, or
                        filename.gz.  Failing which it will try to get a relax2
                        from an aflow style run if possible. Or else, a
                        randomly chosen file is chosen.
                        """
                        for fname in files:
                            if fnmatch.fnmatch(
                                    os.path.basename(fname),
                                    "{}(\.gz|\.bz2)*".format(filename)):
                                files_to_parse[filename] = fname
                                break
                            if fname == "POSCAR" and \
                                    re.search("relax1", fname):
                                files_to_parse[filename] = fname
                                break
                            if (fname in ("CONTCAR", "OSZICAR")
                                    and re.search("relax2", fname)):
                                files_to_parse[filename] = fname
                                break
                            files_to_parse[filename] = fname

            poscar = Poscar.from_file(files_to_parse["POSCAR"])
            contcar = Poscar.from_file(files_to_parse["CONTCAR"])

            param = {}

            incar = Incar.from_file(files_to_parse["INCAR"])
            if "LDAUU" in incar:
                param["hubbards"] = dict(
                    zip(poscar.site_symbols, incar["LDAUU"]))
            else:
                param["hubbards"] = {}
            param["is_hubbard"] = (incar.get("LDAU", False)
                                   and sum(param["hubbards"].values()) > 0)
            param["run_type"] = "GGA+U" if param["is_hubbard"] else "GGA"
            param["history"] = _get_transformation_history(path)

            potcar = Potcar.from_file(files_to_parse["POTCAR"])
            param["potcar_symbols"] = potcar.symbols
            oszicar = Oszicar(files_to_parse["OSZICAR"])
            energy = oszicar.final_energy
            structure = contcar.structure
            initial_vol = poscar.structure.volume
            final_vol = contcar.structure.volume
            delta_volume = (final_vol / initial_vol - 1)
            data = {"filename": path, "delta_volume": delta_volume}
            if self._inc_structure:
                entry = ComputedStructureEntry(structure,
                                               energy,
                                               parameters=param,
                                               data=data)
            else:
                entry = ComputedEntry(structure.composition,
                                      energy,
                                      parameters=param,
                                      data=data)
            return entry

        except Exception as ex:
            logger.debug("error in {}: {}".format(path, ex))
            return None
コード例 #27
0
 def test_write(self):
     tempfname = "INCAR.testing"
     self.incar.write_file(tempfname)
     i = Incar.from_file(tempfname)
     self.assertEqual(i, self.incar)
     os.remove(tempfname)
コード例 #28
0
ファイル: PBE_2nd.py プロジェクト: qimin/python_script
from pymatgen.matproj.rest import MPRester
from pymatgen.io.vaspio_set import MPVaspInputSet, DictVaspInputSet
from pymatgen.io.vaspio.vasp_input import Kpoints,Incar
from pymatgen.io.vaspio.vasp_output import Outcar, Vasprun
import os

if __name__ == '__main__':
    mpr = MPRester(api_key="UhlZvcEux2kmJSQx")

id_expgap = open("ids.txt", "r")

for line in id_expgap:
    words=line.split()
    print words
    id_line=words[0]
    vasp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), str(id_line))
    vasp_run = Vasprun(os.path.join(vasp_dir,"vasprun.xml")).to_dict
    nelect = int(vasp_run['input']['parameters']['NELECT'])
    nband = nelect * 6 +96 - nelect % 96 

    os.chdir(id_line)
    #s = mpr.get_structure_by_material_id(id_line)
    user_incar_settings={"ALGO":'Exact',"NSW":0,"NELM":1,"NBANDS":nband,"LOPTICS":True,"LWAVE":True}
    mpvis = MPVaspInputSet(user_incar_settings=user_incar_settings)
    incar = Incar.from_file(os.path.join(vasp_dir,"INCAR"))
    incar.update(user_incar_settings)
    incar.write_file('INCAR')
    os.chdir('..')
id_expgap.close()
コード例 #29
0
ファイル: vaspio_set.py プロジェクト: leicheng/pymatgen
    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"))
コード例 #30
0
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)
コード例 #31
0
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)
コード例 #32
0
 def setUp(self):
     file_name = os.path.join(test_dir, 'INCAR')
     self.incar = Incar.from_file(file_name)
コード例 #33
0
ファイル: test_vasp_input.py プロジェクト: sikisis/pymatgen
 def test_diff(self):
     filepath1 = os.path.join(test_dir, "INCAR")
     incar1 = Incar.from_file(filepath1)
     filepath2 = os.path.join(test_dir, "INCAR.2")
     incar2 = Incar.from_file(filepath2)
     self.assertEqual(
         incar1.diff(incar2),
         {
             "Different": {
                 "NELM": {"INCAR1": None, "INCAR2": 100},
                 "ISPIND": {"INCAR1": 2, "INCAR2": None},
                 "LWAVE": {"INCAR1": True, "INCAR2": False},
                 "LDAUPRINT": {"INCAR1": None, "INCAR2": 1},
                 "MAGMOM": {
                     "INCAR1": [
                         6,
                         -6,
                         -6,
                         6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                         0.6,
                     ],
                     "INCAR2": None,
                 },
                 "NELMIN": {"INCAR1": None, "INCAR2": 3},
                 "ENCUTFOCK": {"INCAR1": 0.0, "INCAR2": None},
                 "HFSCREEN": {"INCAR1": 0.207, "INCAR2": None},
                 "LSCALU": {"INCAR1": False, "INCAR2": None},
                 "ENCUT": {"INCAR1": 500, "INCAR2": None},
                 "NSIM": {"INCAR1": 1, "INCAR2": None},
                 "ICHARG": {"INCAR1": None, "INCAR2": 1},
                 "NSW": {"INCAR1": 99, "INCAR2": 51},
                 "NKRED": {"INCAR1": 2, "INCAR2": None},
                 "NUPDOWN": {"INCAR1": 0, "INCAR2": None},
                 "LCHARG": {"INCAR1": True, "INCAR2": None},
                 "LPLANE": {"INCAR1": True, "INCAR2": None},
                 "ISMEAR": {"INCAR1": 0, "INCAR2": -5},
                 "NPAR": {"INCAR1": 8, "INCAR2": 1},
                 "SYSTEM": {
                     "INCAR1": "Id=[0] dblock_code=[97763-icsd] formula=[li mn (p o4)] sg_name=[p n m a]",
                     "INCAR2": "Id=[91090] dblock_code=[20070929235612linio-59.53134651-vasp] formula=[li3 ni3 o6] sg_name=[r-3m]",
                 },
                 "ALGO": {"INCAR1": "Damped", "INCAR2": "Fast"},
                 "LHFCALC": {"INCAR1": True, "INCAR2": None},
                 "TIME": {"INCAR1": 0.4, "INCAR2": None},
             },
             "Same": {
                 "IBRION": 2,
                 "PREC": "Accurate",
                 "ISIF": 3,
                 "LMAXMIX": 4,
                 "LREAL": "Auto",
                 "ISPIN": 2,
                 "EDIFF": 0.0001,
                 "LORBIT": 11,
                 "SIGMA": 0.05,
             },
         },
     )
コード例 #34
0
 def test_to_dict_and_from_dict(self):
     file_name = os.path.join(test_dir, 'INCAR')
     incar = Incar.from_file(file_name)
     d = incar.to_dict
     incar2 = Incar.from_dict(d)
     self.assertEqual(incar, incar2)
コード例 #35
0
ファイル: VaspSubmission.py プロジェクト: rousseab/VaspDrive
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
コード例 #36
0
 def test_as_dict_and_from_dict(self):
     d = self.incar.as_dict()
     incar2 = Incar.from_dict(d)
     self.assertEqual(self.incar, incar2)
コード例 #37
0
ファイル: bands.py プロジェクト: ldamewood/dftscripts
def main():
    """ Main routine """
    parser = argparse.ArgumentParser(description='Calculate the band structure of a vasp calculation.')
    parser.add_argument('-d', '--density', nargs='?', default=10, type=int,
                        help='k-point density of the bands (default: 10)')
    parser.add_argument('-s', '--sigma', nargs='?', default=0.04, type=float,
                        help='SIGMA value in eV (default: 0.04)')
    parser.add_argument('-l', '--linemode', nargs='?', default=None, type=str,
                        help='linemode file')
    parser.add_argument('-v', '--vasp', nargs='?', default='vasp', type=str,
                        help='vasp executable')
    args = parser.parse_args()
    
    line_density = args.density
    line_file = args.linemode

    # Check that required files exist
    _check('vasprun.xml')
    _check('INCAR')
    _check('POSCAR')
    _check('POTCAR')
    _check('CHGCAR')

    # Get IBZ from vasprun
    vasprun = Vasprun('vasprun.xml')
    ibz = HighSymmKpath(vasprun.final_structure)

    # Create a temp directory
    print('Create temporary directory ... ', end='')
    tempdir = mkdtemp()
    print(tempdir)

    # Edit the inputs
    print('Saving new inputs in temporary directory ... ')
    incar = Incar.from_file('INCAR')
    print('Making the following changes to the INCAR:')
    print('  ICHARG = 11')
    print('  ISMEAR = 0')
    print('  SIGMA = %f' % args.sigma)
    incar['ICHARG'] = 11  # Constant density
    incar['ISMEAR'] = 0  # Gaussian Smearing
    incar['SIGMA'] = args.sigma  # Smearing temperature
    incar.write_file(os.path.join(tempdir, 'INCAR'))
    # Generate line-mode kpoint file

    if line_file is None:
        print('Creating a new KPOINTS file:')
        kpoints = _automatic_kpoints(line_density, ibz)
        kpoints.write_file(os.path.join(tempdir, 'KPOINTS'))
        print('### BEGIN KPOINTS')
        print(kpoints)
        print('### END KPOINTS')
    else:
        cp(line_file, os.path.join(tempdir, 'KPOINTS'))
    
    # Copy other files (May take some time...)
    print('Copying POSCAR, POTCAR and CHGCAR to the temporary directory.')
    cp('POSCAR', os.path.join(tempdir, 'POSCAR'))
    cp('POTCAR', os.path.join(tempdir, 'POTCAR'))
    cp('CHGCAR', os.path.join(tempdir, 'CHGCAR'))

    # cd to temp directory and run vasp
    path = os.getcwd()
    os.chdir(tempdir)
    print('Running VASP in the temporary directory ...')
    try:
        check_call(args.vasp)
    except CalledProcessError:
        print('There was an error running VASP')
        _clean_exit(path, tempdir)

    # Read output
    vasprun = Vasprun('vasprun.xml')
    ibz = HighSymmKpath(vasprun.final_structure)
    _, _ = ibz.get_kpoints(line_density)
    bands = vasprun.get_band_structure()
    print('Success! Efermi = %f' % bands.efermi)
    
    # Backup vasprun.xml only
    print('Making a gzip backup of vasprun.xml called bands_vasprun.xml.gz')
    zfile = os.path.join(path, 'bands_vasprun.xml.gz')
    try:
        with gzip.open(zfile, 'wb') as gz, open('vasprun.xml', 'rb') as vr:
            gz.writelines(vr)
    except (OSError, IOError):
        print('There was an error with gzip')
        _clean_exit(path, tempdir)

    # Return to original path
    os.chdir(path)

    # Write band structure
    
    # There may be multiple bands due to spin or noncollinear.
    for key, item in bands.bands.items():
        print('Preparing bands_%s.csv' % key)
        
        kpts = []

        # Get list of kpoints
        for kpt in bands.kpoints:
            kpts.append(kpt.cart_coords)
        
        # Subtract fermi energy
        print('Shifting energies so Efermi = 0.')
        band = numpy.array(item) - bands.efermi

        # Prepend kpoint vector as label
        out = numpy.hstack([kpts, band.T])
        
        final = []
        lastrow = float('inf') * numpy.ones(3)
        for row in out:
            if numpy.linalg.norm(row[:3] - lastrow) > 1.e-12:
                final.append(row)
            lastrow = row[:3]

        # Write bands to csv file.
        print('Writing bands_%s.csv to disk' % key)
        with open('bands_%s.csv' % key, 'w+') as f:
            numpy.savetxt(f, numpy.array(final), delimiter=',', header=' kptx, kpty, kptz, band1, band2, ... ')

    # Delete temporary directory
    _clean_exit(path, tempdir, 0)
コード例 #38
0
ファイル: test_vasp_input.py プロジェクト: sikisis/pymatgen
 def test_to_dict_and_from_dict(self):
     file_name = os.path.join(test_dir, "INCAR")
     incar = Incar.from_file(file_name)
     d = incar.to_dict
     incar2 = Incar.from_dict(d)
     self.assertEqual(incar, incar2)
コード例 #39
0
 def test_as_dict_and_from_dict(self):
     d = self.incar.as_dict()
     incar2 = Incar.from_dict(d)
     self.assertEqual(self.incar, incar2)
コード例 #40
0
 def test_write(self):
     tempfname = "INCAR.testing"
     self.incar.write_file(tempfname)
     i = Incar.from_file(tempfname)
     self.assertEqual(i, self.incar)
     os.remove(tempfname)
コード例 #41
0
 def setUp(self):
     file_name = os.path.join(test_dir, 'INCAR')
     self.incar = Incar.from_file(file_name)