Ejemplo n.º 1
0
    def test_static_run_correction(self):
        shutil.copy("OSZICAR.empty", "OSZICAR")
        s1 = Structure.from_file("POSCAR")
        incar = Incar.from_file("INCAR")

        # Test for NSW 0
        incar.update({"NSW": 0})
        incar.write_file("INCAR")
        h = VaspErrorHandler("vasp.out")
        self.assertEqual(h.check(), True)
        d = h.correct()
        self.assertEqual(d["errors"], ["zpotrf"])
        s2 = Structure.from_file("POSCAR")
        self.assertAlmostEqual(s2.volume, s1.volume, 3)
        self.assertEqual(Incar.from_file("INCAR")["ISYM"], 0)

        # Test for ISIF 0-2
        incar.update({"NSW": 99, "ISIF": 2})
        incar.write_file("INCAR")
        h = VaspErrorHandler("vasp.out")
        self.assertEqual(h.check(), True)
        d = h.correct()
        self.assertEqual(d["errors"], ["zpotrf"])
        s2 = Structure.from_file("POSCAR")
        self.assertAlmostEqual(s2.volume, s1.volume, 3)
        self.assertEqual(Incar.from_file("INCAR")["ISYM"], 0)
Ejemplo n.º 2
0
 def test_check_correct_scan_metal(self):
     h = IncorrectSmearingHandler()
     self.assertTrue(h.check())
     d = h.correct()
     self.assertEqual(d["errors"], ["IncorrectSmearing"])
     self.assertEqual(Incar.from_file("INCAR")["ISMEAR"], 2)
     self.assertEqual(Incar.from_file("INCAR")["SIGMA"], 0.2)
     os.remove("vasprun.xml")
Ejemplo n.º 3
0
 def test_eddrmm(self):
     h = VaspErrorHandler("vasp.eddrmm")
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["eddrmm"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["ALGO"], "Normal")
     self.assertEqual(h.correct()["errors"], ["eddrmm"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["POTIM"], 0.25)
Ejemplo n.º 4
0
 def test_rhosyg_vasp6(self):
     h = VaspErrorHandler("vasp6.rhosyg")
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["rhosyg"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["SYMPREC"], 1e-4)
     self.assertEqual(h.correct()["errors"], ["rhosyg"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["ISYM"], 0)
    def get_Incar(self):
        ''' Reads the file titled INCAR from the current working directory '''
        ''' Updates the old_incar object to the new_incar object using self.tags '''
        ''' Returns both the old_incar and new_incar objects (pymatgen.io.vasp.inputs.Incar) '''

        old_incar = Incar.from_file(self.path + '/INCAR')
        new_incar = Incar.from_file(self.path + '/INCAR')
        new_incar.update(self.tags)

        return old_incar, new_incar
Ejemplo n.º 6
0
    def test_posmap_vasp6(self):
        h = VaspErrorHandler("vasp6.posmap")
        self.assertEqual(h.check(), True)
        self.assertEqual(h.correct()["errors"], ["posmap"])
        i = Incar.from_file("INCAR")
        self.assertAlmostEqual(i["SYMPREC"], 1e-6)

        self.assertEqual(h.check(), True)
        self.assertEqual(h.correct()["errors"], ["posmap"])
        i = Incar.from_file("INCAR")
        self.assertAlmostEqual(i["SYMPREC"], 1e-4)
Ejemplo n.º 7
0
    def test_bravais(self):
        h = VaspErrorHandler("vasp6.bravais")
        self.assertEqual(h.check(), True)
        self.assertEqual(h.correct()["errors"], ["bravais"])
        i = Incar.from_file("INCAR")
        self.assertEqual(i["SYMPREC"], 1e-4)

        shutil.copy("INCAR.symprec", "INCAR")
        h = VaspErrorHandler("vasp6.bravais")
        self.assertEqual(h.check(), True)
        self.assertEqual(h.correct()["errors"], ["bravais"])
        i = Incar.from_file("INCAR")
        self.assertEqual(i["SYMPREC"], 1e-5)
Ejemplo n.º 8
0
def plot_enc_convergence(directory="../vasp/examples/SiOptb88/",
                         plot=False,
                         filename="."):
    """
    Plot convergence for plane-wave cut-off data
    Works only if jobs run through jarvis-tools framework
    
    Args:
       directory: parent directory for job run
    Returns:
           matplotlib object, converged cut-off value
    """

    x = []
    y = []
    for a in glob.glob(str(directory) + str("/*.json")):
        if "MAIN-RELAX" in a:
            main_inc = str(a.split(".json")[0]) + str("/") + str("INCAR")
            main_inc_obj = Incar.from_file(main_inc)
            convg_encut = float(main_inc_obj["ENCUT"])
        elif "ENCUT" in a:
            run = str(a.split(".json")[0]) + str("/") + str("vasprun.xml")
            contcar = Structure.from_file((a.split(".json")[0]) + str("/") +
                                          str("CONTCAR"))
            vrun = Vasprun(run)
            infile = str(a.split(".json")[0]) + str("/") + str("INCAR")
            inc = Incar.from_file(infile)
            encut = inc["ENCUT"]
            en = float(
                vrun.final_energy)  # /float(contcar.composition.num_atoms)
            x.append(encut)
            y.append(en)
    order = np.argsort(x)
    xs = np.array(x)[order]
    ys = np.array(y)[order]
    plt = get_publication_quality_plot(14, 10)
    plt.ylabel("Energy (eV)")
    plt.plot(xs, ys, "s-", linewidth=2, markersize=10)
    plt.xlabel("Increment in ENCUT ")
    ax = plt.gca()
    ax.get_yaxis().get_major_formatter().set_useOffset(False)
    plt.title(str("Converged at ") + str(int(convg_encut)) + str("eV"),
              fontsize=26)
    # filename=str('Encut.png')
    plt.tight_layout()
    if plot == True:
        plt.savefig(filename)
        plt.close()

    return plt, convg_encut
Ejemplo n.º 9
0
 def test_finite_difference_ncore(self):
     h = VaspErrorHandler("vasp.fd_ncore")
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["dfpt_ncore"])
     incar = Incar.from_file("INCAR")
     self.assertTrue("NPAR" not in incar)
     self.assertTrue("NCORE" not in incar)
Ejemplo n.º 10
0
def get_directories_VaspJobNotDone(root_dir):
    with cd(root_dir):  ### avoid the link problems
        root_dir_real = os.getcwd()
    scan = subprocess.Popen(['find', root_dir_real, '-name', 'POSCAR'],
                            stdout=subprocess.PIPE)
    scan.wait()
    pos_coll = scan.stdout.read().split()
    pos_dirs = [os.path.split(i)[0] for i in pos_coll]
    vaspjob_dirs = []
    for dir in pos_dirs:
        try:
            pos = Poscar.from_file(os.path.join(dir, 'POSCAR'))
            pot = Potcar.from_file(os.path.join(dir, 'POTCAR'))
            incar = Incar.from_file(os.path.join(dir, 'INCAR'))
            kpt = Kpoints.from_file(os.path.join(dir, 'KPOINTS'))
        except:
            print 'input files are not ready in %s' % dir
        else:
            try:
                out = Outcar(os.path.join(dir, 'OUTCAR'))
                if len(out.run_stats) != 7:
                    vaspjob_dir.append(dir)
            except:
                vaspjob_dirs.append(dir)
    return vaspjob_dirs
Ejemplo n.º 11
0
    def generate_input(self, directory, step, xc, import_kpath):
        flags = {}
        flags.update(self.general_flags)
        flags.update(self.input_dict[step])
        if step == 'scf':
            if xc == 'pbe':
                flags.update(self.input_dict[xc])
            calc = Vasp2(self.atoms,directory=directory,kpts=self.struct_info['kgrid_'+xc],gamma=True,**flags)
            calc.write_input(self.atoms)
            if str(self.atoms.symbols) in ['Ni2O2']:
                mom_list = {'Ni':2,'Mn':5,'Co':3,'Fe':4}
                s = str(self.atoms.symbols[0])
                incar_scf = Incar.from_file(directory+'/INCAR')
                incar_scf['MAGMOM'] = '%s -%s 0 0' %(mom_list[s],mom_list[s])
                incar_scf.write_file(directory+'/INCAR')

            self.modify_poscar(path=directory)
        elif step == 'band':
            flags.update(self.input_dict[xc])
            calc = Vasp2(self.atoms,directory=directory,gamma=True,**flags)
            calc.write_input(self.atoms)
            self.modify_poscar(path=directory)
            if xc == 'pbe':
                self.kpt4pbeband(directory, import_kpath)
            elif xc == 'hse':
                print(directory)
                self.kpt4hseband(directory, import_kpath)
Ejemplo n.º 12
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).as_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})
Ejemplo n.º 13
0
    def test_aliasing_incar(self):
        os.chdir(os.path.join(test_dir, "aliasing"))
        shutil.copy("INCAR", "INCAR.orig")
        h = AliasingErrorHandler("vasp.aliasing_incar")
        h.check()
        d = h.correct()

        self.assertEqual(d["errors"], ['aliasing_incar'])
        self.assertEqual(d["actions"],
                         [{'action': {'_unset': {'NGY':1, 'NGZ': 1}},
                           'dict': 'INCAR'}, {"file": "CHGCAR",
                            "action": {"_file_delete": {'mode': "actual"}}},
                          {"file": "WAVECAR",
                            "action": {"_file_delete": {'mode': "actual"}}}])

        incar = Incar.from_file('INCAR.orig')
        incar["ICHARG"] = 10
        incar.write_file("INCAR")
        d = h.correct()
        self.assertEqual(d["errors"], ['aliasing_incar'])
        self.assertEqual(d["actions"],
                         [{'action': {'_unset': {'NGY': 1, 'NGZ': 1}},
                           'dict': 'INCAR'}])

        shutil.move("INCAR.orig", "INCAR")
        clean_dir()
        os.chdir(test_dir)
Ejemplo n.º 14
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 Exception:
                logger.error("MAGMOM copy from OUTCAR to INCAR failed")

        # Remove continuation so if a subsequent job is run in
        # the same directory, will not restart this job.
        if os.path.exists("continue.json"):
            os.remove("continue.json")
Ejemplo n.º 15
0
    def test_check(self):

        shutil.copy("INCAR", "INCAR.orig")

        h = DriftErrorHandler(max_drift=0.05, to_average=11)
        self.assertFalse(h.check())

        h = DriftErrorHandler(max_drift=0.05)
        self.assertFalse(h.check())

        h = DriftErrorHandler(max_drift=0.0001)
        self.assertFalse(h.check())

        incar = Incar.from_file("INCAR")
        incar["EDIFFG"] = -0.01
        incar.write_file("INCAR")

        h = DriftErrorHandler(max_drift=0.0001)
        self.assertTrue(h.check())

        h = DriftErrorHandler()
        h.check()
        self.assertEqual(h.max_drift, 0.01)

        clean_dir()
        shutil.move("INCAR.orig", "INCAR")
Ejemplo n.º 16
0
 def test_check_correct_scan_metal(self):
     h = ScanMetalHandler()
     self.assertTrue(h.check())
     d = h.correct()
     self.assertEqual(d["errors"], ["ScanMetal"])
     self.assertEqual(Incar.from_file("INCAR")["KSPACING"], 0.22)
     os.remove("vasprun.xml")
Ejemplo n.º 17
0
def driver():
    pwd = os.getcwd()
    num_jobs_in_workflow = check_num_jobs_in_workflow(pwd)

    with open(os.path.join(pwd, 'WORKFLOW_CONVERGENCE'), 'w') as f:
        f.write('WORKFLOW_CONVERGED = False')
        f.close()

    if num_jobs_in_workflow > 1:
        if check_path_exists(os.path.join(pwd, 'WORKFLOW_NAME')):
            workflow_file = Incar.from_file(os.path.join(pwd, 'WORKFLOW_NAME'))
            workflow_name = workflow_file['NAME']
        else:
            print('\n#---------------------------------#\n')
            workflow_name = input("Please enter a name for this workflow: ")
            print('\n#---------------------------------#\n')

            with open(os.path.join(pwd, 'WORKFLOW_NAME'), 'w') as f:
                writeline = 'NAME = ' + str(workflow_name)
                f.write(writeline)
                f.close()
    else:
        workflow_name = get_single_job_name(pwd)

    # need dependencies for vasp_run_main
    computed_entries = vasp_run_main(pwd)
    if computed_entries is None:
        pass
    else:
        with open(os.path.join(pwd, str(workflow_name) + '_converged.json'), 'w') as f:
            json.dump(computed_entries, f)
Ejemplo n.º 18
0
 def setup(self):
     """
     setup static jobs for all the calibrate objects
     copies CONTCAR to POSCAR
     sets NSW = 0
     """
     for cal in self.cal_objs:
         for i, jdir in enumerate(cal.old_job_dir_list):
             job_dir = self.job_dir + os.sep \
                 + jdir.replace(os.sep, '_').replace('.', '_') \
                 + os.sep + 'STATIC'
             logger.info('setting up job in {}'.format(job_dir))
             cal.incar = Incar.from_file(jdir + os.sep + 'INCAR')
             cal.incar['EDIFF'] = '1E-6'
             cal.incar['NSW'] = 0
             cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR')
             cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS')
             contcar_file = jdir + os.sep + 'CONTCAR'
             if os.path.isfile(contcar_file):
                 logger.info('setting poscar file from {}'
                             .format(contcar_file))
                 cal.poscar = Poscar.from_file(contcar_file)
                 cal.add_job(job_dir=job_dir)
             else:
                 logger.critical("""CONTCAR doesnt exist.
                 Setting up job using input set in the old
                 calibration directory""")
                 cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR')
                 cal.add_job(job_dir=job_dir)
Ejemplo n.º 19
0
 def test_point_group_vasp6(self):
     # the error message is formatted differently in VASP6 compared to VASP5
     h = VaspErrorHandler("vasp6.point_group")
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["point_group"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["ISYM"], 0)
Ejemplo n.º 20
0
 def test_inv_rot_matrix_vasp6(self):
     # the error message is formatted differently in VASP6 compared to VASP5
     h = VaspErrorHandler("vasp6.inv_rot_mat")
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["inv_rot_mat"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["SYMPREC"], 1e-08)
Ejemplo n.º 21
0
    def check(self):

        incar = Incar.from_file(self.incar)
        nelm = incar.get("NELM", 60)
        unconverged_line = f":{nelm:4d}"
        with open(self.oszicar, "r") as fr:
            return any(unconverged_line in line for line in fr)
Ejemplo n.º 22
0
    def test_aliasing_incar(self):
        os.chdir(os.path.join(test_dir, "aliasing"))
        shutil.copy("INCAR", "INCAR.orig")
        h = AliasingErrorHandler("vasp.aliasing_incar")
        h.check()
        d = h.correct()

        self.assertEqual(d["errors"], ["aliasing_incar"])
        self.assertEqual(
            d["actions"],
            [
                {
                    "action": {
                        "_unset": {
                            "NGY": 1,
                            "NGZ": 1
                        }
                    },
                    "dict": "INCAR"
                },
                {
                    "file": "CHGCAR",
                    "action": {
                        "_file_delete": {
                            "mode": "actual"
                        }
                    }
                },
                {
                    "file": "WAVECAR",
                    "action": {
                        "_file_delete": {
                            "mode": "actual"
                        }
                    }
                },
            ],
        )

        incar = Incar.from_file("INCAR.orig")
        incar["ICHARG"] = 10
        incar.write_file("INCAR")
        d = h.correct()
        self.assertEqual(d["errors"], ["aliasing_incar"])
        self.assertEqual(
            d["actions"],
            [{
                "action": {
                    "_unset": {
                        "NGY": 1,
                        "NGZ": 1
                    }
                },
                "dict": "INCAR"
            }],
        )

        shutil.move("INCAR.orig", "INCAR")
        clean_dir()
        os.chdir(test_dir)
Ejemplo n.º 23
0
 def setup(self):
     """
     setup static jobs for all the calibrate objects
     copies CONTCAR to POSCAR
     sets NSW = 0
     """
     for cal in self.cal_objs:
         for i, jdir in enumerate(cal.old_job_dir_list):
             job_dir = self.job_dir + os.sep \
                 + jdir.replace(os.sep, '_').replace('.', '_') \
                 + os.sep + 'STATIC'
             logger.info('setting up job in {}'.format(job_dir))
             cal.incar = Incar.from_file(jdir + os.sep + 'INCAR')
             cal.incar['EDIFF'] = '1E-6'
             cal.incar['NSW'] = 0
             cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR')
             cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS')
             contcar_file = jdir + os.sep + 'CONTCAR'
             if os.path.isfile(contcar_file):
                 logger.info(
                     'setting poscar file from {}'.format(contcar_file))
                 cal.poscar = Poscar.from_file(contcar_file)
                 cal.add_job(job_dir=job_dir)
             else:
                 logger.critical("""CONTCAR doesnt exist.
                 Setting up job using input set in the old
                 calibration directory""")
                 cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR')
                 cal.add_job(job_dir=job_dir)
Ejemplo n.º 24
0
def _find_irr_k_points(directory):
    """
    Determine the number of irreducible k-points based on the VASP input files in a
    directory.

    Args:
        directory (str): Path to the directory that contains the VASP input files.

    Returns:
        int: Number of irreducible k-points.

    """
    # TODO Still fails for many calculations.
    warnings.warn("Currently, the _find_irr_k_points method still fails regularly "
                  "to find the same number of irreducible k-points as VASP. Use "
                  "with care.")

    directory = os.path.abspath(directory)

    structure = Structure.from_file(os.path.join(directory, "POSCAR"))

    incar = Incar.from_file(os.path.join(directory, "INCAR"))
    if incar.get("MAGMOM", None) is not None:
        structure.add_site_property("magmom", incar.get("MAGMOM", None))
        structure.add_oxidation_state_by_site(
            [round(magmom, 3) for magmom in structure.site_properties["magmom"]]
        )

    kpoints = Kpoints.from_file(os.path.join(directory, "KPOINTS"))

    spg = SpacegroupAnalyzer(structure, symprec=1e-5)

    return len(spg.get_ir_reciprocal_mesh(kpoints.kpts))
Ejemplo n.º 25
0
    def run_task(self, fw_spec):

        directory = self.get("directory", os.getcwd())
        multiplier = self.get("multiplier", 3)

        os.chdir(directory)

        nelect_written = False

        try:
            with open("OUTCAR", "r") as file:
                if "NELECT" in file.read():
                    nelect_written = True
        except FileNotFoundError:
            pass

        if not nelect_written:

            # Do a trial run to figure out the number of standard bands
            stdout_file = "temp.out"
            stderr_file = "temp.out"
            vasp_cmd = fw_spec["_fw_env"]["vasp_cmd"].split(" ")

            with open(stdout_file, 'w') as f_std, \
                    open(stderr_file, "w", buffering=1) as f_err:
                p = subprocess.Popen(vasp_cmd, stdout=f_std, stderr=f_err,
                                     preexec_fn=os.setsid)

                while not nelect_written:
                    try:
                        with open("OUTCAR", "r") as file:
                            if "NELECT" in file.read():
                                nelect_written = True
                    except FileNotFoundError:
                        pass
                    time.sleep(1)

                os.killpg(os.getpgid(p.pid), signal.SIGTERM)

            time.sleep(3)
            os.remove(os.path.join(directory, "temp.out"))

        outcar = Outcar("OUTCAR")
        incar = Incar.from_file("INCAR")
        pattern = r"\s+NELECT\s=\s+(\d+).\d+\s+total\snumber\sof\selectrons"
        outcar.read_pattern({"nelect": pattern})

        nions = len(Structure.from_file("POSCAR"))
        nelect = int(outcar.data["nelect"][0][0])
        ispin = int(incar.get("ISPIN", 1))

        if ispin == 1:
            nbands = int(round(nelect / 2 + nions / 2)) * multiplier
        elif ispin == 2:
            nbands = int(nelect * 3 / 5 + nions) * multiplier
        else:
            raise ValueError("ISPIN Value is not set to 1 or 2!")

        incar.update({"NBANDS": nbands})
        incar.write_file("INCAR")
def calc_charge_state(args):
    poscar = Poscar.from_file(args.dir / "POSCAR")
    potcar = Potcar.from_file(args.dir / "POTCAR")
    incar = Incar.from_file(args.dir / "INCAR")
    charge_state = get_defect_charge_state(poscar, potcar, incar)
    logger.info(f"Charge state in {args.dir} is {charge_state}.")
    return charge_state
Ejemplo n.º 27
0
 def test_check_correct_large_sigma(self):
     h = LargeSigmaHandler()
     self.assertTrue(h.check())
     d = h.correct()
     self.assertEqual(d["errors"], ["LargeSigma"])
     self.assertEqual(Incar.from_file("INCAR")["SIGMA"], 1.44)
     os.remove("vasprun.xml")
Ejemplo n.º 28
0
 def test_nicht_konv(self):
     h = VaspErrorHandler("vasp.nicht_konvergent")
     h.natoms_large_cell = 5
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["nicht_konv"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["LREAL"], True)
Ejemplo n.º 29
0
    def get_inputs(self, sync=False):
        """
        Read inputs from Job directory
        """
        if sync:
            self.sync_from_hpc()
        inputs = {}
        structures = []
        path = op.abspath(self.path)
        dirs = [d[0] for d in os.walk(path)]
        for d in dirs:
            image_name = op.relpath(d, start=path)
            if all(
                    c.isdigit() for c in list(image_name)
            ):  #check if folder is image (all characters in folder rel path need to be numbers)
                image_path = d
                structure = Poscar.from_file(op.join(image_path,
                                                     'POSCAR')).structure
                structures.append(structure)

        inputs['structures'] = structures
        inputs['INCAR'] = Incar.from_file(op.join(path, 'INCAR'))
        inputs['KPOINTS'] = Kpoints.from_file(op.join(path, 'KPOINTS'))
        inputs['POTCAR'] = Potcar.from_file(op.join(path, 'POTCAR'))

        self.inputs = inputs
        return
Ejemplo n.º 30
0
def write_wannier_input_file(S, spin_polarized=True, write_incar=True):
    string = """Begin Projections
random
End Projections
guiding_centres=true
bands_plot = true

begin kpoint_path\n"""

    string += get_kpoints_wannier(S) + '\n'
    string += 'end kpoint_path\n'

    if spin_polarized:
        string += 'spinors=true\n'

    w = open('wannier90.win', 'w')
    w.write(string)
    w.close()

    #write INCAR
    if write_incar:
        incar = Incar.from_string("""ISMEAR = -5
        # usefull energy range for density of states    
ALGO = None ; NELM = 1                 # exact diagonalization one step suffices
NBANDS = 96                            # need for a lot of bands in GW    
LORBIT = 11
LWRITE_MMN_AMN = TRUE
LWANNIER90_RUN = .TRUE.""")
        try:
            NBANDS = Incar.from_file('../../step1/INCAR')['NBANDS']
        except:
            NBANDS = Incar.from_file('../INCAR')['NBANDS']

        if spin_polarized:
            if os.path.exists('POSCAR'):
                incar.update({
                    'LORBIT':
                    11,
                    'ISPIN':
                    2,
                    'MAGMOM':
                    get_magmom_string(Structure.from_file('POSCAR'))
                })
            else:
                raise IOError('No POSCAR found at ' + os.getcwd())
        incar.update({'NBANDS': NBANDS})
        incar.write_file('INCAR')
Ejemplo n.º 31
0
    def setup(self):
        """
        Performs initial setup for VaspNEBJob, including overriding any settings
        and backing up.
        """
        neb_dirs = self.neb_dirs

        if self.backup:
            # Back up KPOINTS, INCAR, POTCAR
            for f in VASP_NEB_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))
            # Back up POSCARs
            for path in neb_dirs:
                poscar = os.path.join(path, "POSCAR")
                shutil.copy(poscar, "{}.orig".format(poscar))

        if self.half_kpts and os.path.exists("KPOINTS"):
            kpts = Kpoints.from_file("KPOINTS")
            kpts.kpts = np.maximum(np.array(kpts.kpts) / 2, 1)
            kpts.kpts = kpts.kpts.astype(int).tolist()
            if tuple(kpts.kpts[0]) == (1, 1, 1):
                kpt_dic = kpts.as_dict()
                kpt_dic["generation_style"] = "Gamma"
                kpts = Kpoints.from_dict(kpt_dic)
            kpts.write_file("KPOINTS")

        if self.auto_npar:
            try:
                incar = Incar.from_file("INCAR")
                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(math.sqrt(ncores)), ncores):
                    if ncores % npar == 0:
                        incar["NPAR"] = npar
                        break
                incar.write_file("INCAR")
            except Exception:
                pass

        if self.auto_continue and os.path.exists("STOPCAR") and not os.access(
                "STOPCAR", os.W_OK):
            # Remove STOPCAR
            os.chmod("STOPCAR", 0o644)
            os.remove("STOPCAR")

            # Copy CONTCAR to POSCAR
            for path in self.neb_sub:
                contcar = os.path.join(path, "CONTCAR")
                poscar = os.path.join(path, "POSCAR")
                shutil.copy(contcar, poscar)

        if self.settings_override is not None:
            VaspModder().apply_actions(self.settings_override)
Ejemplo n.º 32
0
    def test_optics(self):
        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')
Ejemplo n.º 33
0
 def setUp(self):
     filepath = self.TEST_FILES_DIR / 'INCAR'
     incar = Incar.from_file(filepath)
     filepath = self.TEST_FILES_DIR / 'POSCAR'
     poscar = Poscar.from_file(filepath,check_for_POTCAR=False)
     if "PMG_VASP_PSP_DIR" not in os.environ:
         os.environ["PMG_VASP_PSP_DIR"] = str(self.TEST_FILES_DIR)
     filepath = self.TEST_FILES_DIR / 'POTCAR'
     potcar = Potcar.from_file(filepath)
     filepath = self.TEST_FILES_DIR / 'KPOINTS.auto'
     kpoints = Kpoints.from_file(filepath)
     self.vinput = VaspInput(incar, kpoints, poscar, potcar)
Ejemplo n.º 34
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)
Ejemplo n.º 35
0
    def test_write(self):
        tmp_dir = Path("VaspInput.testing")
        self.vinput.write_input(tmp_dir)

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

        for name in ("INCAR", "POSCAR", "POTCAR", "KPOINTS"):
            (tmp_dir / name).unlink()

        tmp_dir.rmdir()
Ejemplo n.º 36
0
def run_hse_prep_calculation(dim=2, submit=True):
    """
    Submits a quick static calculation to calculate the IBZKPT
    file using a smaller number of k-points (200/atom instead of
    1000/atom). The other outputs from this calculation are
    essentially useless.

    Args:
        dim (int): 2 for relaxing a 2D material, 3 for a 3D material.
        submit (bool): Whether or not to submit the job.
    """

    if not os.path.isdir('hse_prep'):
        os.mkdir('hse_prep')
    os.chdir('hse_prep')
    os.system('cp ../CONTCAR ./POSCAR')
    if os.path.isfile('../POTCAR'):
        os.system('cp POTCAR .')
    relax(dim=2, submit=False)
    incar_dict = Incar.from_file('INCAR').as_dict()
    incar_dict.update({'NSW': 0, 'NELM': 1, 'LWAVE': False, 'LCHARG': False,
                       'LAECHG': False})
    Incar.from_dict(incar_dict).write_file('INCAR')

    Kpoints.automatic_density(
        Structure.from_file('POSCAR'), 200
    ).write_file('KPOINTS')

    if dim == 2:
        kpts_lines = open('KPOINTS').readlines()

        with open('KPOINTS', 'w') as kpts:
            for line in kpts_lines[:3]:
                kpts.write(line)
            kpts.write(kpts_lines[3].split()[0] + ' '
                       + kpts_lines[3].split()[1] + ' 1')

    if QUEUE == 'pbs':
        write_pbs_runjob('{}_prep'.format(
            os.getcwd().split('/')[-2]), 1, 16, '800mb', '6:00:00', VASP)
        submission_command = 'qsub runjob'

    elif QUEUE == 'slurm':
        write_slurm_runjob('{}_prep'.format(
            os.getcwd().split('/')[-2]), 16, '800mb', '6:00:00', VASP)
        submission_command = 'sbatch runjob'

    if submit:
        os.system(submission_command)

    os.chdir('../')
Ejemplo n.º 37
0
 def test_write_inputset(self):
     name = 'Test'
     incar= Incar.from_file(TEST_STEP1+os.sep+'INCAR')
     kpoints = Kpoints.from_file(TEST_STEP1+os.sep+'KPOINTS')
     poscar = Poscar.from_file(TEST_STEP1+os.sep+'POSCAR')
     potcar = TEST_STEP1+os.sep+'DUMMY_POTSPEC'
     #potcar = #Potcar.from_dict({'@class': 'Potcar', 'functional': 'PBE',\
               #                 'symbols': ['Al'], '@module': 'pymatgen.io.vasp.inputs'})
     reuse_path = [TEST_STEP1 + os.sep + 'COPY_FILE']
     print (reuse_path)
     mvis = MPINTVaspInputSet(name,incar,poscar,potcar,kpoints,reuse_path=reuse_path,test=True)
     mvis.write_input(job_dir=TEST_STEP2)
     self.assertCountEqual(os.listdir(TEST_STEP2), ['INCAR','KPOINTS','POSCAR','COPY_FILE'])
     cleanup = [os.remove(TEST_STEP2+os.sep+f) for f in os.listdir(TEST_STEP2)]
Ejemplo n.º 38
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,check_for_POTCAR=False)
     if "PMG_VASP_PSP_DIR" not in os.environ:
         test_potcar_dir = os.path.abspath(
             os.path.join(os.path.dirname(__file__), "..", "..", "..", "..",
                          "test_files"))
         os.environ["PMG_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)
Ejemplo n.º 39
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)
Ejemplo n.º 40
0
 def setup(self):
     """
     setup solvation jobs for the calibrate objects
     copies WAVECAR and sets the solvation params in the incar file
     also dumps system.json file in each directory for the database
     crawler
     mind: works only for cal objects that does only single
     calculations
     """
     for cal in self.cal_objs:
         jdir = cal.old_job_dir_list[0]
         cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR')
         cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR')
         cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS')
         cal.incar = Incar.from_file(jdir + os.sep + 'INCAR')
         cal.incar['LSOL'] = '.TRUE.'
         syms = [site.specie.symbol for site in cal.poscar.structure]
         zvals = {p.symbol: p.nelectrons for p in cal.potcar}
         nelectrons = sum([zvals[a[0]] * len(tuple(a[1]))
                           for a in itertools.groupby(syms)])
         keys = [k for k in self.sol_params.keys()
                 if self.sol_params[k]]
         prod_list = [self.sol_params.get(k) for k in keys]
         for params in itertools.product(*tuple(prod_list)):
             job_dir = self.job_dir + os.sep \
                 + cal.old_job_dir_list[0].replace(os.sep,
                                                   '_').replace('.',
                                                                '_') \
                 + os.sep + 'SOL'
             for i, k in enumerate(keys):
                 if k == 'NELECT':
                     cal.incar[k] = params[i] + nelectrons
                 else:
                     cal.incar[k] = params[i]
                 job_dir = job_dir + os.sep + k + os.sep + str(
                     cal.incar[k]).replace('.', '_')
             if not os.path.exists(job_dir):
                 os.makedirs(job_dir)
             with open(job_dir + os.sep + 'system.json', 'w') as f:
                 json.dump(dict(list(zip(keys, params))), f)
             wavecar_file = cal.old_job_dir_list[0] + os.sep + 'WAVECAR'
             if os.path.isfile(wavecar_file):
                 shutil.copy(wavecar_file, job_dir + os.sep + 'WAVECAR')
                 cal.add_job(job_dir=job_dir)
             else:
                 logger.critical('WAVECAR doesnt exist. Aborting ...')
                 sys.exit(0)
Ejemplo n.º 41
0
def plot_density_of_states(xlim=(-10, 5), ylim=(-1.5, 1.5), fmt='pdf'):
    """
    Plots the density of states from the DOSCAR in the cwd. Plots
    spin up in red, down in green, and the sum in black. Efermi = 0.

    Args:
        xlim (tuple): minimum and maximum energies for the plot's
            x-axis.
        ylim (tuple): minimum and maximum for the plot's
            y-axis.
        fmt (str): matplotlib format style. Check the matplotlib
            docs for options.
    """

    efermi = Vasprun('vasprun.xml').efermi
    dos_lines = open ('DOSCAR').readlines()

    x, up, down = [], [], []
    nedos = Incar.from_file('INCAR').as_dict()['NEDOS'] - 1

    for line in dos_lines[6:6+nedos]:
            split_line = line.split()
            x.append(float(split_line[0]) - efermi)
            up.append(float(split_line[1]))
            down.append(-float(split_line[2]))

    x, up, down = np.array(x), np.array(up), np.array(down)
    sum = up + down

    ax = plt.figure().gca()
    ax.set_xlim(xlim[0], xlim[1])
    ax.set_ylim(ylim[0], ylim[1])

    ax.set_xlabel(r'$\mathrm{E\/(eV)}$')
    ax.set_ylabel(r'$\mathrm{Density\/of\/States$')
    ax.set_xticklabels([r'$\mathrm{%s}$' % t for t in ax.get_xticklabels()])
    ax.set_yticklabels([r'$\mathrm{%s}$' % t for t in ax.get_yticklabels()])

    ax.plot(x, up, color='red' )
    ax.plot(x, down, color='green')
    ax.plot(x, sum, color='black' )
    if fmt is not None:
        plt.savefig('density_of_states.{}'.format(fmt))
    else:
        return ax

    plt.close()
Ejemplo n.º 42
0
 def setup(self):
     """
     setup static jobs for the calibrate objects
     copies CONTCAR to POSCAR
     sets NSW = 0
     write system.json file for database crawler
     """
     d = {}
     for cal in self.cal_objs:
         for i, jdir in enumerate(cal.old_job_dir_list):
             job_dir = self.job_dir + os.sep \
                 + jdir.replace(os.sep, '_').replace('.', '_') + \
                 os.sep + 'STATIC'
             cal.incar = Incar.from_file(jdir + os.sep + 'INCAR')
             cal.incar['EDIFF'] = '1E-6'
             cal.incar['NSW'] = 0
             cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR')
             cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS')
             contcar_file = jdir + os.sep + 'CONTCAR'
             if os.path.isfile(contcar_file):
                 cal.poscar = Poscar.from_file(contcar_file)
                 if cal in self.cal_slabs or cal in self.cal_interfaces:
                     try:
                         d['hkl'] = cal.system['hkl']
                     except:
                         logger.critical("""the calibrate object
                         doesnt have a system set for calibrating""")
                 if cal in self.cal_interfaces:
                     try:
                         d['ligand'] = cal.system['ligand']['name']
                     except:
                         logger.critical("""the calibrate object
                         doesnt have a system set for calibrating""")
                 if not os.path.exists(job_dir):
                     os.makedirs(job_dir)
                 if d:
                     with open(job_dir + os.sep + 'system.json', 'w') as f:
                         json.dump(d, f)
                 cal.add_job(job_dir=job_dir)
             else:
                 logger.critical("""CONTCAR doesnt exist.
                 Setting up job using input set in the old
                 calibration directory""")
                 cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR')
                 cal.add_job(job_dir=job_dir)
Ejemplo n.º 43
0
    def test_init(self):
        prev_run = os.path.join(test_dir, "relaxation")
        vis = MPNonSCFSet.from_prev_calc(
            prev_calc_dir=prev_run, mode="Line", copy_chgcar=False)
        self.assertEqual(vis.incar["NSW"], 0)
        # Check that the ENCUT has been inherited.
        self.assertEqual(vis.incar["ENCUT"], 600)
        self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal)

        # Check as from dict.
        vis = MPNonSCFSet.from_dict(vis.as_dict())
        self.assertEqual(vis.incar["NSW"], 0)
        # Check that the ENCUT has been inherited.
        self.assertEqual(vis.incar["ENCUT"], 600)
        self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal)

        vis.write_input(self.tmp)
        self.assertFalse(os.path.exists(os.path.join(self.tmp, "CHGCAR")))

        vis = MPNonSCFSet.from_prev_calc(prev_calc_dir=prev_run,
                                                mode="Line", copy_chgcar=True)
        vis.write_input(self.tmp)
        self.assertTrue(os.path.exists(os.path.join(self.tmp, "CHGCAR")))

        # Code below is just to make sure that the parameters are the same
        # between the old MPStaticVaspInputSet and the new MPStaticSet.
        # TODO: Delete code below in future.
        MPNonSCFVaspInputSet.from_previous_vasp_run(
            previous_vasp_dir=prev_run, output_dir=self.tmp, mode="Line")

        incar = Incar.from_file(os.path.join(self.tmp, "INCAR"))

        for k, v1 in vis.incar.items():
            v2 = incar.get(k)
            try:
                v1 = v1.upper()
                v2 = v2.upper()
            except:
                # Convert strings to upper case for comparison. Ignore other
                # types.
                pass
            self.assertEqual(v1, v2, str(v1)+str(v2))
        kpoints = Kpoints.from_file(os.path.join(self.tmp, "KPOINTS"))
        self.assertEqual(kpoints.style, vis.kpoints.style)
        self.assertArrayAlmostEqual(kpoints.kpts, vis.kpoints.kpts)
Ejemplo n.º 44
0
def plot_density_of_states(fmt="pdf"):
    """
    Plots the density of states from the DOSCAR in the cwd. Plots
    spin up in red, down in green, and the sum in black. Efermi = 0.

    Args:
        fmt (str): matplotlib format style. Check the matplotlib
            docs for options.
    """

    efermi = Vasprun("vasprun.xml").efermi
    ticks = [-10, -5, -3, -2, -1, 0, 1, 2, 3, 5]

    dos_lines = open("DOSCAR").readlines()
    x, up, down = np.array(), np.array(), np.array()
    nedos = Incar.from_file("INCAR").as_dict()["NEDOS"] - 1

    for line in dos_lines[6 : 6 + nedos]:
        split_line = line.split()
        x.append(float(split_line[0]) - efermi)
        up.append(float(split_line[1]))
        down.append(-float(split_line[2]))

    sum = up + down

    ax = plt.figure().gca()

    ax.set_xlim(-10, 5)
    ax.set_ylim(-1.5, 1.5)
    ax.set_xlabel("E (eV)")
    ax.set_ylabel("Density of States")
    ax.set_xticks(ticks)
    ax.plot(x, up, color="red")
    ax.plot(x, down, color="green")
    ax.plot(x, sum, color="black")
    plt.savefig("density_of_states.{}".format(fmt))
    plt.close()
Ejemplo n.º 45
0
def check_incar(task_type):
    errors = []
    incar = Incar.from_file("INCAR")
    
    if 'deformed' in task_type:
        if incar['ISIF'] != 2:
            errors.append("Deformed optimization requires ISIF = 2")

    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
Ejemplo n.º 46
0
 def run_task(self, fw_spec):
     incar = Incar.from_file(zpath("INCAR"))
     incar.update({"ISIF": 2})
     incar.write_file("INCAR")
     return FWAction()
Ejemplo n.º 47
0
def run_gamma_calculations(submit=True, step_size=0.5):
    """
    Setup a 2D grid of static energy calculations to plot the Gamma
    surface between two layers of the 2D material. These calculations
    are run and stored in subdirectories under 'friction/lateral'.

    Args:
        submit (bool): Whether or not to submit the jobs.
        step_size (float): the distance between grid points in
            Angstroms.
    """

    if not os.path.isdir('friction'):
        os.mkdir('friction')
    os.chdir('friction')

    if not os.path.isdir('lateral'):
        os.mkdir('lateral')
    os.chdir('lateral')

    os.system('cp ../../CONTCAR POSCAR')

    # Pad the bottom layer with 20 Angstroms of vacuum.
    utl.ensure_vacuum(Structure.from_file('POSCAR'), 20)
    structure = Structure.from_file('POSCAR')
    n_sites_per_layer = structure.num_sites

    n_divs_x = int(math.ceil(structure.lattice.a / step_size))
    n_divs_y = int(math.ceil(structure.lattice.b / step_size))

    # Get the thickness of the material.
    max_height = max([site.coords[2] for site in structure.sites])
    min_height = min([site.coords[2] for site in structure.sites])
    thickness = max_height - min_height

    # Make a new layer.
    species, coords = [], []
    for site in structure.sites:
        # Original site
        species.append(site.specie)
        coords.append(site.coords)
        # New layer site
        species.append(site.specie)
        coords.append([site.coords[0], site.coords[1],
                       site.coords[2] + thickness + 3.5])

    Structure(structure.lattice, species, coords,
              coords_are_cartesian=True).to('POSCAR', 'POSCAR')

    for x in range(n_divs_x):
        for y in range(n_divs_y):
            dir = '{}x{}'.format(x, y)

            if not os.path.isdir(dir):
                os.mkdir(dir)

            # Copy input files
            os.chdir(dir)
            os.system('cp ../../../INCAR .')
            os.system('cp ../../../KPOINTS .')
            os.system('cp ../POSCAR .')
            if VDW_KERNEL:
                os.system('cp {} .'.format(VDW_KERNEL))

            # Shift the top layer
            structure = Structure.from_file("POSCAR")
            all_z_coords = [s.coords[2] for s in structure.sites]
            top_layer = [s for s in structure.sites if s.coords[2] > np.mean(all_z_coords)]
            structure.remove_sites([i for i, s in enumerate(structure.sites) if s in top_layer])
            for site in top_layer:
                structure.append(
                    site.specie,
                    [site.coords[0]+float(x)/float(n_divs_x),
                     site.coords[1]+float(y)/float(n_divs_y),
                     site.coords[2]], coords_are_cartesian=True
                )

            structure = structure.get_sorted_structure()
            structure.to("POSCAR", "POSCAR")
            utl.write_potcar()
            incar_dict = Incar.from_file('INCAR').as_dict()
            incar_dict.update({'NSW': 0, 'LAECHG': False, 'LCHARG': False,
                               'LWAVE': False, 'LVTOT': False,
                               'MAGMOM': utl.get_magmom_string(structure)})
            incar_dict.pop('NPAR', None)
            Incar.from_dict(incar_dict).write_file('INCAR')

            if QUEUE_SYSTEM == 'pbs':
                utl.write_pbs_runjob(dir, 1, 8, '1000mb', '2:00:00', VASP_STD_BIN)
                submission_command = 'qsub runjob'

            elif QUEUE_SYSTEM == 'slurm':
                utl.write_slurm_runjob(dir, 8, '1000mb', '2:00:00', VASP_STD_BIN)
                submission_command = 'sbatch runjob'

            if submit:
                os.system(submission_command)

            os.chdir('../')

    os.chdir('../../')
Ejemplo n.º 48
0
def run_normal_force_calculations(basin_and_saddle_dirs,
                                  spacings=np.arange(1.5, 4.25, 0.25),
                                  submit=True):
    """
    Set up and run static calculations of the basin directory and
    saddle directory at specified interlayer spacings to get f_N and
    f_F.

    Args:
        basin_and_saddle_dirs (tuple): Can be obtained by the
            get_basin_and_peak_locations() function under
            friction.analysis. For example,

            run_normal_force_calculations(('0x0', '3x6'))

            or

            run_normal_force_calculations(get_basin_and_peak_locations())

            will both work.
        spacings (tuple): list of interlayer spacings (in Angstroms, as floats)
            at which to run the calculations.
        submit (bool): Whether or not to submit the jobs.
    """

    spacings = [str(spc) for spc in spacings]

    os.chdir('friction')
    if not os.path.isdir('normal'):
        os.mkdir('normal')
    os.chdir('normal')

    for spacing in spacings:
        if not os.path.isdir(spacing):
            os.mkdir(spacing)

        for subdirectory in basin_and_saddle_dirs:

            os.system('cp -r ../lateral/{} {}/'.format(subdirectory, spacing))

            os.chdir('{}/{}'.format(spacing, subdirectory))
            structure = Structure.from_file('POSCAR')
            n_sites = len(structure.sites)
            all_z_coords = [s.coords[2] for s in structure.sites]
            top_layer = [s for s in structure.sites if s.coords[2] >
                np.mean(all_z_coords)]
            bottom_of_top_layer = min([site.coords[2] for site in top_layer])

            remove_indices = [i for i, s in enumerate(structure.sites) if s in
                top_layer]
            structure.remove_sites(remove_indices)

            top_of_bottom_layer = max(
                [site.coords[2] for site in structure.sites]
            )

            for site in top_layer:
                structure.append(
                    site.specie,
                    [site.coords[0],
                     site.coords[1],
                     site.coords[2] - bottom_of_top_layer
                     + top_of_bottom_layer + float(spacing)],
                    coords_are_cartesian=True)

            structure = structure.get_sorted_structure()
            structure.to('POSCAR', 'POSCAR')
            utl.write_potcar()
            incar_dict = Incar.from_file('INCAR').as_dict()
            incar_dict.update({"MAGMOM": utl.get_magmom_string(structure)})
            Incar.from_dict(incar_dict).write_file("INCAR")

            if QUEUE_SYSTEM == 'pbs':
                utl.write_pbs_runjob('{}_{}'.format(
                    subdirectory, spacing), 1, 8, '1000mb', '2:00:00',
                    VASP_STD_BIN)
                submission_command = 'qsub runjob'

            elif QUEUE_SYSTEM == 'slurm':
                utl.write_slurm_runjob('{}_{}'.format(
                    subdirectory, spacing), 8, '1000mb', '2:00:00',
                    VASP_STD_BIN)
                submission_command = 'sbatch runjob'

            if submit:
                os.system(submission_command)

            os.chdir('../../')

    os.chdir('../../')
Ejemplo n.º 49
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)
        filepath3 = os.path.join(test_dir, 'INCAR.3')
        incar3 = 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}})

        self.assertEqual(
            incar1.diff(incar3),
            {'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}})
Ejemplo n.º 50
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)
Ejemplo n.º 51
0
    def assimilate(self, path):
        files = os.listdir(path)
        ciffilepath = None
        if any("relax1" in s for s in files) and any("relax2" in s for s in files):
            filepath = glob.glob(os.path.join(path,
                                              "vasprun.xml.relax2*"))[0]
            try:
                incarfilepath = glob.glob(os.path.join(path,'INCAR.relax1*'))[0]
            except:
                print path

            #Get cif from directory
            # if glob.glob(os.path.join(path,'*cif')):
            #     ciffilepath = glob.glob(os.path.join(path,'*cif'))[0]

            contcarfile = glob.glob(os.path.join(path,"CONTCAR.relax2*"))[0]

        else:
            vasprun_files = glob.glob(os.path.join(path, "vasprun.xml*"))
            try:
                incarfilepath = glob.glob(os.path.join(path,"INCAR*"))[0]
            except:
                print path

            #Get cif from directory
            # if glob.glob(os.path.join(path,'*cif')):
            #     ciffilepath = glob.glob(os.path.join(path,'*cif'))[0]

            contcarfile = glob.glob(os.path.join(path,"CONTCAR*"))[0]

            filepath = None
            if len(vasprun_files) == 1:
                filepath = vasprun_files[0]
                logging.debug(filepath)
            elif len(vasprun_files) > 1:
                """
                This is a bit confusing, since there maybe be multi-steps. By
                default, assimilate will try to find a file simply named
                vasprun.xml, vasprun.xml.bz2, or vasprun.xml.gz.  Failing which
                it will try to get a relax2 from an aflow style run if
                possible. Or else, a randomly chosen file containing
                vasprun.xml is chosen.
                """
                for fname in vasprun_files:
                    if os.path.basename(fname) in ["vasprun.xml",
                                                   "vasprun.xml.gz",
                                                   "vasprun.xml.bz2"]:
                        filepath = fname
                        break
                    if re.search("relax2", fname):
                        filepath = fname
                        break
                    filepath = fname

        try:
            vasprun = Vasprun(filepath)
        except Exception as ex:
            logger.debug("error in {}: {}".format(filepath, ex))
            return None

        logging.debug('Done entry if')

        entry = vasprun.get_computed_entry(self._inc_structure,
                                           parameters=self._parameters,
                                           data=self._data)
        logging.debug(entry)
        entry.parameters["history"] = _get_transformation_history(path)

        incar = Incar.from_file(incarfilepath)
        try:
            entry.data['NUPDOWN'] = incar['NUPDOWN']
            entry.data['ISMEAR'] = incar['ISMEAR']
        except:
            pass
        logging.debug('Return Entry step')
        entry.data['CONTCAR_Structure'] = Structure.from_file(contcarfile,primitive=False)

        # if ciffilepath:
        #     entry.data['Cif_Structure'] = Structure.from_file(ciffilepath,primitive=False)
        return entry
Ejemplo n.º 52
0
 def setUp(self):
     file_name = os.path.join(test_dir, 'INCAR')
     self.incar = Incar.from_file(file_name)
Ejemplo n.º 53
0
    def setup_poscar_jobs(self, scale_list=None, poscar_list=None):
        """
        for scaling the latice vectors of the original structure,
        scale_list is volume scaling factor list
        """
        if scale_list:
            for scale in scale_list:
                self.set_poscar(scale=scale)
                self.set_potcar()
                if not self.is_matrix:
                    job_dir = self.job_dir + os.sep + 'POS' + \
                        os.sep + 'VOLUME_' + str(scale)
                    self.add_job(name=job_dir, job_dir=job_dir)
        elif poscar_list:
            for pos in poscar_list:
                # if it is a twod_database run or any general standard database run,
                # the incar, kpoints and potcar follow a standard input set
                # which will be activated by the twod_database tag set to true
                # NOTE: this implementation means that the first turn_knobs tag
                # needs to be the poscar objects list
                # the database tag will be set to the name of the yaml file with the
                # standard input deck definition for that database
                # this incar dict provided as the init can be general format
                # based on the chosen functional, cutoff
                # so self.incar is a vdW incar for re-relaxation in vdW, gga for every
                # other calculation or LDA+U for LSDA+U calculations
                incar_dict = self.incar.as_dict()
                if self.reuse:
                    # if this is a true list minimally, ['CONTCAR']
                    # it is to be ensured that the poscar list is a
                    # list of paths as opposed to list of poscar objects by the turn knobs
                    # values
                    # Here pos is the path and r in each self.reuse is the name of the file(s)
                    # to be reused
                    # in a reuse calculation the following are possible:
                    # update incar (Solvation calculations) or reset incar (HSE calculations)
                    # reset kpoints file with IBZKPT
                    # copy a CHGCAR or WAVECAR or both perhaps
                    try:
                        # first setup of POSCAR initial, INCAR, KPOINTS
                        poscar = Poscar.from_file(pos + os.sep + 'CONTCAR')
                        self.logger.info('Read previous relaxed CONTCAR file from {}'.
                                         format(pos))
                        # check if it is KPOINTS altering job like HSE
                        if self.Grid_type == 'hse_bands_2D_prep':
                            # HSE prep calcualtions
                            # reset the INCAR file with a magmom only if exists
                            try:
                                incar_dict = {
                                    'MAGMOM': get_magmom_string(poscar)}
                            except:
                                incar_dict = {}
                            incar_dict = get_2D_incar_hse_prep(incar_dict)
                            self.set_kpoints(poscar=poscar)
                            self.logger.info(
                                'updated input set for HSE 2D prep calcaultion')

                        elif self.Grid_type == 'hse_bands_2D':
                            # HSE calculation
                            # reset the incar and kpoints file builds
                            # on the preceding calculations (prep calculation)
                            # IBZKPT
                            try:
                                incar_dict = {
                                    'MAGMOM': get_magmom_string(poscar)}
                            except:
                                incar_dict = {}
                            incar_dict = get_2D_incar_hse(incar_dict)
                            self.set_kpoints(poscar=poscar,
                                             ibzkpth=pos + os.sep + 'IBZKPT')
                            self.logger.info('updated input set for HSE calcaultion\
                                             using IBZKPT from {0}'.format(pos + os.sep + 'IBZKPT'))

                        elif self.Grid_type == 'hse_bands':
                            # general HSE bands
                            pass

                        elif self.Grid_type == 'Finer_G_Mesh':
                            self.logger.info('updating to Finer G Mesh')
                            kpoint = Kpoints.from_file(pos+os.sep+'KPOINTS')
                            self.set_kpoints(kpoint=kpoint.kpts[0])

                        else:
                            # use the same kpoints file and build from the old
                            # incar
                            self.kpoints = Kpoints.from_file(
                                pos + os.sep + 'KPOINTS')
                            # decide on how to use incar, use same one or
                            # update or afresh
                            if self.reuse_incar == 'old':
                                incar_dict = Incar.from_file(
                                    pos + os.sep + 'INCAR').as_dict()
                            elif self.reuse_incar == 'update':
                                # way to go for cutoff updates, convergence, etc.
                                # but retain the old functional
                                incar_dict.update(Incar.from_file(pos + os.sep + 'INCAR').
                                                  as_dict())
                            else:
                                # use a fresh incar as specified by the init
                                # way to go for example for LDAU or other
                                # major removals done to INCAR
                                # but always retain the MAGMOM if present
                                old_incar_dict = Incar.from_file(
                                    pos + os.sep + 'INCAR').as_dict()
                                if 'MAGMOM' in old_incar_dict.keys():
                                    incar_dict['MAGMOM'] = old_incar_dict[
                                        'MAGMOM']
                                else:
                                    incar_dict = incar_dict

                        if isinstance(self.reuse, list):
                            reuse_paths = [
                                pos + os.sep + r for r in self.reuse]
                            self.reuse_paths = reuse_paths
                        # Magnetism use cases, updates to be made to the INCAR (MAE)
                        # and poscar (AFM)
                        # MAE and AFM

                        if self.magnetism == 'MAE':

                            # remove vdW tags for MAE calculations
                            vdW_tags = ('GGA', 'AGGAC', 'LUSE_VDW',
                                        'PARAM1', 'PARAM2')
                            for key in vdW_tags:
                                if key in incar_dict:
                                    del incar_dict[key]

                            self.logger.info(
                                'updating input set for MAE calculation')
                            self.mag_init = Outcar(
                                pos + os.sep + 'OUTCAR').total_mag
                            nbands = 2 * \
                                Vasprun(pos + os.sep +
                                        'vasprun.xml').parameters['NBANDS']
                            # u_value = Vasprun(pos+os.sep+'vasprun.xml').incar['LDAUU']
                            # u_value = 4.0
                            self.logger.info(
                                "updating mag mom with value {0}".format(self.mag_init))
                            self.logger.info(
                                "updating NBANDS with {0}".format(nbands))
                            incar_dict.update({'NBANDS': nbands,
                                               'LSORBIT': True,
                                               'EDIFF': 1e-08,
                                               'ICHARG': 11,
                                               'LMAXMIX': 4,
                                               'LCHARG': False,
                                               'ISYM': 0,
                                               'NSW': 0,
                                               'ISPIN': 2,
                                               'IBRION': -1,
                                               'LORBIT': 11,
                                               'MAGMOM': get_magmom_mae(poscar, self.mag_init)
                                               })
                            # incar_dict.update({'LDAUU': u_value})

                        elif self.magnetism == 'AFM':
                            self.logger.info(
                                'updating INCAR and POSCAR for AFM calculation')
                            afm, poscar = get_magmom_afm(poscar, self.database)
                            incar_dict.update({'MAGMOM': afm})
                    except:
                        # check what to do if the previous calculation being reused is not
                        # actuall done .. system exit or adopt a user override
                        # with POSCAR
                        self.logger.warn(
                            'Empty relaxed CONTCAR file .. Probably job not done')
                        if not self.reuse_override:
                            self.logger.warn(
                                'You can set reuse_override to continue with POSCAR file, exiting now ..')
                            sys.exit(0)
                        else:
                            self.logger.info('Using old Poscar for rerun')
                            poscar = Poscar.from_file(pos + os.sep + 'POSCAR')

                # case for non - reuse
                else:
                    poscar = pos
                    # temporary: magnetism only set if twod flag is activated
                    if self.database == 'twod':
                        incar_dict.update(
                            {'MAGMOM': get_magmom_string(poscar)})
                        self.set_kpoints(poscar=poscar)
                    self.incar = Incar.from_dict(incar_dict)

                self.set_poscar(poscar=poscar)
                self.set_potcar()
                if not self.is_matrix:
                    job_dir = self.job_dir + os.sep + 'POS' + \
                        os.sep + self.val_to_name(poscar)
                    self.add_job(name=job_dir, job_dir=job_dir)
Ejemplo n.º 54
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
Ejemplo n.º 55
0
def run_gamma_calculations(submit=True, step_size=0.5):
    """
    Setup a 2D grid of static energy calculations to plot the Gamma
    surface between two layers of the 2D material. These calculations
    are run and stored in subdirectories under 'friction/lateral'.

    Args:
        submit (bool): Whether or not to submit the jobs.
        step_size (float): the distance between grid points in
            Angstroms.
    """

    if not os.path.isdir('friction'):
        os.mkdir('friction')
    os.chdir('friction')

    if not os.path.isdir('lateral'):
        os.mkdir('lateral')
    os.chdir('lateral')

    os.system('cp ../../CONTCAR POSCAR')

    # Pad the bottom layer with 20 Angstroms of vacuum.
    utl.add_vacuum(20 - utl.get_spacing(), 0.8)
    structure = Structure.from_file('POSCAR')
    n_sites_per_layer = structure.num_sites

    n_divs_x = int(math.ceil(structure.lattice.a / step_size))
    n_divs_y = int(math.ceil(structure.lattice.b / step_size))

    # Get the thickness of the material.
    max_height = max([site.coords[2] for site in structure.sites])
    min_height = min([site.coords[2] for site in structure.sites])
    thickness = max_height - min_height

    # Make a new layer.
    new_sites = []
    for site in structure.sites:
        new_sites.append((site.specie,
                          [site.coords[0], site.coords[1],
                           site.coords[2] + thickness + 3.5]))

    for site in new_sites:
        structure.append(site[0], site[1], coords_are_cartesian=True)

    #structure.get_sorted_structure().to('POSCAR', 'POSCAR')
    structure.to('POSCAR', 'POSCAR')

    for x in range(n_divs_x):
        for y in range(n_divs_y):
            dir = '{}x{}'.format(x, y)

            if not os.path.isdir(dir):
                os.mkdir(dir)

            # Copy input files
            os.chdir(dir)
            os.system('cp ../../../INCAR .')
            os.system('cp ../../../KPOINTS .')
            os.system('cp ../POSCAR .')
            if VDW_KERNEL != '/path/to/vdw_kernel.bindat':
                os.system('cp {} .'.format(VDW_KERNEL))

            utl.write_potcar()
            incar_dict = Incar.from_file('INCAR').as_dict()
            incar_dict.update({'NSW': 0, 'LAECHG': False, 'LCHARG': False,
                               'LWAVE': False,
                               'MAGMOM': utl.get_magmom_string()})
            incar_dict.pop('NPAR', None)
            Incar.from_dict(incar_dict).write_file('INCAR')

            # Shift the top layer
            poscar_lines = open('POSCAR').readlines()
            with open('POSCAR', 'w') as poscar:
                for line in poscar_lines[:8 + n_sites_per_layer]:
                    poscar.write(line)
                for line in poscar_lines[8 + n_sites_per_layer:]:
                    split_line = line.split()
                    new_coords = [
                        float(split_line[0]) + float(x)/float(n_divs_x),
                        float(split_line[1]) + float(y)/float(n_divs_y),
                        float(split_line[2])]
                    poscar.write(' '.join([str(i) for i in new_coords])
                                 + '\n')

            if QUEUE == 'pbs':
                utl.write_pbs_runjob(dir, 1, 4, '800mb', '1:00:00', VASP)
                submission_command = 'qsub runjob'

            elif QUEUE == 'slurm':
                utl.write_slurm_runjob(dir, 4, '800mb', '1:00:00', VASP)
                submission_command = 'sbatch runjob'

            if submit:
                os.system(submission_command)

            os.chdir('../')

    os.chdir('../../')
Ejemplo n.º 56
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 = sorted(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:
                        # Since multiple files are ambiguous, we will always
                        # use the first one for POSCAR and the last one
                        # alphabetically for CONTCAR and OSZICAR.

                        if filename == "POSCAR":
                            files_to_parse[filename] = files[0]
                        else:
                            files_to_parse[filename] = files[-1]
                        warnings.warn(
                            "%d files found. %s is being parsed." %
                            (len(files), files_to_parse[filename]))

            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
Ejemplo n.º 57
0
 def test_write(self):
     tempfname = Path("INCAR.testing")
     self.incar.write_file(tempfname)
     i = Incar.from_file(tempfname)
     self.assertEqual(i, self.incar)
     tempfname.unlink()
Ejemplo n.º 58
0
 def setUp(self):
     file_name = self.TEST_FILES_DIR / 'INCAR'
     self.incar = Incar.from_file(file_name)
Ejemplo n.º 59
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)
        filepath3 = os.path.join(test_dir, "INCAR.3")
        incar3 = 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,
                },
            },
        )

        self.assertEqual(
            incar1.diff(incar3),
            {
                "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,
                },
            },
        )