Пример #1
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})
Пример #2
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
Пример #3
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})
Пример #4
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)
Пример #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 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)
Пример #8
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}})
Пример #9
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')
Пример #10
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}})
Пример #11
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')
Пример #12
0
    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)
Пример #13
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)
Пример #14
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)
Пример #15
0
 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
Пример #16
0
    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(".")
Пример #17
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)
Пример #18
0
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)
Пример #19
0
 def run_task(self, fw_spec):
     incar = Incar.from_file("INCAR")
     incar.update({"ISIF": 2})
     incar.write_file("INCAR")
     return FWAction()
Пример #20
0
 def run_task(self, fw_spec):
     incar = Incar.from_file(zpath("INCAR"))
     incar.update({"ISIF": 2})
     incar.write_file("INCAR")
     return FWAction()
Пример #21
0
 def setUp(self):
     file_name = os.path.join(test_dir, 'INCAR')
     self.incar = Incar.from_file(file_name)
Пример #22
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,
             },
         },
     )
Пример #23
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)
Пример #24
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)
Пример #25
0
    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
Пример #26
0
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()
Пример #27
0
    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
Пример #28
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)
Пример #29
0
    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
Пример #30
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"))
Пример #31
0
 def setUp(self):
     file_name = os.path.join(test_dir, 'INCAR')
     self.incar = Incar.from_file(file_name)