def test_eddrmm(self): h = VaspErrorHandler("vasp.eddrmm") self.assertEqual(h.check(), True) self.assertEqual(h.correct()["errors"], ["eddrmm"]) i = Incar.from_file("INCAR") self.assertEqual(i["ALGO"], "Normal") self.assertEqual(h.correct()["errors"], ["eddrmm"]) i = Incar.from_file("INCAR") self.assertEqual(i["POTIM"], 0.25)
def make_hex_lattice_input(path, atomic_sep, kpointdivs, comment, forbid_symmetry=True): pb = hexagonal_unitcell('C', atomic_sep, layersep=25.) incar = Incar() incar['SYSTEM'] = comment incar['ALGO'] = 'Fast' incar['NSW'] = 1000 incar['IBRION'] = 2 incar['EDIFF'] = 1E-8 if forbid_symmetry: incar['ISYM'] = 0 kpoints = Kpoints.gamma_automatic(kpointdivs, [0, 0, 0]) metadata = {'atomic_sep': atomic_sep, 'kpointdivs': kpointdivs} ws = VaspInput( poscar=pb.poscar(comment=comment), potcar=pb.potcar(functional='PBE'), incar=incar, kpoints=kpoints, # additional files metadata=json.dumps(metadata), ) ws.write_input(path)
def _vasp_incar_setup(self, my_potcar, my_poscar): """Set up the INCAR, including MAGMOM string, ENCUT, and NELECT.""" name=self.keywords['name'] myd = dict() myd = self._vasp_incar_get_non_mast_keywords() try: myd.pop("IMAGES") except KeyError: pass if 'mast_multiplyencut' in self.keywords['program_keys'].keys(): mymult = float(self.keywords['program_keys']['mast_multiplyencut']) else: mymult = 1.5 if 'ENCUT' in myd.keys(): pass else: myd['ENCUT']=self._get_max_enmax_from_potcar(my_potcar)*mymult if 'mast_setmagmom' in self.keywords['program_keys'].keys(): magstr = str(self.keywords['program_keys']['mast_setmagmom']) magmomstr="" maglist = magstr.split() numatoms = sum(my_poscar.natoms) if len(maglist) < numatoms: magct=0 while magct < len(maglist): magmomstr = magmomstr + str(my_poscar.natoms[magct]) + "*" + maglist[magct] + " " magct = magct + 1 else: magmomstr = magstr myd['MAGMOM']=magmomstr if 'mast_charge' in self.keywords['program_keys'].keys(): myelectrons = self.get_total_electrons(my_poscar, my_potcar) newelectrons=0.0 try: adjustment = float(self.keywords['program_keys']['mast_charge']) except (ValueError, TypeError): raise MASTError("vasp_checker, vasp_incar_setup","Could not parse adjustment") #newelectrons = myelectrons + adjustment newelectrons = myelectrons - adjustment myd['NELECT']=str(newelectrons) if self.metafile.read_data('nbands'): myd['NBANDS']=self.metafile.read_data('nbands') my_incar = Incar(myd) dirutil.lock_directory(name) my_incar.write_file(name + "/INCAR") dirutil.unlock_directory(name) return my_incar
def test_potim_correction(self): shutil.copy("OSZICAR.one_step", "OSZICAR") s1 = Structure.from_file("POSCAR") h = VaspErrorHandler("vasp.out") self.assertEqual(h.check(), True) d = h.correct() self.assertEqual(d['errors'], ['zpotrf']) s2 = Structure.from_file("POSCAR") self.assertAlmostEqual(s2.volume, s1.volume, 3) self.assertAlmostEqual(Incar.from_file("INCAR")['POTIM'], 0.25)
def make_vasp_input(path, *, kpointdivs, comment, forbid_symmetry, functional, perturb_dist, **kwargs): assert hasattr(kpointdivs, '__iter__') assert isinstance(comment, str) assert isinstance(forbid_symmetry, bool) assert isinstance(perturb_dist, float) pb = carbon_chain_poxcar(**kwargs) incar = Incar() incar['SYSTEM'] = comment incar['ALGO'] = 'Fast' incar['NSW'] = 1000 incar['NPAR'] = 4 incar['IBRION'] = 2 incar['EDIFF'] = 1E-8 incar['EDIFFG'] = -0.001 if forbid_symmetry: incar['ISYM'] = 0 kpoints = Kpoints.gamma_automatic(kpointdivs, [0, 0, 0]) metadata = { 'kpointdivs': kpointdivs, 'functional': functional, 'perturb_dist': perturb_dist, 'forbid_symmetry': forbid_symmetry, } # FIXME FIXME FIXME # Here, we insert all structure parameters into the metadata. The purpose is because # oftentimes those parameters are the ones we're most interested in (such as scale). # # However, this is all kinds of bad: # * Not all structure arguments are necessarily desirable to have in the metadata. # * What if we want a structure argument to be of a non JSON-encodable type? # * It creates a dependency between names of function arguments in code, and the output file. # In other words, madness. metadata = dict_union(metadata, kwargs) ws = VaspInput( poscar=pb.poscar( perturb_dist=perturb_dist, comment=comment, ), potcar=pb.potcar(functional=functional, ), incar=incar, kpoints=kpoints, # additional files metadata=json.dumps(metadata), ) ws.write_input(path)
def get_incar(self, structure): incar = Incar() symamt = structure.composition.to_dict poscar = Poscar(structure) for key, setting in self.incar_settings.items(): if key == "MAGMOM": mag = [] for site in structure: if hasattr(site, 'magmom'): mag.append(site.magmom) elif hasattr(site.specie, 'spin'): mag.append(site.specie.spin) else: mag.append(setting.get(site.specie.symbol, 0.6)) incar[key] = mag elif key in ['LDAUU', 'LDAUJ', 'LDAUL']: if symamt.get("O", 0) > 0 or symamt.get("F", 0) > 0: incar[key] = [setting.get(sym, 0) for sym in poscar.site_symbols] else: incar[key] = [0 for sym in poscar.site_symbols] elif key == "EDIFF": incar[key] = float(setting) * structure.num_sites else: incar[key] = setting has_u = ("LDAUU" in incar and sum(incar['LDAUU']) > 0) if has_u: # modify LMAXMIX if LSDA+U and you have d or f electrons # note that if the user explicitly sets LMAXMIX in settings it will override this logic if 'LMAXMIX' not in self.incar_settings.keys(): if any([el.Z > 56 for el in structure.composition]): # contains f-electrons incar['LMAXMIX'] = 6 elif any([el.Z > 20 for el in structure.composition]): # contains d-electrons incar['LMAXMIX'] = 4 else: for key in incar.keys(): if key.startswith('LDAU'): del incar[key] return incar
def test_check_correct(self): subdir = os.path.join(test_dir, "potim") os.chdir(subdir) shutil.copy("INCAR", "INCAR.orig") shutil.copy("POSCAR", "POSCAR.orig") incar = Incar.from_file('INCAR') original_potim = incar['POTIM'] h = PotimErrorHandler() self.assertTrue(h.check()) d = h.correct() self.assertEqual(d["errors"], ['POTIM']) os.remove(os.path.join(subdir, "error.1.tar.gz")) incar = Incar.from_file('INCAR') new_potim = incar['POTIM'] shutil.move("INCAR.orig", "INCAR") shutil.move("POSCAR.orig", "POSCAR") self.assertEqual(original_potim, new_potim) self.assertEqual(incar['IBRION'], 3)
def test_setup(self): if "VASP_PSP_DIR" not in os.environ: os.environ["VASP_PSP_DIR"] = test_dir os.chdir(test_dir) v = VaspJob("hello") v.setup() incar = Incar.from_file("INCAR") count = multiprocessing.cpu_count() if count > 1: self.assertGreater(incar["NPAR"], 1) shutil.copy("INCAR.orig", "INCAR") os.remove("INCAR.orig") os.remove("KPOINTS.orig") os.remove("POTCAR.orig") os.remove("POSCAR.orig")
def test_aliasing_incar(self): os.chdir(os.path.join(test_dir, "aliasing")) shutil.copy("INCAR", "INCAR.orig") h = VaspErrorHandler("vasp.aliasing_incar") h.check() d = h.correct() incar = Incar.from_file('INCAR') shutil.move("INCAR.orig", "INCAR") clean_dir() os.chdir(test_dir) self.assertEqual(d["errors"], ['aliasing_incar']) self.assertEqual(d["actions"], [{'action': {'_unset': {'NGY':1, 'NGZ': 1}}, 'dict': 'INCAR'}, {"file": "CHGCAR", "action": {"_file_delete": {'mode': "actual"}}}, {"file": "WAVECAR", "action": {"_file_delete": {'mode': "actual"}}}])
def test_check_correct(self): subdir = os.path.join(test_dir, "positive_energy") os.chdir(subdir) shutil.copy("INCAR", "INCAR.orig") shutil.copy("POSCAR", "POSCAR.orig") h = PositiveEnergyErrorHandler() self.assertTrue(h.check()) d = h.correct() self.assertEqual(d["errors"], ['Positive energy']) os.remove(os.path.join(subdir, "error.1.tar.gz")) incar = Incar.from_file('INCAR') shutil.move("INCAR.orig", "INCAR") shutil.move("POSCAR.orig", "POSCAR") self.assertEqual(incar['ALGO'], 'Normal')
def test_check_correct(self): #NOTE: the vasprun here has had projected and partial eigenvalues removed subdir = os.path.join(test_dir, "max_force") os.chdir(subdir) shutil.copy("INCAR", "INCAR.orig") shutil.copy("POSCAR", "POSCAR.orig") h = MaxForceErrorHandler() self.assertTrue(h.check()) d = h.correct() self.assertEqual(d["errors"], ['MaxForce']) os.remove(os.path.join(subdir, "error.1.tar.gz")) incar = Incar.from_file('INCAR') poscar = Poscar.from_file('POSCAR') contcar = Poscar.from_file('CONTCAR') shutil.move("INCAR.orig", "INCAR") shutil.move("POSCAR.orig", "POSCAR") self.assertEqual(poscar.structure, contcar.structure) self.assertAlmostEqual(incar['EDIFF'], 0.00075)
from pymatgen.io.vaspio import Incar from pymatgen.util.string_utils import str_aligned parser = argparse.ArgumentParser(description='''Convenient INCAR diff. Author: Shyue Ping Ong Version: 1.0 Last updated: Oct 26 2011''') parser.add_argument('incar_file', metavar='filename', type=str, nargs=2, help='files to process') args = parser.parse_args() filepath1 = args.incar_file[0] filepath2 = args.incar_file[1] incar1 = Incar.from_file(filepath1) incar2 = Incar.from_file(filepath2) def format_lists(v): if isinstance(v, (tuple, list)): return " ".join(["%d*%.2f" % (len(tuple(group)), i) for (i, group) in itertools.groupby(v)]) return v d = incar1.diff(incar2) output = [['SAME PARAMS', '', '']] output.append(['---------------', '', '']) output.extend([(k, format_lists(d['Same'][k]), format_lists(d['Same'][k])) for k in sorted(d['Same'].keys()) if k != "SYSTEM"]) output.append(['', '', ''])
def process_killed_run(cls, dir_name): """ Process a killed vasp run. """ fullpath = os.path.abspath(dir_name) logger.info("Processing Killed run " + fullpath) d = {"dir_name": fullpath, "state": "killed", "oszicar": {}} for f in os.listdir(dir_name): filename = os.path.join(dir_name, f) if fnmatch(f, "INCAR*"): try: incar = Incar.from_file(filename) d["incar"] = incar.to_dict d["is_hubbard"] = incar.get("LDAU", False) if d["is_hubbard"]: us = incar.get("LDAUU", []) js = incar.get("LDAUJ", []) if sum(us) == 0 and sum(js) == 0: d["is_hubbard"] = False d["hubbards"] = {} else: d["hubbards"] = {} if d["is_hubbard"]: d["run_type"] = "GGA+U" elif incar.get("LHFCALC", False): d["run_type"] = "HF" else: d["run_type"] = "GGA" except Exception as ex: print str(ex) logger.error("Unable to parse INCAR for killed run {}.".format(dir_name)) elif fnmatch(f, "KPOINTS*"): try: kpoints = Kpoints.from_file(filename) d["kpoints"] = kpoints.to_dict except: logger.error("Unable to parse KPOINTS for killed run {}.".format(dir_name)) elif fnmatch(f, "POSCAR*"): try: s = Poscar.from_file(filename).structure comp = s.composition el_amt = s.composition.get_el_amt_dict() d.update( { "unit_cell_formula": comp.to_dict, "reduced_cell_formula": comp.to_reduced_dict, "elements": list(el_amt.keys()), "nelements": len(el_amt), "pretty_formula": comp.reduced_formula, "anonymous_formula": comp.anonymized_formula, "nsites": comp.num_atoms, "chemsys": "-".join(sorted(el_amt.keys())), } ) d["poscar"] = s.to_dict except: logger.error("Unable to parse POSCAR for killed run {}.".format(dir_name)) elif fnmatch(f, "POTCAR*"): try: potcar = Potcar.from_file(filename) d["pseudo_potential"] = {"functional": "pbe", "pot_type": "paw", "labels": potcar.symbols} except: logger.error("Unable to parse POTCAR for killed run in {}.".format(dir_name)) elif fnmatch(f, "OSZICAR"): try: d["oszicar"]["root"] = Oszicar(os.path.join(dir_name, f)).to_dict except: logger.error("Unable to parse OSZICAR for killed run in {}.".format(dir_name)) elif re.match("relax\d", f): if os.path.exists(os.path.join(dir_name, f, "OSZICAR")): try: d["oszicar"][f] = Oszicar(os.path.join(dir_name, f, "OSZICAR")).to_dict except: logger.error("Unable to parse OSZICAR for killed " "run in {}.".format(dir_name)) return d
def test_to_dict_and_from_dict(self): file_name = os.path.join(test_dir, 'INCAR') incar = Incar.from_file(file_name) d = incar.to_dict incar2 = Incar.from_dict(d) self.assertEqual(incar, incar2)
def process_killed_run(cls, dir_name): """ Process a killed vasp run. """ fullpath = os.path.abspath(dir_name) logger.info("Processing Killed run " + fullpath) d = {"dir_name": fullpath, "state": "killed", "oszicar": {}} for f in os.listdir(dir_name): filename = os.path.join(dir_name, f) if fnmatch(f, "INCAR*"): try: incar = Incar.from_file(filename) d["incar"] = incar.to_dict d["is_hubbard"] = incar.get("LDAU", False) if d["is_hubbard"]: us = incar.get("LDAUU", []) js = incar.get("LDAUJ", []) if sum(us) == 0 and sum(js) == 0: d["is_hubbard"] = False d["hubbards"] = {} else: d["hubbards"] = {} if d["is_hubbard"]: d["run_type"] = "GGA+U" elif incar.get("LHFCALC", False): d["run_type"] = "HF" else: d["run_type"] = "GGA" except Exception as ex: print str(ex) logger.error( "Unable to parse INCAR for killed run {}.".format( dir_name)) elif fnmatch(f, "KPOINTS*"): try: kpoints = Kpoints.from_file(filename) d["kpoints"] = kpoints.to_dict except: logger.error( "Unable to parse KPOINTS for killed run {}.".format( dir_name)) elif fnmatch(f, "POSCAR*"): try: s = Poscar.from_file(filename).structure comp = s.composition el_amt = s.composition.get_el_amt_dict() d.update({ "unit_cell_formula": comp.to_dict, "reduced_cell_formula": comp.to_reduced_dict, "elements": list(el_amt.keys()), "nelements": len(el_amt), "pretty_formula": comp.reduced_formula, "anonymous_formula": comp.anonymized_formula, "nsites": comp.num_atoms, "chemsys": "-".join(sorted(el_amt.keys())) }) d["poscar"] = s.to_dict except: logger.error( "Unable to parse POSCAR for killed run {}.".format( dir_name)) elif fnmatch(f, "POTCAR*"): try: potcar = Potcar.from_file(filename) d["pseudo_potential"] = { "functional": "pbe", "pot_type": "paw", "labels": potcar.symbols } except: logger.error( "Unable to parse POTCAR for killed run in {}.".format( dir_name)) elif fnmatch(f, "OSZICAR"): try: d["oszicar"]["root"] = \ Oszicar(os.path.join(dir_name, f)).to_dict except: logger.error( "Unable to parse OSZICAR for killed run in {}.".format( dir_name)) elif re.match("relax\d", f): if os.path.exists(os.path.join(dir_name, f, "OSZICAR")): try: d["oszicar"][f] = Oszicar( os.path.join(dir_name, f, "OSZICAR")).to_dict except: logger.error("Unable to parse OSZICAR for killed " "run in {}.".format(dir_name)) return d
def test_frozen_job(self): h = FrozenJobErrorHandler() d = h.correct() self.assertEqual(d['errors'], ['Frozen job']) self.assertEqual(Incar.from_file("INCAR")['ALGO'], "Normal")
def test_init(self): filepath = os.path.join(test_dir, 'INCAR') incar = Incar.from_file(filepath) incar["LDAU"] = "T" self.assertEqual(incar["ALGO"], "Damped", "Wrong Algo") self.assertEqual(float(incar["EDIFF"]), 1e-4, "Wrong EDIFF")
def test_pssyevx(self): h = VaspErrorHandler("vasp.pssyevx") self.assertEqual(h.check(), True) self.assertEqual(h.correct()["errors"], ["pssyevx"]) i = Incar.from_file("INCAR") self.assertEqual(i["ALGO"], "Normal")
parser = argparse.ArgumentParser(description='''Convenient INCAR diff. Author: Shyue Ping Ong Version: 1.0 Last updated: Oct 26 2011''') parser.add_argument('incar_file', metavar='filename', type=str, nargs=2, help='files to process') args = parser.parse_args() filepath1 = args.incar_file[0] filepath2 = args.incar_file[1] incar1 = Incar.from_file(filepath1) incar2 = Incar.from_file(filepath2) def format_lists(v): if isinstance(v, (tuple, list)): return " ".join([ "%d*%.2f" % (len(tuple(group)), i) for (i, group) in itertools.groupby(v) ]) return v d = incar1.diff(incar2) output = [['SAME PARAMS', '', '']] output.append(['---------------', '', ''])
def test_diff(self): filepath1 = os.path.join(test_dir, 'INCAR') incar1 = Incar.from_file(filepath1) filepath2 = os.path.join(test_dir, 'INCAR.2') incar2 = Incar.from_file(filepath2) self.assertEqual(incar1.diff(incar2), {'Different': {'NELM': {'INCAR1': 'Default', 'INCAR2': 100}, 'ISPIND': {'INCAR1': 2, 'INCAR2': 'Default'}, 'LWAVE': {'INCAR1': True, 'INCAR2': False}, 'LDAUPRINT': {'INCAR1': 'Default', 'INCAR2': 1}, 'MAGMOM': {'INCAR1': [6, -6, -6, 6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6], 'INCAR2': 'Default'}, 'NELMIN': {'INCAR1': 'Default', 'INCAR2': 3}, 'ENCUTFOCK': {'INCAR1': 0.0, 'INCAR2': 'Default'}, 'HFSCREEN': {'INCAR1': 0.207, 'INCAR2': 'Default'}, 'LSCALU': {'INCAR1': False, 'INCAR2': 'Default'}, 'ENCUT': {'INCAR1': 500, 'INCAR2': 'Default'}, 'NSIM': {'INCAR1': 1, 'INCAR2': 'Default'}, 'ICHARG': {'INCAR1': 'Default', 'INCAR2': 1}, 'NSW': {'INCAR1': 99, 'INCAR2': 51}, 'NKRED': {'INCAR1': 2, 'INCAR2': 'Default'}, 'NUPDOWN': {'INCAR1': 0, 'INCAR2': 'Default'}, 'LCHARG': {'INCAR1': True, 'INCAR2': 'Default'}, 'LPLANE': {'INCAR1': True, 'INCAR2': 'Default'}, 'ISMEAR': {'INCAR1': 0, 'INCAR2':-5}, 'NPAR': {'INCAR1': 8, 'INCAR2': 1}, 'SYSTEM': {'INCAR1': 'Id=[0] dblock_code=[97763-icsd] formula=[li mn (p o4)] sg_name=[p n m a]', 'INCAR2': 'Id=[91090] dblock_code=[20070929235612linio-59.53134651-vasp] formula=[li3 ni3 o6] sg_name=[r-3m]'}, 'ALGO': {'INCAR1': 'Damped', 'INCAR2': 'Fast'}, 'LHFCALC': {'INCAR1': True, 'INCAR2': 'Default'}, 'TIME': {'INCAR1': 0.4, 'INCAR2': 'Default'}}, 'Same': {'IBRION': 2, 'PREC': 'Accurate', 'ISIF': 3, 'LMAXMIX': 4, 'LREAL': 'Auto', 'ISPIN': 2, 'EDIFF': 0.0001, 'LORBIT': '11', 'SIGMA': 0.05}})