コード例 #1
0
ファイル: startup.py プロジェクト: ashtonmv/twod_materials
def run_major_axis_anisotropy_calculations(submit=True):
    """
    Perform static calculations with the magnetic axis along
    100, 010, and 001.

    Kwargs:
        submit (bool): Whether or not to submit the job.
    """

    if not os.path.isdir('MAE'):
        os.mkdir('MAE')
    os.chdir('MAE')
    for d in ['100', '010', '001']:
        if not os.path.isdir(d):
            os.path.mkdir(d)
        os.chdir(d)
        os.system('cp ../CONTCAR POSCAR')
        os.system('cp ../POTCAR .')
        axis = [float(char) for char in d]
        # Small positive number, see vasp manual
        if d in ['001', '010']:
            axis[0] = 0.00000001
        else:
            axis[1] = 0.00000001

        saxis = ' '.join(axis)
        incar_dict = INCAR_DICT
        incar_dict.update({'EDIFF': 1e-8, 'GGA_COMPAT': False, 'ISMEAR': -5,
                           'LORBIT': 11, 'LSORBIT': True, 'LWAVE': False,
                           'LCHARG': False, 'LAECHG': False,
                           'MAGMOM': get_magmom_string(), 'SAXIS': saxis})
        Incar.from_dict(incar_dict).write_file('INCAR')

        if submit:
            os.system(submission_command)
コード例 #2
0
ファイル: test_inputs.py プロジェクト: ExpHP/pymatgen
 def test_as_dict_and_from_dict(self):
     d = self.incar.as_dict()
     incar2 = Incar.from_dict(d)
     self.assertEqual(self.incar, incar2)
     d["MAGMOM"] = [Magmom([1, 2, 3]).as_dict()]
     incar3 = Incar.from_dict(d)
     self.assertEqual(incar3["MAGMOM"], [Magmom([1, 2, 3])])
コード例 #3
0
ファイル: test_inputs.py プロジェクト: gpetretto/pymatgen
    def test_lsorbit_magmom(self):
        magmom1 = [[0.0, 0.0, 3.0], [0, 1, 0], [2, 1, 2]]
        magmom2 = [-1, -1, -1, 0, 0, 0, 0, 0]

        ans_string1 = "LSORBIT = True\nMAGMOM = 0.0 0.0 3.0 0 1 0 2 1 2\n"
        ans_string2 = "LSORBIT = True\nMAGMOM = 3*3*-1 3*5*0\n"
        ans_string3 = "LSORBIT = False\nMAGMOM = 2*-1 2*9\n"

        incar = Incar({})
        incar["MAGMOM"] = magmom1
        incar["LSORBIT"] = "T"
        self.assertEqual(ans_string1, str(incar))

        incar["MAGMOM"] = magmom2
        incar["LSORBIT"] = "T"
        self.assertEqual(ans_string2, str(incar))

        incar = Incar.from_string(ans_string1)
        self.assertEqual(incar["MAGMOM"], [[0.0, 0.0, 3.0], [0, 1, 0], [2, 1, 2]])

        incar = Incar.from_string(ans_string2)
        self.assertEqual(
            incar["MAGMOM"],
            [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
        )

        incar = Incar.from_string(ans_string3)
        self.assertFalse(incar["LSORBIT"])
        self.assertEqual(incar["MAGMOM"], [-1, -1, 9, 9])
コード例 #4
0
ファイル: startup.py プロジェクト: henniggroup/MPInterfaces
def relax(dim=2, submit=True, force_overwrite=False):
    """
    Writes input files and (optionally) submits a self-consistent
    relaxation. Should be run before pretty much anything else, in
    order to get the right energy and structure of the material.

    Args:
        dim (int): 2 for relaxing a 2D material, 3 for a 3D material.
        submit (bool): Whether or not to submit the job.
        force_overwrite (bool): Whether or not to overwrite files
            if an already converged vasprun.xml exists in the
            directory.
    """

    if force_overwrite or not utl.is_converged(os.getcwd()):
        directory = os.getcwd().split('/')[-1]

        # vdw_kernel.bindat file required for VDW calculations.
        if VDW_KERNEL:
            os.system('cp {} .'.format(VDW_KERNEL))
        # KPOINTS
        Kpoints.automatic_density(Structure.from_file('POSCAR'),
                                  1000).write_file('KPOINTS')

        # INCAR
        INCAR_DICT.update(
            {'MAGMOM': utl.get_magmom_string(Structure.from_file('POSCAR'))}
        )
        Incar.from_dict(INCAR_DICT).write_file('INCAR')
        # POTCAR
        utl.write_potcar()

        # Special tasks only performed for 2D materials.
        if dim == 2:
            # Ensure 20A interlayer vacuum
            utl.ensure_vacuum(Structure.from_file('POSCAR'), 20)
            # Remove all z k-points.
            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')

        # Submission script
        if dim == 2:
            binary = VASP_TWOD_BIN
        elif dim == 3:
            binary = VASP_STD_BIN
        if QUEUE_SYSTEM == 'pbs':
            utl.write_pbs_runjob(directory, 1, 16, '800mb', '6:00:00', binary)
            submission_command = 'qsub runjob'

        elif QUEUE_SYSTEM == 'slurm':
            utl.write_slurm_runjob(directory, 16, '800mb', '6:00:00', binary)
            submission_command = 'sbatch runjob'

        if submit:
            os.system(submission_command)
コード例 #5
0
ファイル: startup.py プロジェクト: henniggroup/MPInterfaces
def run_major_axis_anisotropy_calculations(submit=True):
    """
    Perform static calculations with the magnetic axis along
    100, 010, and 001.

    Args:
        submit (bool): Whether or not to submit the job.
    """

    if not os.path.isdir('MAE'):
        os.mkdir('MAE')
    os.chdir('MAE')
    for d in ['100', '010', '001']:
        if not os.path.isdir(d):
            os.mkdir(d)
        os.chdir(d)
        os.system('cp ../CONTCAR POSCAR')
        os.system('cp ../POTCAR .')
        axis = [float(char) for char in d]
        # Small positive number, see vasp manual
        if d in ['001', '010']:
            axis[0] = 0.00000001
        else:
            axis[1] = 0.00000001

        saxis = ' '.join(axis)
        incar_dict = INCAR_DICT
        incar_dict.update({'EDIFF': 1e-8,
                           'GGA_COMPAT': False,
                           'ISMEAR': -5,
                           'LORBIT': 11,
                           'LSORBIT': True,
                           'LWAVE': False,
                           'LCHARG': False,
                           'LAECHG': False,
                           'MAGMOM': get_magmom_string(
                                Structure.from_file('POSCAR')
                            ),
                           'SAXIS': saxis})
        Incar.from_dict(incar_dict).write_file('INCAR')

        if QUEUE_SYSTEM == 'pbs':
            utl.write_pbs_runjob(directory, 1, 16, '800mb', '6:00:00',
                VASP_TWOD_BIN)
            submission_command = 'qsub runjob'

        elif QUEUE_SYSTEM == 'slurm':
            utl.write_slurm_runjob(directory, 16, '800mb', '6:00:00',
                VASP_TWOD_BIN)
            submission_command = 'sbatch runjob'

        if submit:
            os.system(submission_command)
コード例 #6
0
ファイル: startup.py プロジェクト: ashtonmv/twod_materials
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('../')
コード例 #7
0
ファイル: instrument.py プロジェクト: wwmeng/MPInterfaces
 def __init__(self, name, incar, poscar, potcar, kpoints,
              qadapter=None, script_name='submit_script',
              vis_logger=None, **kwargs):
     """
     default INCAR from config_dict
     
     """
     self.name = name
     self.incar = Incar.from_dict(incar.as_dict())
     self.poscar = Poscar.from_dict(poscar.as_dict())
     self.potcar = Potcar.from_dict(potcar.as_dict())
     self.kpoints = Kpoints.from_dict(kpoints.as_dict())
     self.extra = kwargs
     if qadapter is not None:
         self.qadapter = qadapter.from_dict(qadapter.to_dict())
     else:
         self.qadapter = None
     self.script_name = script_name
     config_dict = {}
     config_dict['INCAR'] = self.incar.as_dict()
     config_dict['POSCAR'] = self.poscar.as_dict()
     # caution the key and the value are not always the same
     config_dict['POTCAR'] = self.potcar.as_dict()
     # dict(zip(self.potcar.as_dict()['symbols'],
     # self.potcar.as_dict()['symbols']))
     config_dict['KPOINTS'] = self.kpoints.as_dict()
     # self.user_incar_settings = self.incar.as_dict()
     DictVaspInputSet.__init__(self, name, config_dict,
                               ediff_per_atom=False, **kwargs)
     if vis_logger:
         self.logger = vis_logger
     else:
         self.logger = logger
コード例 #8
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")
コード例 #9
0
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
コード例 #10
0
    def convert_computed_entry_to_job(self,entry):
        """
        Convert ComputedStructureEntry into VaspJob object

        Parameters
        ----------
        entry : 
            ComputedStructureEntry.

        Returns
        -------
        vaspjob : 
            VaspJob object.
        """
        e = entry
        path = e.data['dir_name']
        
        inp = e.data['calculations'][0]['input']           
        incar = Incar(inp['incar'])
        kpoints = Kpoints.from_dict(inp['kpoints'])
        poscar = Poscar(e.structure)
        potcar = Potcar(inp['potcar'])
        
        inputs = VaspInput(incar, kpoints, poscar, potcar)
        job_settings = e.data['job_settings']
        job_script_filename = e.data['job_script_filename']
        name = e.data['job_name']
        
        outputs = {'ComputedStructureEntry':e}
        
        vaspjob =  VaspJob(path,inputs,job_settings,outputs,job_script_filename,name)
        vaspjob._is_converged = e.data['is_converged']
        vaspjob._band_structure = None
            
        return vaspjob            
コード例 #11
0
ファイル: jobs.py プロジェクト: lorenzo-villa-hub/pynter
    def from_dict(d):

        path = d['path']
        inputs = {}
        inputs["structures"] = [
            Structure.from_dict(s) for s in d['inputs']['structures']
        ]
        inputs["INCAR"] = Incar.from_dict(d['inputs']['INCAR'])
        inputs["KPOINTS"] = Kpoints.from_dict(d['inputs']['KPOINTS'])
        inputs["POTCAR"] = Potcar.from_dict(d['inputs']['POTCAR'])
        job_settings = d['job_settings']
        job_script_filename = d['job_script_filename']
        name = d['name']
        outputs = {}

        vaspNEBjob = VaspNEBJob(path, inputs, job_settings, outputs,
                                job_script_filename, name)

        vaspNEBjob._is_step_limit_reached = d['is_step_limit_reached']
        vaspNEBjob._is_converged = d['is_converged']
        vaspNEBjob._r = np.array(d['r'])
        vaspNEBjob._energies = np.array(d['energies'])
        vaspNEBjob._forces = np.array(d['forces'])

        return vaspNEBjob
コード例 #12
0
ファイル: core.py プロジェクト: zezhong-zhang/vsc-workflows
    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")
コード例 #13
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")
コード例 #14
0
ファイル: utils.py プロジェクト: GuodongYu/high_throughput
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
コード例 #15
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)
コード例 #16
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)
コード例 #17
0
def auto_incar(params: Dict[str, Any] = None) -> Incar:
    # kk = grep 'entropy T'  OUTCAR
    # rkk = kk/n_atom<0.001ev  检查
    """"""
    if params is None:
        params = {}
    notes, params = pop_note(params)
    params.update(_ISMEAR(notes, params))
    params.update(_SIGMA(notes, params))
    params.update(_ISTART(notes, params))
    params.update(_ICHARG(notes, params))
    params.update(_ISPIN(notes, params))
    params.update(_PREC(notes, params))
    params.update(_ENCUT(notes, params))
    params.update(_IBRION(notes, params))
    params.update(_ISIF(notes, params))
    params.update(_IVDW(notes, params))
    params.update(_NSW(notes, params))
    params.update(_LORBIT(notes, params))
    params.update(_NBANDS(notes, params))
    # if "SYSTEM" not in params:
    #     params.update({"SYSTEM": "test_write_time_{}".format(time.time())})

    incar = Incar(params)

    return incar
コード例 #18
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)
コード例 #19
0
ファイル: instrument.py プロジェクト: mbkumar/MPInterfaces
 def __init__(self, name, incar, poscar, potcar, kpoints,
              qadapter=None, **kwargs ):
     """
     default INCAR from config_dict
     
     """
     self.name = name
     self.incar = Incar.from_dict(incar.as_dict())
     self.poscar = Poscar.from_dict(poscar.as_dict())
     self.potcar = Potcar.from_dict(potcar.as_dict())
     self.kpoints = Kpoints.from_dict(kpoints.as_dict())
     self.extra = kwargs
     if qadapter is not None:
         self.qadapter = qadapter.from_dict(qadapter.to_dict())
     else:
         self.qadapter = None        
     config_dict = {}
     config_dict['INCAR'] = self.incar.as_dict()
     config_dict['POSCAR'] = self.poscar.as_dict() 
     #caution the key and the value are not always the same        
     config_dict['POTCAR'] = self.potcar.as_dict() 
     #dict(zip(self.potcar.as_dict()['symbols'],
     #self.potcar.as_dict()['symbols']))
     config_dict['KPOINTS'] = self.kpoints.as_dict()
     #self.user_incar_settings = self.incar.as_dict()        
     DictVaspInputSet.__init__(self, name, config_dict,
                                ediff_per_atom=False, **kwargs)
コード例 #20
0
ファイル: jobs.py プロジェクト: lorenzo-villa-hub/pynter
    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
コード例 #21
0
def hse():
    allline = ''
    s = Structure.from_file("POSCAR")
    incar_dict = dict(PREC='Accurate',
                      ENCUT=45678,
                      NBANDS=456789,
                      ISMEAR=0,
                      EDIFF='1E-7',
                      LCHARG='.FALSE.',
                      NEDOS=5000,
                      ISPIN=2,
                      ISIF=2,
                      IBRION=1,
                      NELM=400,
                      LORBIT=11,
                      NPAR=4,
                      LWAVE='.FALSE.')
    incar = Incar.from_dict(incar_dict)
    user_incar_settings = {
        "EDIFF": 1E-6,
        "ISIF": 2,
        "NSW": 0,
        "LORBIT": 11,
        "ENCUT": 34,
        "LWAVE": '.FALSE.',
        "PREC": 'Accurate'
    }
    mpvis = MPBSHSEVaspInputSet(user_incar_settings=incar)
    kpoints = mpvis.get_kpoints(s)
    kpoints.write_file("KPOINTS")
コード例 #22
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)
コード例 #23
0
ファイル: core.py プロジェクト: sonersteiner/BayesianOpt4dftu
    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)
コード例 #24
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")
コード例 #25
0
ファイル: measurement.py プロジェクト: matk86/MPInterfaces
 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)
コード例 #26
0
ファイル: core.py プロジェクト: zezhong-zhang/vsc-workflows
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))
コード例 #27
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)
コード例 #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)
コード例 #29
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)
コード例 #30
0
    def _write_incar(self, calculator):
        """
        Writes INCAR file.
        
        Arguments
        ---------
        calculator: dict
            Calculation configulation as ASE format.
        
        Parameters
        ----------
        incar_dict: dict
            Dictionary of incar setting.
        """
        incar_dict = {
            "SYSTEM": self._struct_name,
            "ALGO": "VeryFast",
            "LWAVE": False,
            "ISTART": 0,
            "ICHARG": 2,
            "ISPIN": 1,
            "IBRION": 1,
            "ISYM": 0,
            "ISIF": 3
        }

        if calculator.get("maxiter") is not None:
            incar_dict["NELM"] = calculator["maxiter"]

        if calculator.get("isif") is not None:
            incar_dict["isif"] = calculator["isif"]

        with open("INCAR", mode="w") as file:
            file.writelines(str(Incar(incar_dict)))
コード例 #31
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})
コード例 #32
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)
コード例 #33
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)
コード例 #34
0
ファイル: jobs.py プロジェクト: sayred1/custodian
    def postprocess(self):
        """
        Postprocessing includes renaming and gzipping where necessary.
        Also copies the magmom to the incar if necessary
        """
        for f in VASP_OUTPUT_FILES + [self.output_file]:
            if os.path.exists(f):
                if self.final and self.suffix != "":
                    shutil.move(f, "{}{}".format(f, self.suffix))
                elif self.suffix != "":
                    shutil.copy(f, "{}{}".format(f, self.suffix))

        if self.copy_magmom and not self.final:
            try:
                outcar = Outcar("OUTCAR")
                magmom = [m["tot"] for m in outcar.magnetization]
                incar = Incar.from_file("INCAR")
                incar["MAGMOM"] = magmom
                incar.write_file("INCAR")
            except 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")
コード例 #35
0
ファイル: wannier.py プロジェクト: Djordje117/2D
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')
コード例 #36
0
def run_pbe_calculation(dim=2, submit=True, force_overwrite=False):
    """
    Setup and submit a normal PBE calculation for band structure along
    high symmetry k-paths.

    Args:
        dim (int): 2 for relaxing a 2D material, 3 for a 3D material.
        submit (bool): Whether or not to submit the job.
        force_overwrite (bool): Whether or not to overwrite files
            if an already converged vasprun.xml exists in the
            directory.
    """

    PBE_INCAR_DICT = {'EDIFF': 1e-6, 'IBRION': 2, 'ISIF': 3,
                      'ISMEAR': 1, 'NSW': 0, 'LVTOT': True, 'LVHAR': True,
                      'LORBIT': 1, 'LREAL': 'Auto', 'NPAR': 4,
                      'PREC': 'Accurate', 'LWAVE': True, 'SIGMA': 0.1,
                      'ENCUT': 500, 'ISPIN': 2}

    directory = os.getcwd().split('/')[-1]

    if not os.path.isdir('pbe_bands'):
        os.mkdir('pbe_bands')
    if force_overwrite or not is_converged('pbe_bands'):
        os.system('cp CONTCAR pbe_bands/POSCAR')
        if os.path.isfile('POTCAR'):
            os.system('cp POTCAR pbe_bands/')
        PBE_INCAR_DICT.update({'MAGMOM': get_magmom_string()})
        Incar.from_dict(PBE_INCAR_DICT).write_file('pbe_bands/INCAR')
        structure = Structure.from_file('POSCAR')
        kpath = HighSymmKpath(structure)
        Kpoints.automatic_linemode(20, kpath).write_file('pbe_bands/KPOINTS')
        os.chdir('pbe_bands')
        if dim == 2:
            remove_z_kpoints()
        if QUEUE == 'pbs':
            write_pbs_runjob(directory, 1, 16, '800mb', '6:00:00', VASP)
            submission_command = 'qsub runjob'

        elif QUEUE == 'slurm':
            write_slurm_runjob(directory, 16, '800mb', '6:00:00', VASP)
            submission_command = 'sbatch runjob'

        if submit:
            os.system(submission_command)

        os.chdir('../')
コード例 #37
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)
コード例 #38
0
ファイル: jobs.py プロジェクト: srshivani/custodian
    def setup(self):
        """
        Performs initial setup for VaspJob, including overriding any settings
        and backing up.
        """
        decompress_dir('.')

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

        if self.auto_continue:
            if os.path.exists("continue.json"):
                actions = loadfn("continue.json").get("actions")
                logger.info("Continuing previous VaspJob. Actions: {}".format(actions))
                backup(VASP_BACKUP_FILES, prefix="prev_run")
                VaspModder().apply_actions(actions)

            else:
                # Default functionality is to copy CONTCAR to POSCAR and set
                # ISTART to 1 in the INCAR, but other actions can be specified
                if self.auto_continue is True:
                    actions = [{"file": "CONTCAR",
                                "action": {"_file_copy": {"dest": "POSCAR"}}},
                               {"dict": "INCAR",
                                "action": {"_set": {"ISTART": 1}}}]
                else:
                    actions = self.auto_continue
                dumpfn({"actions": actions}, "continue.json")

        if self.settings_override is not None:
            VaspModder().apply_actions(self.settings_override)
コード例 #39
0
ファイル: test_inputs.py プロジェクト: ExpHP/pymatgen
 def test_quad_efg(self):
     incar1 = Incar({})
     incar1["LEFG"] = True
     incar1["QUAD_EFG"] = [0.0, 146.6, -25.58]
     ans_string1 = "LEFG = True\nQUAD_EFG = 0.0 146.6 -25.58\n"
     self.assertEqual(ans_string1, str(incar1))
     incar2 = Incar.from_string(ans_string1)
     self.assertEqual(ans_string1, str(incar2))
コード例 #40
0
ファイル: test_inputs.py プロジェクト: ExpHP/pymatgen
    def test_lsorbit_magmom(self):
        magmom1 = [[0.0, 0.0, 3.0], [0, 1, 0], [2, 1, 2]]
        magmom2 = [-1, -1, -1, 0, 0, 0, 0, 0]
        magmom4 = [Magmom([1.0, 2.0, 2.0])]

        ans_string1 = "LANGEVIN_GAMMA = 10 10 10\nLSORBIT = True\n" \
                      "MAGMOM = 0.0 0.0 3.0 0 1 0 2 1 2\n"
        ans_string2 = "LANGEVIN_GAMMA = 10\nLSORBIT = True\n" \
                      "MAGMOM = 3*3*-1 3*5*0\n"
        ans_string3 = "LSORBIT = False\nMAGMOM = 2*-1 2*9\n"
        ans_string4_nolsorbit = "LANGEVIN_GAMMA = 10\nLSORBIT = False\nMAGMOM = 1*3.0\n"
        ans_string4_lsorbit = "LANGEVIN_GAMMA = 10\nLSORBIT = True\nMAGMOM = 1.0 2.0 2.0\n"

        incar = Incar({})
        incar["MAGMOM"] = magmom1
        incar["LSORBIT"] = "T"
        incar["LANGEVIN_GAMMA"] = [10, 10, 10]
        self.assertEqual(ans_string1, str(incar))

        incar["MAGMOM"] = magmom2
        incar["LSORBIT"] = "T"
        incar["LANGEVIN_GAMMA"] = 10
        self.assertEqual(ans_string2, str(incar))

        incar["MAGMOM"] = magmom4
        incar["LSORBIT"] = "F"
        self.assertEqual(ans_string4_nolsorbit, str(incar))
        incar["LSORBIT"] = "T"
        self.assertEqual(ans_string4_lsorbit, str(incar))

        incar = Incar.from_string(ans_string1)
        self.assertEqual(incar["MAGMOM"],
                         [[0.0, 0.0, 3.0], [0, 1, 0], [2, 1, 2]])
        self.assertEqual(incar["LANGEVIN_GAMMA"], [10, 10, 10])

        incar = Incar.from_string(ans_string2)
        self.assertEqual(incar["MAGMOM"], [[-1, -1, -1], [-1, -1, -1],
                                           [-1, -1, -1], [0, 0, 0],
                                           [0, 0, 0], [0, 0, 0],
                                           [0, 0, 0], [0, 0, 0]])
        self.assertEqual(incar["LANGEVIN_GAMMA"], [10])

        incar = Incar.from_string(ans_string3)
        self.assertFalse(incar["LSORBIT"])
        self.assertEqual(incar["MAGMOM"], [-1, -1, 9, 9])
コード例 #41
0
ファイル: instrument.py プロジェクト: mbkumar/MPInterfaces
 def from_dict(cls, d):
     incar = Incar.from_dict(d["incar"])
     poscar = Poscar.from_dict(d["poscar"])
     potcar = Potcar.from_dict(d["potcar"])
     kpoints = Kpoints.from_dict(d["kpoints"])
     qadapter = None
     if d["qadapter"] is not None:
         qadapter = CommonAdapter.from_dict(d["qadapter"])
     return MPINTVaspInputSet(d["name"], incar, poscar, potcar,
                              kpoints, qadapter, **d["kwargs"])
コード例 #42
0
ファイル: test_sets.py プロジェクト: AtlasL/pymatgen
    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')
コード例 #43
0
ファイル: test_inputs.py プロジェクト: ExpHP/pymatgen
    def test_write(self):
        tmp_dir = "VaspInput.testing"
        self.vinput.write_input(tmp_dir)

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

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

        os.rmdir(tmp_dir)
コード例 #44
0
ファイル: test_inputs.py プロジェクト: adengz/pymatgen
    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()
コード例 #45
0
ファイル: test_inputs.py プロジェクト: adengz/pymatgen
 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)
コード例 #46
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)]
コード例 #47
0
ファイル: instrument.py プロジェクト: HanmeiTang/MPInterfaces
 def from_dict(cls, d):
     incar = Incar.from_dict(d["incar"])
     poscar = Poscar.from_dict(d["poscar"])
     potcar = Potcar.from_dict(d["potcar"])
     kpoints = Kpoints.from_dict(d["kpoints"])
     qadapter = None
     if d["qadapter"] is not None:
         qadapter = CommonAdapter.from_dict(d["qadapter"])
     script_name = d["script_name"]
     return MPINTVaspInputSet(d["name"], incar, poscar, potcar,
                              kpoints, qadapter,
                              script_name=script_name,
                              vis_logger=logging.getLogger(d["logger"]),
                              **d["kwargs"])
コード例 #48
0
ファイル: test_inputs.py プロジェクト: ExpHP/pymatgen
 def setUp(self):
     filepath = os.path.join(test_dir, 'INCAR')
     incar = Incar.from_file(filepath)
     filepath = os.path.join(test_dir, 'POSCAR')
     poscar = Poscar.from_file(filepath,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)
コード例 #49
0
ファイル: test_inputs.py プロジェクト: ExpHP/pymatgen
    def test_types(self):
        incar_str = """ALGO = Fast
ECUT = 510
EDIFF = 1e-07
EINT = -0.85 0.85
IBRION = -1
ICHARG = 11
ISIF = 3
ISMEAR = 1
ISPIN = 1
LPARD = True
NBMOD = -3
PREC = Accurate
SIGMA = 0.1"""
        i = Incar.from_string(incar_str)
        self.assertIsInstance(i["EINT"], list)
        self.assertEqual(i["EINT"][0], -0.85)

        incar_str += "\nLHFCALC = .TRUE. ; HFSCREEN = 0.2"
        incar_str += "\nALGO = All;"
        i = Incar.from_string(incar_str)
        self.assertTrue(i["LHFCALC"])
        self.assertEqual(i["HFSCREEN"], 0.2)
        self.assertEqual(i["ALGO"], "All")
コード例 #50
0
ファイル: test_inputs.py プロジェクト: gpetretto/pymatgen
 def setUp(self):
     filepath = os.path.join(test_dir, "INCAR")
     incar = Incar.from_file(filepath)
     filepath = os.path.join(test_dir, "POSCAR")
     poscar = Poscar.from_file(filepath)
     if "VASP_PSP_DIR" not in os.environ:
         test_potcar_dir = os.path.abspath(
             os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "test_files")
         )
         os.environ["VASP_PSP_DIR"] = test_potcar_dir
     filepath = os.path.join(test_dir, "POTCAR")
     potcar = Potcar.from_file(filepath)
     filepath = os.path.join(test_dir, "KPOINTS.auto")
     kpoints = Kpoints.from_file(filepath)
     self.vinput = VaspInput(incar, kpoints, poscar, potcar)
コード例 #51
0
ファイル: calibrate.py プロジェクト: zhuyizhou/MPInterfaces
 def from_dict(cls, d):
     incar = Incar.from_dict(d["incar"])
     poscar = Poscar.from_dict(d["poscar"])
     potcar = Potcar.from_dict(d["potcar"])
     kpoints = Kpoints.from_dict(d["kpoints"])
     cal =  Calibrate(incar, poscar, potcar, kpoints, 
                      system=d["system"], is_matrix = d["is_matrix"], 
                      Grid_type = d["Grid_type"], 
                      parent_job_dir=d["parent_job_dir"], 
                      job_dir=d["job_dir"], qadapter=d.get("qadapter"), 
                      job_cmd=d["job_cmd"], wait=d["wait"],
                      turn_knobs=d["turn_knobs"])
     cal.job_dir_list = d["job_dir_list"]
     cal.job_ids = d["job_ids"]
     return cal
コード例 #52
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)
コード例 #53
0
ファイル: analysis.py プロジェクト: henniggroup/MPInterfaces
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()
コード例 #54
0
ファイル: test_inputs.py プロジェクト: matk86/pymatgen
    def test_types(self):
        incar_str = """ALGO = Fast
ECUT = 510
EDIFF = 1e-07
EINT = -0.85 0.85
IBRION = -1
ICHARG = 11
ISIF = 3
ISMEAR = 1
ISPIN = 1
LPARD = True
NBMOD = -3
PREC = Accurate
SIGMA = 0.1"""
        i = Incar.from_string(incar_str)
        self.assertIsInstance(i["EINT"], list)
        self.assertEqual(i["EINT"][0], -0.85)
コード例 #55
0
    def __init__(self, name, incar, poscar, kpoints, potcar=None,
                 qadapter=None, script_name='submit_script',
                 vis_logger=None, reuse_path=None, test=False,
                 **kwargs):
        """
        default INCAR from config_dict

        """
        self.name = name
        self.test = test
        self.incar_init = Incar.from_dict(incar.as_dict())
        self.poscar_init = Poscar.from_dict(poscar.as_dict())
        if not self.test:
            self.potcar_init = Potcar.from_dict(potcar.as_dict())
        if not isinstance(kpoints, str):
            self.kpoints_init = Kpoints.from_dict(kpoints.as_dict())
        else:
            self.kpoints_init = kpoints
        self.reuse_path = reuse_path  # complete reuse paths
        self.extra = kwargs
        if qadapter is not None:
            self.qadapter = qadapter.from_dict(qadapter.to_dict())
        else:
            self.qadapter = None
        self.script_name = script_name
        config_dict = {}
        config_dict['INCAR'] = self.incar_init.as_dict()
        config_dict['POSCAR'] = self.poscar_init.as_dict()
        # caution the key and the value are not always the same
        if not self.test:
            config_dict['POTCAR'] = self.potcar_init.as_dict()
        # dict(zip(self.potcar.as_dict()['symbols'],
        # self.potcar.as_dict()['symbols']))
        if not isinstance(kpoints, str):
            config_dict['KPOINTS'] = self.kpoints_init.as_dict()
        else:
            # need to find a way to dictify this kpoints string more
            # appropriately
            config_dict['KPOINTS'] = {'kpts_hse':self.kpoints_init}
        # self.user_incar_settings = self.incar.as_dict()
        DictSet.__init__(self, poscar.structure, config_dict)
                         #**kwargs)
        if vis_logger:
            self.logger = vis_logger
        else:
            self.logger = logger
コード例 #56
0
ファイル: test_sets.py プロジェクト: yiwang62/pymatgen
    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)
コード例 #57
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)
コード例 #58
0
ファイル: analysis.py プロジェクト: ashtonmv/twod_materials
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()