Exemple #1
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            
Exemple #2
0
 def test_as_dict_from_dict(self):
     k = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0])
     d = k.as_dict()
     k2 = Kpoints.from_dict(d)
     self.assertEqual(k.kpts, k2.kpts)
     self.assertEqual(k.style, k2.style)
     self.assertEqual(k.kpts_shift, k2.kpts_shift)
Exemple #3
0
 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)
Exemple #4
0
 def test_as_dict_from_dict(self):
     k = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0])
     d = k.as_dict()
     k2 = Kpoints.from_dict(d)
     self.assertEqual(k.kpts, k2.kpts)
     self.assertEqual(k.style, k2.style)
     self.assertEqual(k.kpts_shift, k2.kpts_shift)
Exemple #5
0
    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
Exemple #6
0
 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
Exemple #7
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)
Exemple #8
0
    def get_kpoints(self):
        """
        Create and return a :class:`pymatgen.io.vasp.inputs.Kpoints` instance
        initialized from the node's stored k-point data contents.

        :return: a pymatgen Kpoints instance
        :rtype: :class:`pymatgen.io.vasp.inputs.Kpoints`
        """
        return Kpoints.from_dict(self.get_dict())
Exemple #9
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
        #print (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())
            #print (kpoints)
        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):
            #print (self.kpoints_init)
            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
Exemple #10
0
 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"])
Exemple #11
0
 def test_kpt_bands_as_dict_from_dict(self):
     file_name = os.path.join(test_dir, 'KPOINTS.band')
     k = Kpoints.from_file(file_name)
     d = k.as_dict()
     import json
     json.dumps(d)
     # This doesn't work
     k2 = Kpoints.from_dict(d)
     self.assertEqual(k.kpts, k2.kpts)
     self.assertEqual(k.style, k2.style)
     self.assertEqual(k.kpts_shift, k2.kpts_shift)
     self.assertEqual(k.num_kpts, k2.num_kpts)
Exemple #12
0
 def test_kpt_bands_as_dict_from_dict(self):
     file_name = self.TEST_FILES_DIR / 'KPOINTS.band'
     k = Kpoints.from_file(file_name)
     d = k.as_dict()
     import json
     json.dumps(d)
     # This doesn't work
     k2 = Kpoints.from_dict(d)
     self.assertEqual(k.kpts, k2.kpts)
     self.assertEqual(k.style, k2.style)
     self.assertEqual(k.kpts_shift, k2.kpts_shift)
     self.assertEqual(k.num_kpts, k2.num_kpts)
Exemple #13
0
 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"])
Exemple #14
0
 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
Exemple #15
0
 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
    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
Exemple #17
0
    def set_kpoints(self, kpoint=None, poscar=None, ibzkpth=None):
        """
        set the kpoint
        """
        # useful to check if a poscar is supplied from setup_poscar_jobs (most often the case)
        # or this is a single poscar use case
        if not poscar:
            poscar = self.poscar

        # splitting into two if elif branches means fewer if statements to check on
        # a run

        # Most general method of setting the k-points for
        # different grid types
        # NOTE: requires that at least one k-points value be passed
        # as a turn - knobs list value
        # this is not true for values that may be caculated out of
        # a database
        # use this part only if this is a non-database run for example
        # for k-points calibration

        if not self.database:

            if self.Grid_type == 'M':
                self.kpoints = Kpoints.monkhorst_automatic(kpts=kpoint)
            elif self.Grid_type == 'A':
                self.kpoints = Kpoints.automatic(subdivisions=kpoint)
            elif self.Grid_type == 'G':
                self.kpoints = Kpoints.gamma_automatic(kpts=kpoint)
            elif self.Grid_type == '3D_vol':
                self.kpoints = Kpoints.automatic_density_by_vol(structure=poscar.structure,
                                                                kppvol=kpoint)
            elif self.Grid_type == 'bulk_bands_pbe':
                self.kpoints = Kpoints.automatic_linemode(divisions=kpoint,
                                                          ibz=HighSymmKpath(
                                                              poscar.structure))

            elif self.Grid_type == 'D':
                self.kpoints = Kpoints.automatic_density(structure=poscar.structure,kppa=kpoint)

            elif self.Grid_type == 'Finer_G_Mesh':
                # kpoint is the scaling factor and self.kpoints is the old kpoint mesh
                self.logger.info('Setting Finer G Mesh for {0} by scale {1}'.format(kpoint, self.finer_kpoint))
                self.kpoints = Kpoints.gamma_automatic(kpts = \
                   [i * self.finer_kpoint for i in kpoint])
                self.logger.info('Finished scaling operation of k-mesh')

        # applicable for database runs
        # future constructs or settinsg can be activated via a yaml file
        # database yaml file or better still the input deck from its speification
        # decides what combination of input calibrate constructor settings to use
        # one of them being the grid_type tag

        elif self.database == 'twod':

            # set of kpoints settings according to the 2D database profile
            # the actual settings of k-points density
            # will in future come from any database input file set

            if self.Grid_type == 'hse_bands_2D_prep':
                kpoint_dict = Kpoints.automatic_gamma_density(poscar.structure,
                                                              200).as_dict()
                kpoint_dict['kpoints'][0][2] = 1  # remove z kpoints
                self.kpoints = Kpoints.from_dict(kpoint_dict)

            elif self.Grid_type == 'hse_bands_2D':
                # can at most return the path to the correct kpoints file
                # needs kpoints to be written out in instrument in a different way
                # not using the Kpoints object
                self.kpoints = get_2D_hse_kpoints(poscar.structure, ibzkpth)

            elif self.Grid_type == 'bands_2D':
                kpoint_dict = Kpoints.automatic_linemode(divisions=20,
                                                         ibz=HighSymmKpath(poscar.structure)).as_dict()
                self.kpoints = Kpoints.from_dict(kpoint_dict)

            elif self.Grid_type == 'relax_2D':
                # general relaxation settings for 2D
                kpoint_dict = Kpoints.automatic_gamma_density(poscar.structure,
                                                              1000).as_dict()
                kpoint_dict['kpoints'][0][2] = 1
                self.kpoints = Kpoints.from_dict(kpoint_dict)

            elif self.Grid_type == 'relax_3D':
                # general relaxation settings for 3D
                kpoint_dict = Kpoints.automatic_gamma_density(
                    poscar.structure, 1000)
                self.kpoints = Kpoints.from_dict(kpoint_dict)
from matgendb.creator import VaspToDbTaskDrone

drone = VaspToDbTaskDrone(collection='test')

for j in ds:
    drone.assimilate(j.path)

#%%

from matgendb.query_engine import QueryEngine

qe = QueryEngine(collection='test')

# entries = qe.get_entries({'dir_name':'localhost:/home/lorenzo/tests/project-test/tutorials/Si-BS-dataset/3-PBE-BS'})

entries = qe.get_entries({'chemsys': 'Si'},
                         optional_data=['calculations'],
                         inc_structure=True)

#%%

e = entries[0]
inputs = e.data['calculations'][0]['input']
incar = Incar(inputs['incar'])
kpoints = Kpoints.from_dict(inputs['kpoints'])
poscar = Poscar(e.structure)
potcar = Potcar(inputs['potcar'])

vaspinput = VaspInput(incar, kpoints, poscar, potcar)

#%%
Exemple #19
0
def make_vasp_defect_files(defects, path_base, user_settings={}, hse=False):
    """
    Generates VASP files for defect computations
    Args:
        defect_structs:
            the defects data as a dictionnary. Ideally this is generated
            from core.defectsmaker.ChargedDefectsStructures.
        path_base:
            where we write the files
        user_settings:
            Settings in dict format to override the defaults used in 
            generating vasp files. The format of the dictionary is
            {'defects:{'INCAR':{...},'KPOINTS':{...},
             'bulk':{'INCAR':{...},'KPOINTS':{...}}
        hse:
            hse run or not
    """
    bulk_sys = defects['bulk']['supercell']
    comb_defs = functools.reduce(lambda x, y: x+y, [
        defects[key] for key in defects if key != 'bulk'])

    # User setting dicts
    user_settings = deepcopy(user_settings)
    user_incar = user_settings.pop('INCAR', {})
    user_incar_blk_tmp = user_incar.pop('bulk', {})
    user_incar_blk_def = user_incar.pop('defects', {})
    user_incar.pop('dielectric', {})
    user_incar_blk = deepcopy(user_incar)
    user_incar_def = deepcopy(user_incar)
    user_incar_blk.update(user_incar_blk_tmp)
    user_incar_def.update(user_incar_blk_def)
    user_kpoints = user_settings.pop('KPOINTS', {})
    potcar_settings = user_settings.pop('POTCAR', {})
    potcar_functional = potcar_settings.pop('functional', 'PBE')

    for defect in comb_defs:
        for charge in defect['charges']:
            s = defect['supercell']
            dict_transf = {
                    'defect_type': defect['name'], 
                    'defect_site': defect['unique_site'], 
                    'defect_supercell_site': defect['bulk_supercell_site'],
                    'defect_multiplicity': defect['site_multiplicity'],
                    'charge': charge, 'supercell': s['size']}
            if 'substitution_specie' in defect:
                dict_transf['substitution_specie'] = defect['substitution_specie']

            defect_relax_set = DefectRelaxSet(
                s['structure'], user_incar_settings=user_incar_def,
                user_potcar_settings=potcar_settings,
                potcar_functional=potcar_functional, charge=charge)

            path = os.path.join(path_base, defect['name'],
                                "charge_"+str(charge))
            try:
                potcar = defect_relax_set.potcar
            except:
                potcar = None

            if potcar or not charge:
                defect_relax_set.write_input(path)
                incar = defect_relax_set.incar if hse else {}
                kpoints = Kpoints.from_dict(user_kpoints) if user_kpoints \
                    else None

                write_additional_files(path, dict_transf, incar=incar,
                                       kpoints=kpoints, hse=hse)
            else:
                os.makedirs(path)
                with open(os.path.join(path, 'readme.txt'), 'w') as fp:
                    print("Vasp input files not generated for charged defects "
                          "due to unavailability of POTCAR. "
                          "If charged defects desired, please supply POTCAR file "
                          "path to .pmgrc.yaml file.", end="", file=fp)

    # Generate bulk supercell inputs
    s = bulk_sys
    dict_transf = {'defect_type': 'bulk', 'supercell': s['size']}

    #potcar_functional = user_potcar.get('functional', 'PBE')
    blk_static_set = DefectStaticSet(s['structure'],
                                     user_incar_settings=user_incar_blk,
                                     user_potcar_settings=potcar_settings,
                                     potcar_functional=potcar_functional)
    path = os.path.join(path_base, 'bulk')
    blk_static_set.write_input(path)

    incar = blk_static_set.incar if hse else {}
    kpoints = Kpoints.from_dict(user_kpoints) if user_kpoints else None

    write_additional_files(path, dict_transf, incar=incar, kpoints=kpoints,
                           hse=hse)