Esempio n. 1
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)
    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})
Esempio n. 3
0
    def run_task(self, fw_spec):
        chgcar_start = False
        # read the VaspInput from the previous run

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

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

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

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

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

        # write back the new INCAR to the current directory
        incar.write_file('INCAR')
        return FWAction(stored_data={'chgcar_start': chgcar_start})
Esempio n. 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})
Esempio n. 5
0
    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
        })
Esempio n. 6
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()
Esempio n. 7
0
    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.mphseparamset.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})
Esempio n. 8
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
        })
Esempio n. 9
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
Esempio n. 10
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")
Esempio n. 11
0
 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)])
Esempio n. 12
0
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)
Esempio n. 13
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")
Esempio n. 14
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
Esempio n. 15
0
    def run_task(self, fw_spec):
        chgcar_start = False

        vi = VaspInput.from_directory(".")  # read the VaspInput from the previous run

        # figure out what GGA+U values to use and override them
        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}  # LDAU values to use
        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

        vi['INCAR'].write_file('INCAR')  # write back the new INCAR to the current directory

        return FWAction(stored_data={'chgcar_start': chgcar_start})
Esempio n. 16
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})
Esempio n. 17
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")
Esempio n. 18
0
    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  
Esempio n. 19
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
Esempio n. 20
0
    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 = {}
Esempio n. 21
0
    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  
Esempio n. 22
0
    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'])
Esempio n. 23
0
    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())
Esempio n. 24
0
    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 = {}
Esempio n. 25
0
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
Esempio n. 26
0
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
Esempio n. 27
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)
Esempio n. 28
0
# print os.environ['VASP_PSP_DIR']

id_expgap = open("ids.txt", "r")
for line in id_expgap:
    words=line.split()
    print words
    id_line=words[0]
    os.mkdir(id_line)
    os.chdir(id_line)
    s = mpr.get_structure_by_material_id(id_line)
    # obtain structural information from Materials Project database
    #print json.dumps(s.to_dict)
    # convert structural infomation into a dictionary and then dump to a json file

    user_incar_settings={"ALGO":'Normal',"EDIFF":1E-8,"ENCUT":500,"NSW":0,"LWAVE":True}
    mpvis = MPVaspInputSet(user_incar_settings=user_incar_settings)

    mpvis.get_incar(s).write_file('INCAR')
    # from the GW input set, get the incar parameters, generate INCAR
    print mpvis.get_incar(s)
    #
    kp_density = mpvis.get_kpoints(s).kpts[0]
    # from the GW input set, get the k-point density
    kpoints = Kpoints.gamma_automatic(kp_density)
    # generate Gamma centered k-point mesh
    kpoints.write_file('KPOINTS')
    # generate KPOINTS file
    mpvis.get_poscar(s).write_file('POSCAR')
    # generate POSCAR file
    mpvis.get_potcar(s).write_file('POTCAR')
    # generate POTCAR file
Esempio n. 29
0
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)
Esempio n. 30
0
class MITMPVaspInputSetTest(unittest.TestCase):
    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")

    def test_get_poscar(self):
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 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, ["Fe", "Mn"], coords)

        s_unsorted = self.mitparamset_unsorted.get_poscar(struct).structure
        s_sorted = self.mitparamset.get_poscar(struct).structure

        self.assertEqual(s_unsorted[0].specie.symbol, 'Fe')
        self.assertEqual(s_sorted[0].specie.symbol, 'Mn')

    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'])

    def test_get_incar(self):
        incar = self.paramset.get_incar(self.struct)

        self.assertEqual(incar['LDAUU'], [5.3, 0, 0])
        self.assertAlmostEqual(incar['EDIFF'], 0.0012)

        incar = self.mitparamset.get_incar(self.struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0, 0])
        self.assertAlmostEqual(incar['EDIFF'], 0.0012)

        incar_gga = self.mitggaparam.get_incar(self.struct)
        self.assertNotIn("LDAU", incar_gga)

        incar_static = self.mpstaticparamset.get_incar(self.struct)
        self.assertEqual(incar_static["NSW"], 0)

        incar_nscfl = self.mpnscfparamsetl.get_incar(self.struct)
        self.assertEqual(incar_nscfl["NBANDS"], 60)

        incar_nscfu = self.mpnscfparamsetu.get_incar(self.struct)
        self.assertEqual(incar_nscfu["ISYM"], 0)

        si = 14
        coords = list()
        coords.append(array([0, 0, 0]))
        coords.append(array([0.75, 0.5, 0.75]))

        #Silicon structure for testing.
        latt = Lattice(
            array([[3.8401979337, 0.00, 0.00],
                   [1.9200989668, 3.3257101909, 0.00],
                   [0.00, -2.2171384943, 3.1355090603]]))
        struct = Structure(latt, [si, si], coords)
        incar = self.paramset.get_incar(struct)
        self.assertNotIn("LDAU", incar)

        incar = self.mithseparamset.get_incar(self.struct)
        self.assertTrue(incar['LHFCALC'])

        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 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, ["Fe", "Mn"], coords)

        incar = self.paramset.get_incar(struct)
        self.assertNotIn('LDAU', incar)

        #check fluorides
        struct = Structure(lattice, ["Fe", "F"], coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [5.3, 0])
        self.assertEqual(incar['MAGMOM'], [5, 0.6])

        struct = Structure(lattice, ["Fe", "F"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0])

        #Make sure this works with species.
        struct = Structure(lattice, ["Fe2+", "O2-"], coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [5.3, 0])

        struct = Structure(lattice, ["Fe", "Mn"],
                           coords,
                           site_properties={'magmom': (5.2, -4.5)})
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [-4.5, 5.2])
        incar = self.mpstaticparamset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [-4.5, 5.2])
        incar = self.mitparamset_unsorted.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [5.2, -4.5])

        struct = Structure(lattice, [Specie("Fe", 2, {'spin': 4.1}), "Mn"],
                           coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [5, 4.1])
        incar = self.mpnscfparamsetl.get_incar(struct)
        self.assertEqual(incar.get('MAGMOM', None), None)

        struct = Structure(lattice, ["Mn3+", "Mn4+"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [4, 3])
        incar = self.mpnscfparamsetu.get_incar(struct)
        self.assertEqual(incar.get('MAGMOM', None), None)

        self.assertEqual(
            self.userparamset.get_incar(struct)['MAGMOM'], [100, 0.6])

        #sulfide vs sulfate test

        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 0.75])
        coords.append([0.25, 0.5, 0])

        struct = Structure(lattice, ["Fe", "Fe", "S"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [1.9, 0])

        #Make sure Matproject sulfides are ok.
        self.assertNotIn('LDAUU', self.paramset.get_incar(struct))
        self.assertNotIn('LDAUU', self.mpstaticparamset.get_incar(struct))

        struct = Structure(lattice, ["Fe", "S", "O"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0, 0])

        #Make sure Matproject sulfates are ok.
        self.assertEqual(self.paramset.get_incar(struct)['LDAUU'], [5.3, 0, 0])
        self.assertEqual(
            self.mpnscfparamsetl.get_incar(struct)['LDAUU'], [5.3, 0, 0])

        self.assertEqual(
            self.userparamset.get_incar(struct)['MAGMOM'], [10, -5, 0.6])

    def test_get_kpoints(self):
        kpoints = self.paramset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[2, 4, 6]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mitparamset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[2, 4, 6]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mpstaticparamset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[4, 6, 6]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mpnscfparamsetl.get_kpoints(self.struct)
        self.assertEquals(kpoints.num_kpts, 140)
        self.assertEquals(kpoints.style, 'Reciprocal')

        kpoints = self.mpnscfparamsetu.get_kpoints(self.struct)
        self.assertEquals(kpoints.num_kpts, 168)

    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
        })
Esempio n. 31
0
class MITMPVaspInputSetTest(unittest.TestCase):

    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()

    def test_get_poscar(self):
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 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, ["Fe", "Mn"], coords)
        
        s_unsorted = self.mitparamset_unsorted.get_poscar(struct).structure
        s_sorted = self.mitparamset.get_poscar(struct).structure
        
        self.assertEqual(s_unsorted[0].specie.symbol, 'Fe')
        self.assertEqual(s_sorted[0].specie.symbol, 'Mn')

    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'])

    def test_lda_potcar(self):
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 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"], coords)
        p = MITVaspInputSet(potcar_functional="LDA").get_potcar(struct)
        self.assertEqual(p.functional, 'LDA')

    def test_get_nelect(self):
        coords = [[0]*3, [0.5]*3, [0.75]*3]
        lattice = Lattice.cubic(4)
        s = Structure(lattice, ['Si', 'Si', 'Fe'], coords)
        self.assertAlmostEqual(MITVaspInputSet().get_nelect(s), 16)

    def test_get_incar(self):
        incar = self.paramset.get_incar(self.struct)

        self.assertEqual(incar['LDAUU'], [5.3, 0, 0])
        self.assertAlmostEqual(incar['EDIFF'], 0.0012)

        incar = self.mitparamset.get_incar(self.struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0, 0])
        self.assertAlmostEqual(incar['EDIFF'], 0.0012)

        incar_gga = self.mitggaparam.get_incar(self.struct)
        self.assertNotIn("LDAU", incar_gga)

        incar_static = self.mpstaticparamset.get_incar(self.struct)
        self.assertEqual(incar_static["NSW"], 0)

        incar_nscfl = self.mpnscfparamsetl.get_incar(self.struct)
        self.assertEqual(incar_nscfl["NBANDS"], 60)

        incar_nscfu = self.mpnscfparamsetu.get_incar(self.struct)
        self.assertEqual(incar_nscfu["ISYM"], 0)

        incar_hse = self.mphseparamset.get_incar(self.struct)
        self.assertEqual(incar_hse['LHFCALC'], True)
        self.assertEqual(incar_hse['HFSCREEN'], 0.2)

        incar_hse_bsl = self.mpbshseparamsetl.get_incar(self.struct)
        self.assertEqual(incar_hse_bsl['LHFCALC'], True)
        self.assertEqual(incar_hse_bsl['HFSCREEN'], 0.2)
        self.assertEqual(incar_hse_bsl['NSW'], 0)

        incar_hse_bsu = self.mpbshseparamsetu.get_incar(self.struct)
        self.assertEqual(incar_hse_bsu['LHFCALC'], True)
        self.assertEqual(incar_hse_bsu['HFSCREEN'], 0.2)
        self.assertEqual(incar_hse_bsu['NSW'], 0)

        incar_diel = self.mpdielparamset.get_incar(self.struct)
        self.assertEqual(incar_diel['IBRION'], 8)
        self.assertEqual(incar_diel['LEPSILON'], True)

        si = 14
        coords = list()
        coords.append(np.array([0, 0, 0]))
        coords.append(np.array([0.75, 0.5, 0.75]))

        #Silicon structure for testing.
        latt = Lattice(np.array([[3.8401979337, 0.00, 0.00],
                              [1.9200989668, 3.3257101909, 0.00],
                              [0.00, -2.2171384943, 3.1355090603]]))
        struct = Structure(latt, [si, si], coords)
        incar = self.paramset.get_incar(struct)
        self.assertNotIn("LDAU", incar)

        incar = self.mithseparamset.get_incar(self.struct)
        self.assertTrue(incar['LHFCALC'])

        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 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, ["Fe", "Mn"], coords)

        incar = self.paramset.get_incar(struct)
        self.assertNotIn('LDAU', incar)

        #check fluorides
        struct = Structure(lattice, ["Fe", "F"], coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [5.3, 0])
        self.assertEqual(incar['MAGMOM'], [5, 0.6])

        struct = Structure(lattice, ["Fe", "F"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0])

        #Make sure this works with species.
        struct = Structure(lattice, ["Fe2+", "O2-"], coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [5.3, 0])

        struct = Structure(lattice, ["Fe", "Mn"], coords,
                           site_properties={'magmom': (5.2, -4.5)})
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [-4.5, 5.2])
        incar = self.mpstaticparamset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [-4.5, 5.2])
        incar = self.mitparamset_unsorted.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [5.2, -4.5])

        struct = Structure(lattice, [Specie("Fe", 2, {'spin': 4.1}), "Mn"],
                           coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [5, 4.1])
        incar = self.mpnscfparamsetl.get_incar(struct)
        self.assertEqual(incar.get('MAGMOM', None), None)

        struct = Structure(lattice, ["Mn3+", "Mn4+"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [4, 3])
        incar = self.mpnscfparamsetu.get_incar(struct)
        self.assertEqual(incar.get('MAGMOM', None), None)

        self.assertEqual(self.userparamset.get_incar(struct)['MAGMOM'],
                         [100, 0.6])

        #sulfide vs sulfate test

        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 0.75])
        coords.append([0.25, 0.5, 0])

        struct = Structure(lattice, ["Fe", "Fe", "S"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [1.9, 0])

        #Make sure Matproject sulfides are ok.
        self.assertNotIn('LDAUU', self.paramset.get_incar(struct))
        self.assertNotIn('LDAUU', self.mpstaticparamset.get_incar(struct))

        struct = Structure(lattice, ["Fe", "S", "O"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0, 0])

        #Make sure Matproject sulfates are ok.
        self.assertEqual(self.paramset.get_incar(struct)['LDAUU'], [5.3, 0, 0])
        self.assertEqual(self.mpnscfparamsetl.get_incar(struct)['LDAUU'],
                         [5.3, 0, 0])

        self.assertEqual(self.userparamset.get_incar(struct)['MAGMOM'],
                         [10, -5, 0.6])

    def test_optics(self):
        if "VASP_PSP_DIR" not in os.environ:
            os.environ["VASP_PSP_DIR"] = test_dir
        self.mpopticsparamset = MPOpticsNonSCFVaspInputSet.from_previous_vasp_run(
            '{}/static_silicon'.format(test_dir), output_dir='optics_test_dir',
            nedos=1145)
        self.assertTrue(os.path.exists('optics_test_dir/CHGCAR'))
        incar = Incar.from_file('optics_test_dir/INCAR')
        self.assertTrue(incar['LOPTICS'])
        self.assertEqual(incar['NEDOS'], 1145)

        #Remove the directory in which the inputs have been created
        shutil.rmtree('optics_test_dir')

    def test_get_kpoints(self):
        kpoints = self.paramset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[4, 4, 6]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mitparamset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[4, 4, 6]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mpstaticparamset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[6, 6, 4]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mpnscfparamsetl.get_kpoints(self.struct)
        self.assertEquals(kpoints.num_kpts, 140)
        self.assertEquals(kpoints.style, 'Reciprocal')

        kpoints = self.mpnscfparamsetu.get_kpoints(self.struct)
        self.assertEquals(kpoints.num_kpts, 240)

        kpoints = self.mpbshseparamsetl.get_kpoints(self.struct)
        self.assertAlmostEquals(kpoints.num_kpts, 176)
        self.assertAlmostEqual(kpoints.kpts[10][0], 0.25)
        self.assertAlmostEqual(kpoints.kpts[10][1], 0.0)
        self.assertAlmostEqual(kpoints.kpts[10][2], 0.16666667)
        self.assertAlmostEqual(kpoints.kpts[-1][0], 0.66006924)
        self.assertAlmostEqual(kpoints.kpts[-1][1], 0.51780182)
        self.assertAlmostEqual(kpoints.kpts[-1][2], 0.30173482)

        kpoints = self.mpbshseparamsetu.get_kpoints(self.struct)
        self.assertAlmostEquals(kpoints.num_kpts, 37)
        self.assertAlmostEqual(kpoints.kpts[10][0], 0.25)
        self.assertAlmostEqual(kpoints.kpts[10][1], 0.0)
        self.assertAlmostEqual(kpoints.kpts[10][2], 0.16666667)
        self.assertAlmostEqual(kpoints.kpts[-1][0], 0.5)
        self.assertAlmostEqual(kpoints.kpts[-1][1], 0.5)
        self.assertAlmostEqual(kpoints.kpts[-1][2], 0.0)

    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.mphseparamset.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})
Esempio n. 32
0
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
Esempio n. 33
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)
Esempio n. 34
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)
Esempio n. 35
0
class MITMPVaspInputSetTest(unittest.TestCase):

    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")
        
    def test_get_poscar(self):
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 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, ["Fe", "Mn"], coords)
        
        s_unsorted = self.mitparamset_unsorted.get_poscar(struct).structure
        s_sorted = self.mitparamset.get_poscar(struct).structure
        
        self.assertEqual(s_unsorted[0].specie.symbol, 'Fe')
        self.assertEqual(s_sorted[0].specie.symbol, 'Mn')
        

    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'])
        

    def test_get_incar(self):
        incar = self.paramset.get_incar(self.struct)

        self.assertEqual(incar['LDAUU'], [5.3, 0, 0])
        self.assertAlmostEqual(incar['EDIFF'], 0.0012)

        incar = self.mitparamset.get_incar(self.struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0, 0])
        self.assertAlmostEqual(incar['EDIFF'], 0.0012)

        incar_gga = self.mitggaparam.get_incar(self.struct)
        self.assertNotIn("LDAU", incar_gga)

        incar_static = self.mpstaticparamset.get_incar(self.struct)
        self.assertEqual(incar_static["NSW"], 0)

        incar_nscfl = self.mpnscfparamsetl.get_incar(self.struct)
        self.assertEqual(incar_nscfl["NBANDS"], 60)

        incar_nscfu = self.mpnscfparamsetu.get_incar(self.struct)
        self.assertEqual(incar_nscfu["ISYM"], 0)

        si = 14
        coords = list()
        coords.append(array([0, 0, 0]))
        coords.append(array([0.75, 0.5, 0.75]))

        #Silicon structure for testing.
        latt = Lattice(array([[3.8401979337, 0.00, 0.00],
                              [1.9200989668, 3.3257101909, 0.00],
                              [0.00, -2.2171384943, 3.1355090603]]))
        struct = Structure(latt, [si, si], coords)
        incar = self.paramset.get_incar(struct)
        self.assertNotIn("LDAU", incar)

        incar = self.mithseparamset.get_incar(self.struct)
        self.assertTrue(incar['LHFCALC'])

        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 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, ["Fe", "Mn"], coords)

        incar = self.paramset.get_incar(struct)
        self.assertNotIn('LDAU', incar)

        #check fluorides
        struct = Structure(lattice, ["Fe", "F"], coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [5.3, 0])
        self.assertEqual(incar['MAGMOM'], [5, 0.6])

        struct = Structure(lattice, ["Fe", "F"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0])

        #Make sure this works with species.
        struct = Structure(lattice, ["Fe2+", "O2-"], coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [5.3, 0])

        struct = Structure(lattice, ["Fe", "Mn"], coords,
                           site_properties={'magmom': (5.2, -4.5)})
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [-4.5, 5.2])
        incar = self.mpstaticparamset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [-4.5, 5.2])
        incar = self.mitparamset_unsorted.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [5.2, -4.5])

        struct = Structure(lattice, [Specie("Fe", 2, {'spin': 4.1}), "Mn"],
                           coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [5, 4.1])
        incar = self.mpnscfparamsetl.get_incar(struct)
        self.assertEqual(incar.get('MAGMOM', None), None)

        struct = Structure(lattice, ["Mn3+", "Mn4+"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [4, 3])
        incar = self.mpnscfparamsetu.get_incar(struct)
        self.assertEqual(incar.get('MAGMOM', None), None)

        self.assertEqual(self.userparamset.get_incar(struct)['MAGMOM'],
                         [100, 0.6])

        #sulfide vs sulfate test

        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 0.75])
        coords.append([0.25, 0.5, 0])

        struct = Structure(lattice, ["Fe", "Fe", "S"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [1.9, 0])

        #Make sure Matproject sulfides are ok.
        self.assertNotIn('LDAUU', self.paramset.get_incar(struct))
        self.assertNotIn('LDAUU', self.mpstaticparamset.get_incar(struct))

        struct = Structure(lattice, ["Fe", "S", "O"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0, 0])

        #Make sure Matproject sulfates are ok.
        self.assertEqual(self.paramset.get_incar(struct)['LDAUU'], [5.3, 0, 0])
        self.assertEqual(self.mpnscfparamsetl.get_incar(struct)['LDAUU'],
                         [5.3, 0, 0])

        self.assertEqual(self.userparamset.get_incar(struct)['MAGMOM'],
                         [10, -5, 0.6])

    def test_get_kpoints(self):
        kpoints = self.paramset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[2, 4, 6]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mitparamset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[2, 4, 6]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mpstaticparamset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[4, 6, 6]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mpnscfparamsetl.get_kpoints(self.struct)
        self.assertEquals(kpoints.num_kpts, 140)
        self.assertEquals(kpoints.style, 'Reciprocal')

        kpoints = self.mpnscfparamsetu.get_kpoints(self.struct)
        self.assertEquals(kpoints.num_kpts, 168)

    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})
Esempio n. 36
0
class MITMPVaspInputSetTest(unittest.TestCase):
    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()

    def test_get_poscar(self):
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 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, ["Fe", "Mn"], coords)

        s_unsorted = self.mitparamset_unsorted.get_poscar(struct).structure
        s_sorted = self.mitparamset.get_poscar(struct).structure

        self.assertEqual(s_unsorted[0].specie.symbol, 'Fe')
        self.assertEqual(s_sorted[0].specie.symbol, 'Mn')

    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'])

    def test_lda_potcar(self):
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 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"], coords)
        p = MITVaspInputSet(potcar_functional="LDA").get_potcar(struct)
        self.assertEqual(p.functional, 'LDA')

    def test_get_nelect(self):
        coords = [[0] * 3, [0.5] * 3, [0.75] * 3]
        lattice = Lattice.cubic(4)
        s = Structure(lattice, ['Si', 'Si', 'Fe'], coords)
        self.assertAlmostEqual(MITVaspInputSet().get_nelect(s), 16)

    def test_get_incar(self):
        incar = self.paramset.get_incar(self.struct)

        self.assertEqual(incar['LDAUU'], [5.3, 0, 0])
        self.assertAlmostEqual(incar['EDIFF'], 0.0012)

        incar = self.mitparamset.get_incar(self.struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0, 0])
        self.assertAlmostEqual(incar['EDIFF'], 0.0012)

        incar_gga = self.mitggaparam.get_incar(self.struct)
        self.assertNotIn("LDAU", incar_gga)

        incar_static = self.mpstaticparamset.get_incar(self.struct)
        self.assertEqual(incar_static["NSW"], 0)

        incar_nscfl = self.mpnscfparamsetl.get_incar(self.struct)
        self.assertEqual(incar_nscfl["NBANDS"], 60)

        incar_nscfu = self.mpnscfparamsetu.get_incar(self.struct)
        self.assertEqual(incar_nscfu["ISYM"], 0)

        incar_hse = self.mphseparamset.get_incar(self.struct)
        self.assertEqual(incar_hse['LHFCALC'], True)
        self.assertEqual(incar_hse['HFSCREEN'], 0.2)

        incar_hse_bsl = self.mpbshseparamsetl.get_incar(self.struct)
        self.assertEqual(incar_hse_bsl['LHFCALC'], True)
        self.assertEqual(incar_hse_bsl['HFSCREEN'], 0.2)
        self.assertEqual(incar_hse_bsl['NSW'], 0)

        incar_hse_bsu = self.mpbshseparamsetu.get_incar(self.struct)
        self.assertEqual(incar_hse_bsu['LHFCALC'], True)
        self.assertEqual(incar_hse_bsu['HFSCREEN'], 0.2)
        self.assertEqual(incar_hse_bsu['NSW'], 0)

        incar_diel = self.mpdielparamset.get_incar(self.struct)
        self.assertEqual(incar_diel['IBRION'], 8)
        self.assertEqual(incar_diel['LEPSILON'], True)

        si = 14
        coords = list()
        coords.append(np.array([0, 0, 0]))
        coords.append(np.array([0.75, 0.5, 0.75]))

        #Silicon structure for testing.
        latt = Lattice(
            np.array([[3.8401979337, 0.00, 0.00],
                      [1.9200989668, 3.3257101909, 0.00],
                      [0.00, -2.2171384943, 3.1355090603]]))
        struct = Structure(latt, [si, si], coords)
        incar = self.paramset.get_incar(struct)
        self.assertNotIn("LDAU", incar)

        incar = self.mithseparamset.get_incar(self.struct)
        self.assertTrue(incar['LHFCALC'])

        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 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, ["Fe", "Mn"], coords)

        incar = self.paramset.get_incar(struct)
        self.assertNotIn('LDAU', incar)

        #check fluorides
        struct = Structure(lattice, ["Fe", "F"], coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [5.3, 0])
        self.assertEqual(incar['MAGMOM'], [5, 0.6])

        struct = Structure(lattice, ["Fe", "F"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0])

        #Make sure this works with species.
        struct = Structure(lattice, ["Fe2+", "O2-"], coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [5.3, 0])

        struct = Structure(lattice, ["Fe", "Mn"],
                           coords,
                           site_properties={'magmom': (5.2, -4.5)})
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [-4.5, 5.2])
        incar = self.mpstaticparamset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [-4.5, 5.2])
        incar = self.mitparamset_unsorted.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [5.2, -4.5])

        struct = Structure(lattice, [Specie("Fe", 2, {'spin': 4.1}), "Mn"],
                           coords)
        incar = self.paramset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [5, 4.1])
        incar = self.mpnscfparamsetl.get_incar(struct)
        self.assertEqual(incar.get('MAGMOM', None), None)

        struct = Structure(lattice, ["Mn3+", "Mn4+"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['MAGMOM'], [4, 3])
        incar = self.mpnscfparamsetu.get_incar(struct)
        self.assertEqual(incar.get('MAGMOM', None), None)

        self.assertEqual(
            self.userparamset.get_incar(struct)['MAGMOM'], [100, 0.6])

        #sulfide vs sulfate test

        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 0.75])
        coords.append([0.25, 0.5, 0])

        struct = Structure(lattice, ["Fe", "Fe", "S"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [1.9, 0])

        #Make sure Matproject sulfides are ok.
        self.assertNotIn('LDAUU', self.paramset.get_incar(struct))
        self.assertNotIn('LDAUU', self.mpstaticparamset.get_incar(struct))

        struct = Structure(lattice, ["Fe", "S", "O"], coords)
        incar = self.mitparamset.get_incar(struct)
        self.assertEqual(incar['LDAUU'], [4.0, 0, 0])

        #Make sure Matproject sulfates are ok.
        self.assertEqual(self.paramset.get_incar(struct)['LDAUU'], [5.3, 0, 0])
        self.assertEqual(
            self.mpnscfparamsetl.get_incar(struct)['LDAUU'], [5.3, 0, 0])

        self.assertEqual(
            self.userparamset.get_incar(struct)['MAGMOM'], [10, -5, 0.6])

    def test_optics(self):
        if "VASP_PSP_DIR" not in os.environ:
            os.environ["VASP_PSP_DIR"] = test_dir
        self.mpopticsparamset = MPOpticsNonSCFVaspInputSet.from_previous_vasp_run(
            '{}/static_silicon'.format(test_dir),
            output_dir='optics_test_dir',
            nedos=1145)
        self.assertTrue(os.path.exists('optics_test_dir/CHGCAR'))
        incar = Incar.from_file('optics_test_dir/INCAR')
        self.assertTrue(incar['LOPTICS'])
        self.assertEqual(incar['NEDOS'], 1145)

        #Remove the directory in which the inputs have been created
        shutil.rmtree('optics_test_dir')

    def test_get_kpoints(self):
        kpoints = self.paramset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[2, 4, 6]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mitparamset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[2, 4, 6]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mpstaticparamset.get_kpoints(self.struct)
        self.assertEquals(kpoints.kpts, [[6, 6, 4]])
        self.assertEquals(kpoints.style, 'Monkhorst')

        kpoints = self.mpnscfparamsetl.get_kpoints(self.struct)
        self.assertEquals(kpoints.num_kpts, 140)
        self.assertEquals(kpoints.style, 'Reciprocal')

        kpoints = self.mpnscfparamsetu.get_kpoints(self.struct)
        self.assertEquals(kpoints.num_kpts, 168)

        kpoints = self.mpbshseparamsetl.get_kpoints(self.struct)
        self.assertAlmostEquals(kpoints.num_kpts, 164)
        self.assertAlmostEqual(kpoints.kpts[10][0], 0.0)
        self.assertAlmostEqual(kpoints.kpts[10][1], 0.5)
        self.assertAlmostEqual(kpoints.kpts[10][2], 0.16666667)
        self.assertAlmostEqual(kpoints.kpts[-1][0], 0.66006924)
        self.assertAlmostEqual(kpoints.kpts[-1][1], 0.51780182)
        self.assertAlmostEqual(kpoints.kpts[-1][2], 0.30173482)

        kpoints = self.mpbshseparamsetu.get_kpoints(self.struct)
        self.assertAlmostEquals(kpoints.num_kpts, 25)
        self.assertAlmostEqual(kpoints.kpts[10][0], 0.0)
        self.assertAlmostEqual(kpoints.kpts[10][1], 0.5)
        self.assertAlmostEqual(kpoints.kpts[10][2], 0.16666667)
        self.assertAlmostEqual(kpoints.kpts[-1][0], 0.5)
        self.assertAlmostEqual(kpoints.kpts[-1][1], 0.5)
        self.assertAlmostEqual(kpoints.kpts[-1][2], 0.0)

    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.mphseparamset.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
        })