コード例 #1
0
    def setUp(self):
        filepath = os.path.join(test_dir, 'POSCAR')
        poscar = Poscar.from_file(filepath)
        self.struct = poscar.structure

        self.mitparamset = MITVaspInputSet()
        self.mitparamset_unsorted = MITVaspInputSet(sort_structure=False)
        self.mithseparamset = MITHSEVaspInputSet()
        self.paramset = MPVaspInputSet()
        self.userparamset = MPVaspInputSet(
            user_incar_settings={'MAGMOM': {
                "Fe": 10,
                "S": -5,
                "Mn3+": 100
            }})
        self.mitggaparam = MITGGAVaspInputSet()
        self.mpstaticparamset = MPStaticVaspInputSet()
        self.mpnscfparamsetu = MPNonSCFVaspInputSet({"NBANDS": 50},
                                                    mode="Uniform")
        self.mpnscfparamsetl = MPNonSCFVaspInputSet({"NBANDS": 60},
                                                    mode="Line")
        self.mphseparamset = MPHSEVaspInputSet()
        self.mpbshseparamsetl = MPBSHSEVaspInputSet(mode="Line")
        self.mpbshseparamsetu = MPBSHSEVaspInputSet(
            mode="Uniform", added_kpoints=[[0.5, 0.5, 0.0]])
        self.mpdielparamset = MPStaticDielectricDFPTVaspInputSet()
コード例 #2
0
    def test_to_from_dict(self):
        self.mitparamset = MITVaspInputSet()
        self.mithseparamset = MITHSEVaspInputSet()
        self.paramset = MPVaspInputSet()
        self.userparamset = MPVaspInputSet(
            {'MAGMOM': {
                "Fe": 10,
                "S": -5,
                "Mn3+": 100
            }})

        d = self.mitparamset.to_dict
        v = dec.process_decoded(d)
        self.assertEqual(type(v), MITVaspInputSet)

        d = self.mitggaparam.to_dict
        v = dec.process_decoded(d)
        self.assertEqual(type(v), MITGGAVaspInputSet)

        d = self.mithseparamset.to_dict
        v = dec.process_decoded(d)
        self.assertEqual(type(v), MITHSEVaspInputSet)

        d = self.paramset.to_dict
        v = dec.process_decoded(d)
        self.assertEqual(type(v), MPVaspInputSet)

        d = self.userparamset.to_dict
        v = dec.process_decoded(d)
        self.assertEqual(type(v), MPVaspInputSet)
        self.assertEqual(v.incar_settings["MAGMOM"], {
            "Fe": 10,
            "S": -5,
            "Mn3+": 100
        })
コード例 #3
0
ファイル: test_vaspio_set.py プロジェクト: bkappes/pymatgen
    def test_to_from_dict(self):
        self.mitparamset = MITVaspInputSet()
        self.mithseparamset = MITHSEVaspInputSet()
        self.paramset = MPVaspInputSet()
        self.userparamset = MPVaspInputSet(
            user_incar_settings={'MAGMOM': {
                "Fe": 10,
                "S": -5,
                "Mn3+": 100
            }})

        d = self.mitparamset.to_dict
        v = dec.process_decoded(d)
        self.assertEqual(v.incar_settings["LDAUU"]["O"]["Fe"], 4)

        d = self.mitggaparam.to_dict
        v = dec.process_decoded(d)
        self.assertNotIn("LDAUU", v.incar_settings)

        d = self.mithseparamset.to_dict
        v = dec.process_decoded(d)
        self.assertEqual(v.incar_settings["LHFCALC"], True)

        d = self.paramset.to_dict
        v = dec.process_decoded(d)
        self.assertEqual(v.incar_settings["LDAUU"]["O"]["Fe"], 5.3)

        d = self.userparamset.to_dict
        v = dec.process_decoded(d)
        #self.assertEqual(type(v), MPVaspInputSet)
        self.assertEqual(v.incar_settings["MAGMOM"], {
            "Fe": 10,
            "S": -5,
            "Mn3+": 100
        })
コード例 #4
0
    def run_task(self, fw_spec):
        chgcar_start = False
        # read the VaspInput from the previous run

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

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

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

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

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

        # write back the new INCAR to the current directory
        incar.write_file('INCAR')
        return FWAction(stored_data={'chgcar_start': chgcar_start})
コード例 #5
0
ファイル: compatibility.py プロジェクト: paulfons/pymatgen
 def __init__(self, compat_type="Advanced", correct_peroxide=True):
     module_dir = os.path.dirname(os.path.abspath(__file__))
     fp = os.path.join(module_dir, "MPCompatibility.yaml")
     i_s = MPVaspInputSet()
     Compatibility.__init__(
         self, [PotcarCorrection(i_s),
                GasCorrection(fp, correct_peroxide=correct_peroxide),
                UCorrection(fp, i_s, compat_type), AqueousCorrection(fp)])
コード例 #6
0
def _snl_to_spec(snl, enforce_gga=False, parameters=None):

    parameters = parameters if parameters else {}
    parameters['boltztrap'] = parameters.get('boltztrap',
                                             True)  # by default run boltztrap
    spec = {'parameters': parameters}

    incar_enforce = {'NPAR': 2}
    if 'exact_structure' in parameters and parameters['exact_structure']:
        structure = snl.structure
    else:
        structure = snl.structure.get_primitive_structure()

    mpvis = MPGGAVaspInputSet(
        user_incar_settings=incar_enforce) if enforce_gga else MPVaspInputSet(
            user_incar_settings=incar_enforce)

    incar = mpvis.get_incar(structure)
    poscar = mpvis.get_poscar(structure)
    kpoints = mpvis.get_kpoints(structure)
    potcar = mpvis.get_potcar(structure)

    spec['vasp'] = {}
    spec['vasp']['incar'] = incar.as_dict()
    spec['vasp']['poscar'] = poscar.as_dict()
    spec['vasp']['kpoints'] = kpoints.as_dict()
    spec['vasp']['potcar'] = potcar.as_dict()

    # Add run tags of pseudopotential
    spec['run_tags'] = spec.get('run_tags', [potcar.functional])
    spec['run_tags'].extend(potcar.symbols)

    # Add run tags of +U
    u_tags = [
        '%s=%s' % t
        for t in zip(poscar.site_symbols,
                     incar.get('LDAUU', [0] * len(poscar.site_symbols)))
    ]
    spec['run_tags'].extend(u_tags)

    # add user run tags
    if 'run_tags' in parameters:
        spec['run_tags'].extend(parameters['run_tags'])
        del spec['parameters']['run_tags']

    # add exact structure run tag automatically if we have a unique situation
    if 'exact_structure' in parameters and parameters[
            'exact_structure'] and snl.structure != snl.structure.get_primitive_structure(
            ):
        spec['run_tags'].extend('exact_structure')

    spec['_dupefinder'] = DupeFinderVasp().to_dict()
    spec['vaspinputset_name'] = mpvis.__class__.__name__
    spec['task_type'] = 'GGA+U optimize structure (2x)' if spec['vasp'][
        'incar'].get('LDAU', False) else 'GGA optimize structure (2x)'

    return spec
コード例 #7
0
ファイル: matgenie.py プロジェクト: bkappes/pymatgen
def convert_fmt(args):
    iformat = args.input_format[0]
    oformat = args.output_format[0]
    filename = args.input_filename[0]
    out_filename = args.output_filename[0]

    try:
        if iformat == "smart":
            structure = read_structure(filename)
        if iformat == "POSCAR":
            p = Poscar.from_file(filename)
            structure = p.structure
        elif iformat == "CIF":
            r = CifParser(filename)
            structure = r.get_structures()[0]
        elif iformat == "CSSR":
            structure = Cssr.from_file(filename).structure

        if oformat == "smart":
            write_structure(structure, out_filename)
        elif oformat == "POSCAR":
            p = Poscar(structure)
            p.write_file(out_filename)
        elif oformat == "CIF":
            w = CifWriter(structure)
            w.write_file(out_filename)
        elif oformat == "CSSR":
            c = Cssr(structure)
            c.write_file(out_filename)
        elif oformat == "VASP":
            input_set = MPVaspInputSet()
            ts = TransformedStructure(structure, [],
                                      history=[{
                                          "source":
                                          "file",
                                          "datetime":
                                          str(datetime.datetime.now()),
                                          "original_file":
                                          open(filename).read()
                                      }])
            ts.write_vasp_input(input_set, output_dir=out_filename)
        elif oformat == "MITVASP":
            input_set = MITVaspInputSet()
            ts = TransformedStructure(structure, [],
                                      history=[{
                                          "source":
                                          "file",
                                          "datetime":
                                          str(datetime.datetime.now()),
                                          "original_file":
                                          open(filename).read()
                                      }])
            ts.write_vasp_input(input_set, output_dir=out_filename)

    except Exception as ex:
        print "Error converting file. Are they in the right format?"
        print str(ex)
コード例 #8
0
    def setUp(self):
        filepath = os.path.join(test_dir, 'POSCAR')
        poscar = Poscar.from_file(filepath)
        self.struct = poscar.structure

        self.mitparamset = MITVaspInputSet()
        self.mithseparamset = MITHSEVaspInputSet()
        self.paramset = MPVaspInputSet()
        self.userparamset = MPVaspInputSet(
            {'MAGMOM': {
                "Fe": 10,
                "S": -5,
                "Mn3+": 100
            }})
        self.mitggaparam = MITGGAVaspInputSet()
        self.mpstaticparamset = MPStaticVaspInputSet()
        self.mpnscfparamsetu = MPNonSCFVaspInputSet({"NBANDS": 50},
                                                    mode="Uniform")
        self.mpnscfparamsetl = MPNonSCFVaspInputSet({"NBANDS": 60},
                                                    mode="Line")
コード例 #9
0
ファイル: compatibility.py プロジェクト: sikisis/pymatgen
    def __init__(self, input_set_name, compat_type):
        """
        Args:
            input_set_name:
                The name of the input set to use. Can be either
                MaterialsProject or MITMatgen.
            compat_type:
                Two options, GGA or Advanced.  GGA means all GGA+U entries are
                excluded.  Advanced means mixing scheme is implemented to make
                entries compatible with each other, but entries which are
                supposed to be done in GGA+U will have the equivalent GGA
                entries excluded. For example, Fe oxides should have a U value
                under the Advanced scheme. A GGA Fe oxide run will therefore be
                excluded under the scheme.
        """
        self.compat_type = compat_type
        self.input_set_name = input_set_name
        if input_set_name == "MaterialsProject":
            self.input_set = MPVaspInputSet()
        elif input_set_name == "MITMatgen":
            self.input_set = MITVaspInputSet()
        else:
            raise ValueError(
                "Invalid input set name {}".format(input_set_name))

        module_dir = os.path.dirname(os.path.abspath(__file__))
        self._config = ConfigParser.SafeConfigParser()
        self._config.optionxform = str
        self._config.readfp(open(os.path.join(module_dir,
                                              "Compatibility.cfg")))
        u_corrections = {}
        for el in self.input_set.incar_settings["LDAUU"].keys():
            name = "{}{}UCorrections{}".format(input_set_name, compat_type, el)
            if name in self._config.sections():
                corr = dict(self._config.items(name))
                u_corrections[el] = {k: float(v) for k, v in corr.items()}

        cpd_energies = dict(
            self._config.items("{}{}CompoundEnergies".format(
                input_set_name, compat_type)))

        self.u_corrections = u_corrections
        self.cpd_energies = {k: float(v) for k, v in cpd_energies.items()}

        self.valid_potcars = set(self.input_set.potcar_settings.values())
        self.u_settings = self.input_set.incar_settings["LDAUU"]

        if compat_type == "GGA":
            self.u_corrections = {}
            self.u_settings = {}
コード例 #10
0
ファイル: test_vaspio_set.py プロジェクト: bkappes/pymatgen
    def test_get_potcar_symbols(self):
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 0.75])
        coords.append([0.75, 0.25, 0.75])
        lattice = Lattice([[3.8401979337, 0.00, 0.00],
                           [1.9200989668, 3.3257101909, 0.00],
                           [0.00, -2.2171384943, 3.1355090603]])
        struct = Structure(lattice, ["P", "Fe", "O"], coords)

        syms = self.paramset.get_potcar_symbols(struct)
        self.assertEquals(syms, ['Fe_pv', 'P', 'O'])

        syms = MPVaspInputSet(sort_structure=False).get_potcar_symbols(struct)
        self.assertEquals(syms, ['P', 'Fe_pv', 'O'])
コード例 #11
0
ファイル: compatibility.py プロジェクト: bkappes/pymatgen
    def __init__(self, name):
        """
        Args:
            name:
                Name of settings to use. Current valid settings are MP or
                MIT, which is the relevant settings based on the MP or MIT
                VaspInputSets.

        Raises:
            ValueError if entry do not contain "potcar_symbols" key.
        """
        if name == "MP":
            input_set = MPVaspInputSet()
        elif name == "MIT":
            input_set = MITVaspInputSet()
        else:
            raise ValueError("Only MIT and MP POTCAR corrections are "
                             "supported currently.")
        self.valid_potcars = set(input_set.potcar_settings.values())
コード例 #12
0
    def run_task(self, fw_spec):
        chgcar_start = False
        # read the VaspInput from the previous run
        vi = VaspInput.from_directory(".")

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

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

        # write back the new INCAR to the current directory
        vi['INCAR'].write_file('INCAR')
        return FWAction(stored_data={'chgcar_start': chgcar_start})
コード例 #13
0
ファイル: VaspUStrategy.py プロジェクト: rousseab/VaspDrive
    def get_LDAU(self):
        """ Produce LDAU related variables, to be passed to VASP as strings """

        # let's simply use the Materials Project results as default.

        self.check_structure_is_read()

        dummy_input_set = MPVaspInputSet()
        dummy_incar  = dummy_input_set.get_incar(self.structure)

        LDAU_dict = {}
        
        for key in self._LDAU_KEYS: 
            if key in dummy_incar:
                LDAU_dict[key] = dummy_incar[key]

        # no need to hack  the poscar or potcar
        poscar_need_hack = False
        potcar_need_hack = False

        return LDAU_dict, poscar_need_hack, potcar_need_hack  
コード例 #14
0
ファイル: compatibility.py プロジェクト: bkappes/pymatgen
    def __init__(self, name, compat_type):
        """
        Args:
            name:
                Name of settings to use. Current valid settings are MP or
                MIT, which is the relevant settings based on the MP or MIT
                VaspInputSets.
            compat_type:
                Two options, GGA or Advanced.  GGA means all GGA+U entries are
                excluded.  Advanced means mixing scheme is implemented to make
                entries compatible with each other, but entries which are
                supposed to be done in GGA+U will have the equivalent GGA
                entries excluded. For example, Fe oxides should have a U value
                under the Advanced scheme. A GGA Fe oxide run will therefore be
                excluded under the scheme.
        """
        module_dir = os.path.dirname(os.path.abspath(__file__))
        config = ConfigParser.SafeConfigParser()
        config.optionxform = str
        config.readfp(open(os.path.join(module_dir, "Compatibility.cfg")))
        if name == "MP":
            self.input_set = MPVaspInputSet()
        elif name == "MIT":
            self.input_set = MITVaspInputSet()
        else:
            raise ValueError("Invalid input set name {}".format(name))

        u_corrections = {}
        for el in self.input_set.incar_settings["LDAUU"].keys():
            sect_name = "{}{}UCorrections{}".format(name, compat_type, el)
            if sect_name in config.sections():
                corr = dict(config.items(sect_name))
                u_corrections[el] = {k: float(v) for k, v in corr.items()}

        self.u_corrections = u_corrections
        self.u_settings = self.input_set.incar_settings["LDAUU"]

        if compat_type == "GGA":
            self.u_corrections = {}
            self.u_settings = {}
コード例 #15
0
ファイル: snl_to_wf.py プロジェクト: miaoliu/MPWorks
def _snl_to_spec(snl, enforce_gga=False):
    spec = {}

    incar_enforce = {'NPAR': 2}
    structure = snl.structure
    mpvis = MPGGAVaspInputSet(
        user_incar_settings=incar_enforce) if enforce_gga else MPVaspInputSet(
            user_incar_settings=incar_enforce)

    incar = mpvis.get_incar(structure)
    poscar = mpvis.get_poscar(structure)
    kpoints = mpvis.get_kpoints(structure)
    potcar = mpvis.get_potcar(structure)

    spec['vasp'] = {}
    spec['vasp']['incar'] = incar.to_dict
    spec['vasp']['poscar'] = poscar.to_dict
    spec['vasp']['kpoints'] = kpoints.to_dict
    spec['vasp']['potcar'] = potcar.to_dict

    # Add run tags of pseudopotential
    spec['run_tags'] = spec.get('run_tags', [potcar.functional])
    spec['run_tags'].extend(potcar.symbols)

    # Add run tags of +U
    u_tags = [
        '%s=%s' % t
        for t in zip(poscar.site_symbols,
                     incar.get('LDAUU', [0] * len(poscar.site_symbols)))
    ]
    spec['run_tags'].extend(u_tags)

    spec['_dupefinder'] = DupeFinderVasp().to_dict()
    spec['vaspinputset_name'] = mpvis.__class__.__name__
    spec['task_type'] = 'GGA+U optimize structure (2x)' if spec['vasp'][
        'incar'].get('LDAU', False) else 'GGA optimize structure (2x)'

    return spec
コード例 #16
0
    def __init__(self, save_old_file=False):

        # read in what is there
        json_filename = 'run_data.json'

        try:
            with open(json_filename, 'r') as f:
                data = json.load(f)
        except:
            print(
                "CANNOT FIND run_data.json: CLASS MUST BE CALLED IN DIRECTORY WHERE FILE IS"
            )
            return

        last_step = data['relaxation'][-1]

        structure = pymatgen.Structure.from_dict(last_step['structure'])
        composition = structure.composition
        energy = last_step['electronic']['e_0_energy']

        set = MPVaspInputSet()
        incar = set.get_incar(structure)
        poscar = set.get_poscar(structure)
        potcar = set.get_potcar(structure)

        parameters = self.parse_pseudo_inputs(poscar, incar, potcar)

        entry = pymatgen.entries.computed_entries.ComputedEntry(
            composition, energy, parameters=parameters)

        data['ComputedEntry'] = entry

        if save_old_file:
            shutil.move('run_data.json', 'run_data_OLD.json')

        pmg_dump(data, 'run_data.json')

        return
コード例 #17
0
ファイル: VaspUStrategy.py プロジェクト: rousseab/VaspDrive
    def get_LDAU(self):
        """ Produce LDAU related variables, to be passed to VASP as strings """

        # let's simply use the Materials Project results as default.

        self.check_structure_is_read()

    
        dummy_input_set = MPVaspInputSet()
        dict = dummy_input_set.as_dict() 
        # Spoof the input set to throw in the values of U we want!
        for symbol, U_value in self.new_U_dict.iteritems():
            dict['config_dict']['INCAR']['LDAUU']['O'][symbol] = U_value

        input_set = pymatgen.io.vaspio_set.DictVaspInputSet.from_dict(dict)

        incar  = input_set.get_incar(self.structure)

        LDAU_dict = {}
        
        for key in self._LDAU_KEYS: 
            if key in incar:
                if key == 'MAGMOM':

                    magn_array = np.array(incar[key])
                    # add randomness to large values, corresponding to TM
                    new_magn_array = np.where(magn_array > 1, magn_array+0.01*np.random.random(len(magn_array)), magn_array)
    
                    LDAU_dict[key] = list(new_magn_array)
                else:
                    LDAU_dict[key] = incar[key]

        # no need to hack  the poscar or potcar
        poscar_need_hack = False
        potcar_need_hack = False

        return LDAU_dict, poscar_need_hack, potcar_need_hack  
コード例 #18
0
ファイル: VaspSubmission.py プロジェクト: rousseab/VaspDrive
def get_MaterialsProject_VASP_inputs(structure, workdir, job_name, nproc=16, supplementary_incar_dict=None):

    if os.path.exists(workdir):
        print 'WORKDIR ALREADY EXISTS. DELETE TO LAUNCH NEW JOB'
        return -1

    os.mkdir(workdir)

    input_set = MPVaspInputSet()
   
    incar  = input_set.get_incar(structure)


    # set the number of parallel processors to sqrt(nproc), 
    # as recommended in manual.
    incar.update({'NPAR':int(np.sqrt(nproc))}) 

    if supplementary_incar_dict != None:
        incar.update(supplementary_incar_dict) 

    poscar = input_set.get_poscar(structure)
    kpoints = input_set.get_kpoints(structure)
    potcar = input_set.get_potcar(structure)

    incar.write_file(workdir+'INCAR')
    poscar.write_file(workdir+'POSCAR', vasp4_compatible = True)
    kpoints.write_file(workdir+'KPOINTS')
    potcar.write_file(workdir+'POTCAR')


    with open(workdir+'job.sh','w') as f:
        f.write(submit_template.format(job_name,nproc))

    with open(workdir+'clean.sh','w') as f:
        f.write(clean_template)

    return 0
コード例 #19
0
 def test_get_vasp_input(self):
     vaspis = MPVaspInputSet()
     self.assertEqual(
         "Na_pv\nO\nP\nFe_pv",
         self.trans.get_vasp_input(vaspis, False)['POTCAR.spec'])
     self.assertEqual(len(self.trans.structures), 2)
コード例 #20
0
def snl_to_wf(snl, parameters=None):
    fws = []
    connections = defaultdict(list)
    parameters = parameters if parameters else {}

    snl_priority = parameters.get('priority', 1)
    priority = snl_priority * 2  # once we start a job, keep going!

    f = Composition(
        snl.structure.composition.reduced_formula).alphabetical_formula

    snl_spec = {}
    if 'snlgroup_id' in parameters:
        if 'mpsnl' in parameters:
            snl_spec['mpsnl'] = parameters['mpsnl']
        elif isinstance(snl, MPStructureNL):
            snl_spec['mpsnl'] = snl.as_dict()
        else:
            raise ValueError("improper use of force SNL")
        snl_spec['snlgroup_id'] = parameters['snlgroup_id']
    else:
        # add the SNL to the SNL DB and figure out duplicate group
        tasks = [AddSNLTask()]
        spec = {
            'task_type': 'Add to SNL database',
            'snl': snl.as_dict(),
            '_queueadapter': QA_DB,
            '_priority': snl_priority
        }
        fws.append(
            Firework(tasks,
                     spec,
                     name=get_slug(f + '--' + spec['task_type']),
                     fw_id=0))
        connections[0] = [1]

    trackers = [
        Tracker('FW_job.out'),
        Tracker('FW_job.error'),
        Tracker('vasp.out'),
        Tracker('OUTCAR'),
        Tracker('OSZICAR'),
        Tracker('OUTCAR.relax1'),
        Tracker('OUTCAR.relax2')
    ]
    trackers_db = [Tracker('FW_job.out'), Tracker('FW_job.error')]
    # run GGA structure optimization
    spec = _snl_to_spec(snl, enforce_gga=True, parameters=parameters)
    spec.update(snl_spec)
    spec['_priority'] = priority
    spec['_queueadapter'] = QA_VASP
    spec['_trackers'] = trackers
    tasks = [VaspWriterTask(), get_custodian_task(spec)]
    fws.append(
        Firework(tasks,
                 spec,
                 name=get_slug(f + '--' + spec['task_type']),
                 fw_id=1))

    # insert into DB - GGA structure optimization
    spec = {
        'task_type': 'VASP db insertion',
        '_priority': priority * 2,
        '_allow_fizzled_parents': True,
        '_queueadapter': QA_DB,
        "_dupefinder": DupeFinderDB().to_dict(),
        '_trackers': trackers_db
    }
    fws.append(
        Firework([VaspToDBTask()],
                 spec,
                 name=get_slug(f + '--' + spec['task_type']),
                 fw_id=2))
    connections[1] = [2]

    # determine if GGA+U FW is needed
    incar = MPVaspInputSet().get_incar(snl.structure).as_dict()
    ggau_compound = ('LDAU' in incar and incar['LDAU'])

    if not parameters.get('skip_bandstructure', False) and (
            not ggau_compound
            or parameters.get('force_gga_bandstructure', False)):
        spec = {
            'task_type': 'Controller: add Electronic Structure v2',
            '_priority': priority,
            '_queueadapter': QA_CONTROL
        }
        fws.append(
            Firework([AddEStructureTask()],
                     spec,
                     name=get_slug(f + '--' + spec['task_type']),
                     fw_id=3))
        connections[2] = [3]

    if ggau_compound:
        spec = _snl_to_spec(snl, enforce_gga=False, parameters=parameters)
        del spec[
            'vasp']  # we are stealing all VASP params and such from previous run
        spec['_priority'] = priority
        spec['_queueadapter'] = QA_VASP
        spec['_trackers'] = trackers
        fws.append(
            Firework(
                [VaspCopyTask(),
                 SetupGGAUTask(),
                 get_custodian_task(spec)],
                spec,
                name=get_slug(f + '--' + spec['task_type']),
                fw_id=10))
        connections[2].append(10)

        spec = {
            'task_type': 'VASP db insertion',
            '_queueadapter': QA_DB,
            '_allow_fizzled_parents': True,
            '_priority': priority,
            "_dupefinder": DupeFinderDB().to_dict(),
            '_trackers': trackers_db
        }
        fws.append(
            Firework([VaspToDBTask()],
                     spec,
                     name=get_slug(f + '--' + spec['task_type']),
                     fw_id=11))
        connections[10] = [11]

        if not parameters.get('skip_bandstructure', False):
            spec = {
                'task_type': 'Controller: add Electronic Structure v2',
                '_priority': priority,
                '_queueadapter': QA_CONTROL
            }
            fws.append(
                Firework([AddEStructureTask()],
                         spec,
                         name=get_slug(f + '--' + spec['task_type']),
                         fw_id=12))
            connections[11] = [12]

    wf_meta = get_meta_from_structure(snl.structure)
    wf_meta['run_version'] = 'May 2013 (1)'

    if '_materialsproject' in snl.data and 'submission_id' in snl.data[
            '_materialsproject']:
        wf_meta['submission_id'] = snl.data['_materialsproject'][
            'submission_id']
    return Workflow(
        fws,
        connections,
        name=Composition(
            snl.structure.composition.reduced_formula).alphabetical_formula,
        metadata=wf_meta)
コード例 #21
0
ファイル: VaspSubmission.py プロジェクト: rousseab/VaspDrive
def get_ModifiedMaterialsProject_VASP_inputs(structure, workdir, job_name, nproc=16, 
                                U_strategy_instance = None, supplementary_incar_dict = None):
    """
    Inputs will be inspired by MaterialsProject, but this function is appropriate
    when we are seriously modifying the inputs such that they no longer conform to Materials Project.
    """

    if os.path.exists(workdir):
        print 'WORKDIR ALREADY EXISTS. DELETE TO LAUNCH NEW JOB'
        return -1

    os.mkdir(workdir)

    # let's start with MP
    input_set = MPVaspInputSet()
   
    incar  = input_set.get_incar(structure)

    if U_strategy_instance != None:
        #  reading the structure here insures consistency, rather
        #  than having the strategy read the structure outside this driver.
        U_strategy_instance.read_structure(structure)

        # Generate all LDAU-related variables according to specified strategy.
        LDAU_dict, poscar_need_hack, potcar_need_hack = U_strategy_instance.get_LDAU()

        incar.update(LDAU_dict) 

    # set the number of parallel processors to sqrt(nproc), 
    # as recommended in manual.
    incar.update({'NPAR':int(np.sqrt(nproc))}) 

    if supplementary_incar_dict != None:
        incar.update(supplementary_incar_dict) 

    poscar = input_set.get_poscar(structure)

    kpoints = input_set.get_kpoints(structure)
    potcar = input_set.get_potcar(structure)

    incar.write_file(workdir+'INCAR')
    poscar.write_file(workdir+'POSCAR', vasp4_compatible = True)
    kpoints.write_file(workdir+'KPOINTS')
    potcar.write_file(workdir+'POTCAR')


    if poscar_need_hack:
        # do we need specialized hacking of the poscar because of the U strategy?       
        new_poscar_lines = U_strategy_instance.get_new_poscar_lines()
        with open(workdir+'POSCAR','w') as f:
            for line in new_poscar_lines:
                print >>f, line.strip()

    if potcar_need_hack:
        # do we need specialized hacking of the potcar because of the U strategy?       
        new_potcar_symbols = U_strategy_instance.get_new_potcar_symbols(potcar)
        new_potcar = Potcar(new_potcar_symbols) 
        # overwrite the previous potcar
        new_potcar.write_file(workdir+'POTCAR')

    with open(workdir+'job.sh','w') as f:
        f.write(submit_template.format(job_name,nproc))

    with open(workdir+'clean.sh','w') as f:
        f.write(clean_template)

    return 0
コード例 #22
0
ファイル: snl_to_wf.py プロジェクト: miaoliu/MPWorks
def snl_to_wf(snl, parameters=None):
    fws = []
    connections = {}
    parameters = parameters if parameters else {}

    snl_priority = parameters.get('priority', 1)
    priority = snl_priority * 2  # once we start a job, keep going!

    f = Composition.from_formula(
        snl.structure.composition.reduced_formula).alphabetical_formula

    # add the SNL to the SNL DB and figure out duplicate group
    tasks = [AddSNLTask()]
    spec = {
        'task_type': 'Add to SNL database',
        'snl': snl.to_dict,
        '_queueadapter': QA_DB,
        '_priority': snl_priority
    }
    if 'snlgroup_id' in parameters and isinstance(snl, MPStructureNL):
        spec['force_mpsnl'] = snl.to_dict
        spec['force_snlgroup_id'] = parameters['snlgroup_id']
        del spec['snl']
    fws.append(
        FireWork(tasks,
                 spec,
                 name=get_slug(f + '--' + spec['task_type']),
                 fw_id=0))
    connections[0] = [1]

    # run GGA structure optimization
    spec = _snl_to_spec(snl, enforce_gga=True)
    spec['_priority'] = priority
    spec['_queueadapter'] = QA_VASP
    tasks = [VaspWriterTask(), get_custodian_task(spec)]
    fws.append(
        FireWork(tasks,
                 spec,
                 name=get_slug(f + '--' + spec['task_type']),
                 fw_id=1))

    # insert into DB - GGA structure optimization
    spec = {
        'task_type': 'VASP db insertion',
        '_priority': priority,
        '_allow_fizzled_parents': True,
        '_queueadapter': QA_DB
    }
    fws.append(
        FireWork([VaspToDBTask()],
                 spec,
                 name=get_slug(f + '--' + spec['task_type']),
                 fw_id=2))
    connections[1] = [2]

    if not parameters.get('skip_bandstructure', False):
        spec = {
            'task_type': 'Controller: add Electronic Structure v2',
            '_priority': priority,
            '_queueadapter': QA_CONTROL
        }
        fws.append(
            FireWork([AddEStructureTask()],
                     spec,
                     name=get_slug(f + '--' + spec['task_type']),
                     fw_id=3))
        connections[2] = [3]

    # determine if GGA+U FW is needed
    incar = MPVaspInputSet().get_incar(snl.structure).to_dict

    if 'LDAU' in incar and incar['LDAU']:
        spec = _snl_to_spec(snl, enforce_gga=False)
        del spec[
            'vasp']  # we are stealing all VASP params and such from previous run
        spec['_priority'] = priority
        spec['_queueadapter'] = QA_VASP
        fws.append(
            FireWork(
                [VaspCopyTask(),
                 SetupGGAUTask(),
                 get_custodian_task(spec)],
                spec,
                name=get_slug(f + '--' + spec['task_type']),
                fw_id=10))
        connections[2].append(10)

        spec = {
            'task_type': 'VASP db insertion',
            '_queueadapter': QA_DB,
            '_allow_fizzled_parents': True,
            '_priority': priority
        }
        fws.append(
            FireWork([VaspToDBTask()],
                     spec,
                     name=get_slug(f + '--' + spec['task_type']),
                     fw_id=11))
        connections[10] = [11]

        if not parameters.get('skip_bandstructure', False):
            spec = {
                'task_type': 'Controller: add Electronic Structure v2',
                '_priority': priority,
                '_queueadapter': QA_CONTROL
            }
            fws.append(
                FireWork([AddEStructureTask()],
                         spec,
                         name=get_slug(f + '--' + spec['task_type']),
                         fw_id=12))
            connections[11] = [12]

    wf_meta = get_meta_from_structure(snl.structure)
    wf_meta['run_version'] = 'May 2013 (1)'

    if '_materialsproject' in snl.data and 'submission_id' in snl.data[
            '_materialsproject']:
        wf_meta['submission_id'] = snl.data['_materialsproject'][
            'submission_id']
    return Workflow(
        fws,
        connections,
        name=Composition.from_formula(
            snl.structure.composition.reduced_formula).alphabetical_formula,
        metadata=wf_meta)
コード例 #23
0
def main(api="", queryid=""):
    """Get VASP inputs for Materials Project structure
        Args:
            api <str>: Materials Project API key
            queryid <str>: Materials Project ID of the structure
        Returns:
            creates a folder named with that mpid, and including
            some VASP input files.
    """
    if api == "":
        print "Must have an API key from materialsproject.org"
        return None
    if queryid == "":
        print "No MP structure ID given. Exiting."
        return None
    rest_adapter = MPRester(api)
    entries = list()
    proplist = list()
    proplist.append('pretty_formula')
    proplist.append('structure')
    proplist.append('potcar')
    proplist.append('material_id')

    myentry = rest_adapter.mpquery(criteria={'material_id': queryid},
                                   properties=proplist)
    if len(myentry) == 0:
        print "Could not find entry for %s as material_id. Trying entry_id." % queryid
        myentry = rest_adapter.mpquery(criteria={'entry_id': queryid},
                                       properties=proplist)
    if len(myentry) == 0:
        print "Could not find entry for %s" % queryid
        return None
    entries.extend(myentry)

    workdir = os.getcwd()
    from pymatgen.io.vaspio_set import MITVaspInputSet, MPVaspInputSet
    for entry in entries:
        mpvis = MPVaspInputSet()
        myname = str(entry['pretty_formula'])
        #print entry['structure'].composition
        #print entry['structure'].formula
        #myname = entry['pretty_formula']
        myname = myname.replace("(", "_").replace(")", "_")
        myname = myname + "_" + entry['material_id']
        os.mkdir(myname)
        os.chdir(myname)
        mystructure = entry['structure']
        if mystructure.num_sites <= 10:
            mystructure.make_supercell([2, 2, 2])
        #mystructure.perturb(0.01)
        incar = mpvis.get_incar(mystructure)
        incar.write_file("INCAR")
        potcar = mpvis.get_potcar(mystructure)
        potcar.write_file("POTCAR")
        #potcar_symbols = mpvis.get_potcar_symbols(mystructure)
        myposcar = Poscar(mystructure)
        mykpoints = mpvis.get_kpoints(mystructure)
        mykpoints.write_file("KPOINTS")

        myposcar.write_file("POSCAR")
        os.chdir(workdir)