def test_dielectric(self): filepath = os.path.join(test_dir, "OUTCAR.dielectric") outcar = Outcar(filepath) outcar.read_corrections() self.assertAlmostEqual(outcar.data["dipol_quadrupol_correction"], 0.03565) self.assertAlmostEqual(outcar.final_energy, -797.46760559)
def run_task(self, fw_spec): directory = self.get("directory", os.getcwd()) multiplier = self.get("multiplier", 3) os.chdir(directory) nelect_written = False try: with open("OUTCAR", "r") as file: if "NELECT" in file.read(): nelect_written = True except FileNotFoundError: pass if not nelect_written: # Do a trial run to figure out the number of standard bands stdout_file = "temp.out" stderr_file = "temp.out" vasp_cmd = fw_spec["_fw_env"]["vasp_cmd"].split(" ") with open(stdout_file, 'w') as f_std, \ open(stderr_file, "w", buffering=1) as f_err: p = subprocess.Popen(vasp_cmd, stdout=f_std, stderr=f_err, preexec_fn=os.setsid) while not nelect_written: try: with open("OUTCAR", "r") as file: if "NELECT" in file.read(): nelect_written = True except FileNotFoundError: pass time.sleep(1) os.killpg(os.getpgid(p.pid), signal.SIGTERM) time.sleep(3) os.remove(os.path.join(directory, "temp.out")) outcar = Outcar("OUTCAR") incar = Incar.from_file("INCAR") pattern = r"\s+NELECT\s=\s+(\d+).\d+\s+total\snumber\sof\selectrons" outcar.read_pattern({"nelect": pattern}) nions = len(Structure.from_file("POSCAR")) nelect = int(outcar.data["nelect"][0][0]) ispin = int(incar.get("ISPIN", 1)) if ispin == 1: nbands = int(round(nelect / 2 + nions / 2)) * multiplier elif ispin == 2: nbands = int(nelect * 3 / 5 + nions) * multiplier else: raise ValueError("ISPIN Value is not set to 1 or 2!") incar.update({"NBANDS": nbands}) incar.write_file("INCAR")
def test_single_atom(self): filepath = os.path.join(test_dir, "OUTCAR.Al") outcar = Outcar(filepath) expected_mag = ({"p": 0.0, "s": 0.0, "d": 0.0, "tot": 0.0},) expected_chg = ({"p": 0.343, "s": 0.425, "d": 0.0, "tot": 0.768},) self.assertAlmostEqual(outcar.magnetization, expected_mag) self.assertAlmostEqual(outcar.charge, expected_chg) self.assertFalse(outcar.is_stopped) self.assertEqual( outcar.run_stats, { "System time (sec)": 0.592, "Total CPU time used (sec)": 50.194, "Elapsed time (sec)": 52.337, "Maximum memory used (kb)": 62900.0, "Average memory used (kb)": 0.0, "User time (sec)": 49.602, "cores": "32", }, ) self.assertAlmostEqual(outcar.efermi, 8.0942) self.assertAlmostEqual(outcar.nelect, 3) self.assertAlmostEqual(outcar.total_mag, 8.2e-06) self.assertIsNotNone(outcar.as_dict())
def test_avg_core_poten(self): filepath = os.path.join(test_dir, "OUTCAR.lepsilon") cp = Outcar(filepath).read_avg_core_poten() self.assertAlmostEqual(cp[-1][1], -90.0487) filepath = os.path.join(test_dir, "OUTCAR") cp = Outcar(filepath).read_avg_core_poten() self.assertAlmostEqual(cp[0][6], -73.1068)
def set_ionic_dielectric_tensor_from_vasp(self, directory_path: str, outcar_name: str = "OUTCAR" ) -> None: outcar = Outcar(os.path.join(directory_path, outcar_name)) outcar.read_lepsilon_ionic() self._ionic_dielectric_tensor = outcar.dielectric_ionic_tensor
def test_read_fermi_contact_shift(self): filepath = os.path.join(test_dir, "OUTCAR_fc") outcar = Outcar(filepath) outcar.read_fermi_contact_shift() self.assertAlmostEqual(outcar.data["fermi_contact_shift"][u'fch'][0][0], -0.002) self.assertAlmostEqual(outcar.data["fermi_contact_shift"][u'th'][0][0], -0.052) self.assertAlmostEqual(outcar.data["fermi_contact_shift"][u'dh'][0][0], 0.0)
def test_core_state_eigen(self): filepath = os.path.join(test_dir, "OUTCAR.CL") cl = Outcar(filepath).read_core_state_eigen() self.assertAlmostEqual(cl[6]["2s"][-1], -174.4779) filepath = os.path.join(test_dir, "OUTCAR.icorelevel") cl = Outcar(filepath).read_core_state_eigen() self.assertAlmostEqual(cl[4]["3d"][-1], -31.4522)
def test_read_piezo_tensor(self): filepath = os.path.join(test_dir, "OUTCAR.lepsilon.gz") outcar = Outcar(filepath) outcar.read_piezo_tensor() self.assertAlmostEqual(outcar.data["piezo_tensor"][0][0], 0.52799) self.assertAlmostEqual(outcar.data["piezo_tensor"][1][3], 0.35998) self.assertAlmostEqual(outcar.data["piezo_tensor"][2][5], 0.35997)
def test_drift(self): outcar = Outcar(os.path.join(test_dir, "OUTCAR")) self.assertEqual(len(outcar.drift),5) self.assertAlmostEqual(np.sum(outcar.drift),0) outcar = Outcar(os.path.join(test_dir, "OUTCAR.CL")) self.assertEqual(len(outcar.drift), 79) self.assertAlmostEqual(np.sum(outcar.drift), 0.448010)
def test_cs_core_contribution(self): filename = os.path.join(test_dir, "nmr", "cs", "core.diff", "core.diff.chemical.shifts.OUTCAR") outcar = Outcar(filename) core_contrib = outcar.read_cs_core_contribution() self.assertEqual(core_contrib, {'Mg': -412.8248405, 'C': -200.5098812, 'O': -271.0766979})
def test_cs_g0_contribution(self): filename = os.path.join(test_dir, "nmr", "cs", "core.diff", "core.diff.chemical.shifts.OUTCAR") outcar = Outcar(filename) g0_contrib = outcar.read_cs_g0_contribution() self.assertEqual(g0_contrib, [[-8.773535, 9e-06, 1e-06], [1.7e-05, -8.773536, -0.0792], [-6e-06, -0.008328, -9.320237]])
def test_cs_g0_contribution(self): filename = os.path.join(test_dir, "nmr", "cs", "core.diff", "core.diff.chemical.shifts.OUTCAR") outcar = Outcar(filename) g0_contrib = outcar.read_cs_g0_contribution() self.assertEqual( g0_contrib, [[-8.773535, 9e-06, 1e-06], [1.7e-05, -8.773536, -0.0792], [-6e-06, -0.008328, -9.320237]])
def test_read_elastic_tensor(self): filepath = os.path.join(test_dir, "OUTCAR.total_tensor.Li2O.gz") outcar = Outcar(filepath) outcar.read_elastic_tensor() self.assertAlmostEqual(outcar.data["elastic_tensor"][0][0], 1986.3391) self.assertAlmostEqual(outcar.data["elastic_tensor"][0][1], 187.8324) self.assertAlmostEqual(outcar.data["elastic_tensor"][3][3], 586.3034)
def test_freq_dielectric(self): filepath = os.path.join(test_dir, "OUTCAR.LOPTICS") outcar = Outcar(filepath) outcar.read_freq_dielectric() self.assertAlmostEqual(outcar.frequencies[0], 0) self.assertAlmostEqual(outcar.frequencies[-1], 39.826101) self.assertAlmostEqual(outcar.dielectric_tensor_function[0][0, 0], 8.96938800) self.assertAlmostEqual(outcar.dielectric_tensor_function[-1][0, 0], 7.36167000e-01 +1.53800000e-03j) self.assertEqual(len(outcar.frequencies), len(outcar.dielectric_tensor_function))
def test_freq_dielectric_vasp544(self): filepath = os.path.join(test_dir, "OUTCAR.LOPTICS.vasp544") outcar = Outcar(filepath) outcar.read_freq_dielectric() self.assertAlmostEqual(outcar.frequencies[0], 0) self.assertAlmostEqual(outcar.frequencies[-1], 39.63964) self.assertAlmostEqual(outcar.dielectric_tensor_function[0][0, 0], 12.769435+0j) self.assertAlmostEqual(outcar.dielectric_tensor_function[-1][0, 0], 0.828615+0.016594j) self.assertEqual(len(outcar.frequencies), len(outcar.dielectric_tensor_function)) np.testing.assert_array_equal( outcar.dielectric_tensor_function[0], outcar.dielectric_tensor_function[0].transpose())
def test_chemical_shifts_with_different_core_contribution(self): filename = os.path.join(test_dir, "nmr", "cs", "core.diff", "core.diff.chemical.shifts.OUTCAR") outcar = Outcar(filename) outcar.read_chemical_shifts() c_vo = outcar.data["chemical_shifts"]["valence_only"][7].maryland_values for x1, x2 in zip(list(c_vo), [198.7009, 73.7484, 1.0000]): self.assertAlmostEqual(x1, x2) c_vc = outcar.data["chemical_shifts"]["valence_and_core"][7].maryland_values for x1, x2 in zip(list(c_vc), [-1.9406, 73.7484, 1.0000]): self.assertAlmostEqual(x1, x2)
def test_get_outcar_method(testdata): from pymatgen.io.vasp.outputs import Outcar from aiida_cusp.data.outputs.vasp_outcar import VaspOutcarData outcar = testdata / 'OUTCAR' outcar_node = VaspOutcarData(file=outcar) # create Outcar object from node and compare to the original # pymatgen class generated from the test file outcar_obj_node = outcar_node.get_outcar() outcar_obj_pmg = Outcar(outcar) node_contents = json.dumps(outcar_obj_node.as_dict(), sort_keys=True) pmg_contents = json.dumps(outcar_obj_pmg.as_dict(), sort_keys=True) assert node_contents == pmg_contents
def test_cs_raw_tensors(self): filename = os.path.join(test_dir, "nmr", "cs", "core.diff", "core.diff.chemical.shifts.OUTCAR") outcar = Outcar(filename) unsym_tensors = outcar.read_cs_raw_symmetrized_tensors() self.assertEqual(unsym_tensors[0], [[-145.814605, -4.263425, 0.000301], [4.263434, -145.812238, -8.7e-05], [0.000136, -0.000189, -142.794068]]) self.assertEqual(unsym_tensors[29], [[287.789318, -53.799325, 30.900024], [-53.799571, 225.668117, -17.839598], [3.801103, -2.195218, 88.896756]])
def test_chemical_shifts_with_different_core_contribution(self): filename = os.path.join(test_dir, "nmr", "cs", "core.diff", "core.diff.chemical.shifts.OUTCAR") outcar = Outcar(filename) outcar.read_chemical_shifts() c_vo = outcar.data["chemical_shifts"]["valence_only"][ 7].maryland_values for x1, x2 in zip(list(c_vo), [198.7009, 73.7484, 1.0000]): self.assertAlmostEqual(x1, x2) c_vc = outcar.data["chemical_shifts"]["valence_and_core"][ 7].maryland_values for x1, x2 in zip(list(c_vc), [-1.9406, 73.7484, 1.0000]): self.assertAlmostEqual(x1, x2)
def test_electrostatic_potential(self): outcar = Outcar(os.path.join(test_dir,"OUTCAR")) self.assertEqual(outcar.ngf,[54,30,54]) self.assertTrue(np.allclose(outcar.sampling_radii,[0.9748, 0.9791, 0.7215])) self.assertTrue(np.allclose(outcar.electrostatic_potential, [-26.0704, -45.5046, -45.5046, -72.9539, -73.0621, -72.9539, -73.0621]))
def parse_calculation(folder, zero_weighted_kpoints=defaults["zero_weighted_kpoints"]): vr = Vasprun(get_gzipped_file("vasprun.xml", folder)) out = Outcar(get_gzipped_file("OUTCAR", folder)) bs = get_band_structure(vr, zero_weighted=zero_weighted_kpoints) reference_level = get_reference_energy(bs, out) return {"reference": reference_level, "bandstructure": bs}
def generate_nscf_soc_folders(structures, saxis, user_incar): """ Generate the non self-consistent calculation with the spin-orbit coupling """ for name in structures: # add magmom as a site property for each atom outcar = Outcar(filename=os.path.join(name, 'OUTCAR')) for i, atom in enumerate(structures[name].sites): atom.properties = { "magmom": [0., 0., round(outcar.magnetization[i]['tot'], 2)] } # geterate calculation from the MPSOCSet mpsoc = MPSOCSet(structures[name], saxis=saxis, user_incar_settings=user_incar, user_kpoints_settings={"reciprocal_density": 500}) mpsoc.write_input(os.path.join(name, 'nscf_SOC')) # walk around the bug in MPSICSet to introduce LDAUU and LDAUL into INCAR dic = mpsoc.incar.as_dict() dic["LDAUU"] = list(dic["LDAUU"].values()) dic["LDAUL"] = list(dic["LDAUL"].values()) Incar.from_dict(dic).write_file(os.path.join(name, 'nscf_SOC/INCAR')) shutil.copy(os.path.join(name, 'CHGCAR'), os.path.join(name, 'nscf_SOC'))
def from_files(poscar_filename, locpot_filename, outcar_filename, shift=0): p = Poscar.from_file(poscar_filename) l = Locpot.from_file(locpot_filename) o = Outcar(outcar_filename) return WorkFunctionAnalyzer(p.structure, l.get_average_along_axis(int(sys.argv[1])), o.efermi, shift=shift)
def parse_outcar(self): """Try to parse the OUTCAR file.""" outcar_path = self.get_file('OUTCAR') if not outcar_path: return None parsed_outcar = Outcar(outcar_path) return parsed_outcar
def get_structure(directory, write_cif=False): """ Construct a .json file with the structure and magnetic moment from the output of a VASP calculation, i.e. the CONTCAR and OUTCAR file. Args: directory (str): Directory in which the geometry optimization output files (i.e. CONTCAR and OUTCAR) are stored. write_cif (bool): Flag that indicates whether the structure should also be written as a .cif file. """ directory = os.path.abspath(directory) structure = Structure.from_file(os.path.join(directory, "CONTCAR")) out = Outcar(os.path.join(directory, "OUTCAR")) magmom = [site["tot"] for site in out.magnetization] # Add the magnetic moments to the Structure try: structure.add_site_property("magmom", magmom) except ValueError: # If something goes wrong in assigning the magnetic moments, # give the user a warning and assign magnetic moment zero to all sites. print("WARNING: Could not assign the magnetic moments found in the " "OUTCAR file. They may be missing.") structure.add_site_property("magmom", len(structure.sites) * [0]) structure.to("json", "structure.json") if write_cif: structure.to("cif", "structure.cif")
def get_directories_VaspJobNotDone(root_dir): with cd(root_dir): ### avoid the link problems root_dir_real = os.getcwd() scan = subprocess.Popen(['find', root_dir_real, '-name', 'POSCAR'], stdout=subprocess.PIPE) scan.wait() pos_coll = scan.stdout.read().split() pos_dirs = [os.path.split(i)[0] for i in pos_coll] vaspjob_dirs = [] for dir in pos_dirs: try: pos = Poscar.from_file(os.path.join(dir, 'POSCAR')) pot = Potcar.from_file(os.path.join(dir, 'POTCAR')) incar = Incar.from_file(os.path.join(dir, 'INCAR')) kpt = Kpoints.from_file(os.path.join(dir, 'KPOINTS')) except: print 'input files are not ready in %s' % dir else: try: out = Outcar(os.path.join(dir, 'OUTCAR')) if len(out.run_stats) != 7: vaspjob_dir.append(dir) except: vaspjob_dirs.append(dir) return vaspjob_dirs
def postprocess(self): """ Postprocessing includes renaming and gzipping where necessary. Also copies the magmom to the incar if necessary """ for f in VASP_OUTPUT_FILES + [self.output_file]: if os.path.exists(f): if self.final and self.suffix != "": shutil.move(f, "{}{}".format(f, self.suffix)) elif self.suffix != "": shutil.copy(f, "{}{}".format(f, self.suffix)) if self.copy_magmom and not self.final: try: outcar = Outcar("OUTCAR") magmom = [m["tot"] for m in outcar.magnetization] incar = Incar.from_file("INCAR") incar["MAGMOM"] = magmom incar.write_file("INCAR") except Exception: logger.error("MAGMOM copy from OUTCAR to INCAR failed") # Remove continuation so if a subsequent job is run in # the same directory, will not restart this job. if os.path.exists("continue.json"): os.remove("continue.json")
def test_nmr_efg(self): filename = os.path.join(test_dir, "nmr", "efg", "AlPO4", "OUTCAR") outcar = Outcar(filename) outcar.read_nmr_efg() expected_efg = [{'eta': 0.465, 'nuclear_quadrupole_moment': 146.6, 'cq': -5.573}, {'eta': 0.465, 'nuclear_quadrupole_moment': 146.6, 'cq': -5.573}, {'eta': 0.137, 'nuclear_quadrupole_moment': 146.6, 'cq': 6.327}, {'eta': 0.137, 'nuclear_quadrupole_moment': 146.6, 'cq': 6.327}, {'eta': 0.112, 'nuclear_quadrupole_moment': 146.6, 'cq': -7.453}, {'eta': 0.112, 'nuclear_quadrupole_moment': 146.6, 'cq': -7.453}, {'eta': 0.42, 'nuclear_quadrupole_moment': 146.6, 'cq': -5.58}, {'eta': 0.42, 'nuclear_quadrupole_moment': 146.6, 'cq': -5.58}] self.assertEqual(len(outcar.data["efg"][2:10]), len(expected_efg)) for e1, e2 in zip(outcar.data["efg"][2:10], expected_efg): for k in e1.keys(): self.assertAlmostEqual(e1[k], e2[k], places=5)
def test_pseudo_zval(self): filepath = os.path.join(test_dir, "OUTCAR.BaTiO3.polar") outcar = Outcar(filepath) self.assertDictEqual({ 'Ba': 10.00, 'Ti': 10.00, 'O': 6.00 }, outcar.zval_dict)
def test_chemical_shifts(self): filename = os.path.join(test_dir, "nmr_chemical_shift", "hydromagnesite", "OUTCAR") outcar = Outcar(filename) expected_chemical_shifts = [[191.9974, 69.5232, 0.6342], [195.0808, 68.183, 0.833], [192.0389, 69.5762, 0.6329], [195.0844, 68.1756, 0.8336], [192.005, 69.5289, 0.6339], [195.0913, 68.1859, 0.833], [192.0237, 69.565, 0.6333], [195.0788, 68.1733, 0.8337]] self.assertAlmostEqual(len(outcar.chemical_shifts[20: 28]), len(expected_chemical_shifts)) for c1, c2 in zip(outcar.chemical_shifts[20: 28], expected_chemical_shifts): for x1, x2 in zip(list(c1.maryland_values), c2): self.assertAlmostEqual(x1, x2, places=5) d1 = outcar.as_dict() self.assertIn("chemical_shifts", d1)
def test_elastic_tensor(self): filepath = os.path.join(test_dir, "OUTCAR.total_tensor.Li2O.gz") outcar = Outcar(filepath) elastic_tensor = outcar.elastic_tensor self.assertAlmostEqual(elastic_tensor[0][0], 1986.3391) self.assertAlmostEqual(elastic_tensor[0][1], 187.8324) self.assertAlmostEqual(elastic_tensor[3][3], 586.3034)
def read_outcar(outcar_file): if os.path.exists(outcar_file): f = Outcar(outcar_file) # with Outcar(outcar_file) as f: # print(f) forces = f.read_table_pattern( header_pattern=r"\sPOSITION\s+TOTAL-FORCE \(eV/Angst\)\n\s-+", row_pattern= r"\s+[+-]?\d+\.\d+\s+[+-]?\d+\.\d+\s+[+-]?\d+\.\d+\s+([+-]?\d+\.\d+)\s+([+-]?\d+\.\d+)\s+([+-]?\d+\.\d+)", footer_pattern=r"\s--+", postprocess=lambda x: float(x), last_one_only=False) return (forces) else: print( "No OUTCAR file reads in, at least make sure you have '{}' by default" .format(outcar_file), file=sys.stderr)
def get_endiff(directory): """ Calculate the energy difference for a transition in a directory. Args: directory: Returns: """ initial_outcar = Outcar(os.path.join(directory, "initial", "OUTCAR")) final_outcar = Outcar(os.path.join(directory, "final", "OUTCAR")) initial_energy = initial_outcar.final_energy final_energy = final_outcar.final_energy print("The energy difference is: ", end="") print(str(final_energy - initial_energy) + " eV")
def forces_from_outcar( filename='OUTCAR' ): """Finds and returns forces from the OUTCAR file. Args: filename (:obj:'str', optional): the name of the ``OUTCAR`` file to be read. Default is `OUTCAR`. Returns: (np.array): The force as found in the ``OUTCAR`` file, as a NSTEPS x NIONS x 3 numpy array. """ outcar = Outcar("OUTCAR") forces = outcar.read_table_pattern( header_pattern=r"\sPOSITION\s+TOTAL-FORCE \(eV/Angst\)\n\s-+", row_pattern=r"\s+[+-]?\d+\.\d+\s+[+-]?\d+\.\d+\s+[+-]?\d+\.\d+\s+([+-]?\d+\.\d+)\s+([+-]?\d+\.\d+)\s+([+-]?\d+\.\d+)", footer_pattern=r"\s--+", postprocess=lambda x: float(x), last_one_only=False ) return np.array( forces )
def test_single_atom(self): filepath = os.path.join(test_dir, "OUTCAR.Al") outcar = Outcar(filepath) expected_mag = ({u'p': 0.0, u's': 0.0, u'd': 0.0, u'tot': 0.0},) expected_chg = ({u'p': 0.343, u's': 0.425, u'd': 0.0, u'tot': 0.768},) self.assertAlmostEqual(outcar.magnetization, expected_mag) self.assertAlmostEqual(outcar.charge, expected_chg) self.assertFalse(outcar.is_stopped) self.assertEqual(outcar.run_stats, {'System time (sec)': 0.592, 'Total CPU time used (sec)': 50.194, 'Elapsed time (sec)': 52.337, 'Maximum memory used (kb)': 62900.0, 'Average memory used (kb)': 0.0, 'User time (sec)': 49.602, 'cores': '32'}) self.assertAlmostEqual(outcar.efermi, 8.0942) self.assertAlmostEqual(outcar.nelect, 3) self.assertAlmostEqual(outcar.total_mag, 8.2e-06) self.assertIsNotNone(outcar.as_dict())
def test_init(self): for f in ["OUTCAR", "OUTCAR.gz"]: filepath = os.path.join(test_dir, f) outcar = Outcar(filepath) expected_mag = ( {"d": 0.0, "p": 0.003, "s": 0.002, "tot": 0.005}, {"d": 0.798, "p": 0.008, "s": 0.007, "tot": 0.813}, {"d": 0.798, "p": 0.008, "s": 0.007, "tot": 0.813}, {"d": 0.0, "p": -0.117, "s": 0.005, "tot": -0.112}, {"d": 0.0, "p": -0.165, "s": 0.004, "tot": -0.162}, {"d": 0.0, "p": -0.117, "s": 0.005, "tot": -0.112}, {"d": 0.0, "p": -0.165, "s": 0.004, "tot": -0.162}, ) expected_chg = ( {"p": 0.154, "s": 0.078, "d": 0.0, "tot": 0.232}, {"p": 0.707, "s": 0.463, "d": 8.316, "tot": 9.486}, {"p": 0.707, "s": 0.463, "d": 8.316, "tot": 9.486}, {"p": 3.388, "s": 1.576, "d": 0.0, "tot": 4.964}, {"p": 3.365, "s": 1.582, "d": 0.0, "tot": 4.947}, {"p": 3.388, "s": 1.576, "d": 0.0, "tot": 4.964}, {"p": 3.365, "s": 1.582, "d": 0.0, "tot": 4.947}, ) self.assertAlmostEqual(outcar.magnetization, expected_mag, 5, "Wrong magnetization read from Outcar") self.assertAlmostEqual(outcar.charge, expected_chg, 5, "Wrong charge read from Outcar") self.assertFalse(outcar.is_stopped) self.assertEqual( outcar.run_stats, { "System time (sec)": 0.938, "Total CPU time used (sec)": 545.142, "Elapsed time (sec)": 546.709, "Maximum memory used (kb)": 0.0, "Average memory used (kb)": 0.0, "User time (sec)": 544.204, "cores": "8", }, ) self.assertAlmostEqual(outcar.efermi, 2.0112) self.assertAlmostEqual(outcar.nelect, 44.9999991) self.assertAlmostEqual(outcar.total_mag, 0.9999998) self.assertIsNotNone(outcar.as_dict()) self.assertFalse(outcar.lepsilon) filepath = os.path.join(test_dir, "OUTCAR.stopped") outcar = Outcar(filepath) self.assertTrue(outcar.is_stopped) for f in ["OUTCAR.lepsilon", "OUTCAR.lepsilon.gz"]: filepath = os.path.join(test_dir, f) outcar = Outcar(filepath) self.assertTrue(outcar.lepsilon) self.assertAlmostEqual(outcar.dielectric_tensor[0][0], 3.716432) self.assertAlmostEqual(outcar.dielectric_tensor[0][1], -0.20464) self.assertAlmostEqual(outcar.dielectric_tensor[1][2], -0.20464) self.assertAlmostEqual(outcar.dielectric_ionic_tensor[0][0], 0.001419) self.assertAlmostEqual(outcar.dielectric_ionic_tensor[0][2], 0.001419) self.assertAlmostEqual(outcar.dielectric_ionic_tensor[2][2], 0.001419) self.assertAlmostEqual(outcar.piezo_tensor[0][0], 0.52799) self.assertAlmostEqual(outcar.piezo_tensor[1][3], 0.35998) self.assertAlmostEqual(outcar.piezo_tensor[2][5], 0.35997) self.assertAlmostEqual(outcar.piezo_ionic_tensor[0][0], 0.05868) self.assertAlmostEqual(outcar.piezo_ionic_tensor[1][3], 0.06241) self.assertAlmostEqual(outcar.piezo_ionic_tensor[2][5], 0.06242) self.assertAlmostEqual(outcar.born[0][1][2], -0.385) self.assertAlmostEqual(outcar.born[1][2][0], 0.36465)
def assimilate(self, path, launches_coll=None): """ Parses vasp runs. Then insert the result into the db. and return the task_id or doc of the insertion. Returns: If in simulate_mode, the entire doc is returned for debugging purposes. Else, only the task_id of the inserted doc is returned. """ d = self.get_task_doc(path) if self.additional_fields: d.update(self.additional_fields) # always add additional fields, even for failed jobs try: d["dir_name_full"] = d["dir_name"].split(":")[1] d["dir_name"] = get_block_part(d["dir_name_full"]) d["stored_data"] = {} except: print 'COULD NOT GET DIR NAME' pprint.pprint(d) print traceback.format_exc() raise ValueError('IMPROPER PARSING OF {}'.format(path)) if not self.simulate: # Perform actual insertion into db. Because db connections cannot # be pickled, every insertion needs to create a new connection # to the db. conn = MongoClient(self.host, self.port) db = conn[self.database] if self.user: db.authenticate(self.user, self.password) coll = db[self.collection] # Insert dos data into gridfs and then remove it from the dict. # DOS data tends to be above the 4Mb limit for mongo docs. A ref # to the dos file is in the dos_fs_id. result = coll.find_one({"dir_name": d["dir_name"]}) if result is None or self.update_duplicates: if self.parse_dos and "calculations" in d: for calc in d["calculations"]: if "dos" in calc: dos = json.dumps(calc["dos"], cls=MontyEncoder) fs = gridfs.GridFS(db, "dos_fs") dosid = fs.put(dos) calc["dos_fs_id"] = dosid del calc["dos"] d["last_updated"] = datetime.datetime.today() if result is None: if ("task_id" not in d) or (not d["task_id"]): d["task_id"] = "mp-{}".format( db.counter.find_one_and_update( {"_id": "taskid"}, {"$inc": {"c": 1}} )["c"]) logger.info("Inserting {} with taskid = {}" .format(d["dir_name"], d["task_id"])) elif self.update_duplicates: d["task_id"] = result["task_id"] logger.info("Updating {} with taskid = {}" .format(d["dir_name"], d["task_id"])) #Fireworks processing self.process_fw(path, d) try: #Add oxide_type struct=Structure.from_dict(d["output"]["crystal"]) d["oxide_type"]=oxide_type(struct) except: logger.error("can't get oxide_type for {}".format(d["task_id"])) d["oxide_type"] = None #Override incorrect outcar subdocs for two step relaxations if "optimize structure" in d['task_type'] and \ os.path.exists(os.path.join(path, "relax2")): try: run_stats = {} for i in [1,2]: o_path = os.path.join(path,"relax"+str(i),"OUTCAR") o_path = o_path if os.path.exists(o_path) else o_path+".gz" outcar = Outcar(o_path) d["calculations"][i-1]["output"]["outcar"] = outcar.as_dict() run_stats["relax"+str(i)] = outcar.run_stats except: logger.error("Bad OUTCAR for {}.".format(path)) try: overall_run_stats = {} for key in ["Total CPU time used (sec)", "User time (sec)", "System time (sec)", "Elapsed time (sec)"]: overall_run_stats[key] = sum([v[key] for v in run_stats.values()]) run_stats["overall"] = overall_run_stats except: logger.error("Bad run stats for {}.".format(path)) d["run_stats"] = run_stats # add is_compatible mpc = MaterialsProjectCompatibility("Advanced") try: func = d["pseudo_potential"]["functional"] labels = d["pseudo_potential"]["labels"] symbols = ["{} {}".format(func, label) for label in labels] parameters = {"run_type": d["run_type"], "is_hubbard": d["is_hubbard"], "hubbards": d["hubbards"], "potcar_symbols": symbols} entry = ComputedEntry(Composition(d["unit_cell_formula"]), 0.0, 0.0, parameters=parameters, entry_id=d["task_id"]) d['is_compatible'] = bool(mpc.process_entry(entry)) except: traceback.print_exc() print 'ERROR in getting compatibility' d['is_compatible'] = None #task_type dependent processing if 'static' in d['task_type']: launch_doc = launches_coll.find_one({"fw_id": d['fw_id'], "launch_dir": {"$regex": d["dir_name"]}}, {"action.stored_data": 1}) for i in ["conventional_standard_structure", "symmetry_operations", "symmetry_dataset", "refined_structure"]: try: d['stored_data'][i] = launch_doc['action']['stored_data'][i] except: pass #parse band structure if necessary if ('band structure' in d['task_type'] or "Uniform" in d['task_type'])\ and d['state'] == 'successful': launch_doc = launches_coll.find_one({"fw_id": d['fw_id'], "launch_dir": {"$regex": d["dir_name"]}}, {"action.stored_data": 1}) vasp_run = Vasprun(zpath(os.path.join(path, "vasprun.xml")), parse_projected_eigen=False) if 'band structure' in d['task_type']: def string_to_numlist(stringlist): g=re.search('([0-9\-\.eE]+)\s+([0-9\-\.eE]+)\s+([0-9\-\.eE]+)', stringlist) return [float(g.group(i)) for i in range(1,4)] for i in ["kpath_name", "kpath"]: d['stored_data'][i] = launch_doc['action']['stored_data'][i] kpoints_doc = d['stored_data']['kpath']['kpoints'] for i in kpoints_doc: kpoints_doc[i]=string_to_numlist(kpoints_doc[i]) bs=vasp_run.get_band_structure(efermi=d['calculations'][0]['output']['outcar']['efermi'], line_mode=True) else: bs=vasp_run.get_band_structure(efermi=d['calculations'][0]['output']['outcar']['efermi'], line_mode=False) bs_json = json.dumps(bs.as_dict(), cls=MontyEncoder) fs = gridfs.GridFS(db, "band_structure_fs") bs_id = fs.put(bs_json) d['calculations'][0]["band_structure_fs_id"] = bs_id # also override band gap in task doc gap = bs.get_band_gap() vbm = bs.get_vbm() cbm = bs.get_cbm() update_doc = {'bandgap': gap['energy'], 'vbm': vbm['energy'], 'cbm': cbm['energy'], 'is_gap_direct': gap['direct']} d['analysis'].update(update_doc) d['calculations'][0]['output'].update(update_doc) coll.update_one({"dir_name": d["dir_name"]}, {'$set': d}, upsert=True) return d["task_id"], d else: logger.info("Skipping duplicate {}".format(d["dir_name"])) return result["task_id"], result else: d["task_id"] = 0 logger.info("Simulated insert into database for {} with task_id {}" .format(d["dir_name"], d["task_id"])) return 0, d
def test_init(self): for f in ['OUTCAR', 'OUTCAR.gz']: filepath = os.path.join(test_dir, f) outcar = Outcar(filepath) expected_mag = ({'d': 0.0, 'p': 0.003, 's': 0.002, 'tot': 0.005}, {'d': 0.798, 'p': 0.008, 's': 0.007, 'tot': 0.813}, {'d': 0.798, 'p': 0.008, 's': 0.007, 'tot': 0.813}, {'d': 0.0, 'p':-0.117, 's': 0.005, 'tot':-0.112}, {'d': 0.0, 'p':-0.165, 's': 0.004, 'tot':-0.162}, {'d': 0.0, 'p':-0.117, 's': 0.005, 'tot':-0.112}, {'d': 0.0, 'p':-0.165, 's': 0.004, 'tot':-0.162}) expected_chg = ({'p': 0.154, 's': 0.078, 'd': 0.0, 'tot': 0.232}, {'p': 0.707, 's': 0.463, 'd': 8.316, 'tot': 9.486}, {'p': 0.707, 's': 0.463, 'd': 8.316, 'tot': 9.486}, {'p': 3.388, 's': 1.576, 'd': 0.0, 'tot': 4.964}, {'p': 3.365, 's': 1.582, 'd': 0.0, 'tot': 4.947}, {'p': 3.388, 's': 1.576, 'd': 0.0, 'tot': 4.964}, {'p': 3.365, 's': 1.582, 'd': 0.0, 'tot': 4.947}) self.assertAlmostEqual(outcar.magnetization, expected_mag, 5, "Wrong magnetization read from Outcar") self.assertAlmostEqual(outcar.charge, expected_chg, 5, "Wrong charge read from Outcar") self.assertFalse(outcar.is_stopped) self.assertEqual(outcar.run_stats, {'System time (sec)': 0.938, 'Total CPU time used (sec)': 545.142, 'Elapsed time (sec)': 546.709, 'Maximum memory used (kb)': 0.0, 'Average memory used (kb)': 0.0, 'User time (sec)': 544.204, 'cores': '8'}) self.assertAlmostEqual(outcar.efermi, 2.0112) self.assertAlmostEqual(outcar.nelect, 44.9999991) self.assertAlmostEqual(outcar.total_mag, 0.9999998) self.assertIsNotNone(outcar.as_dict()) self.assertFalse(outcar.lepsilon) filepath = os.path.join(test_dir, 'OUTCAR.stopped') outcar = Outcar(filepath) self.assertTrue(outcar.is_stopped) for f in ['OUTCAR.lepsilon', 'OUTCAR.lepsilon.gz']: filepath = os.path.join(test_dir, f) outcar = Outcar(filepath) self.assertTrue(outcar.lepsilon) self.assertAlmostEqual(outcar.dielectric_tensor[0][0], 3.716432) self.assertAlmostEqual(outcar.dielectric_tensor[0][1], -0.20464) self.assertAlmostEqual(outcar.dielectric_tensor[1][2], -0.20464) self.assertAlmostEqual(outcar.dielectric_ionic_tensor[0][0], 0.001419) self.assertAlmostEqual(outcar.dielectric_ionic_tensor[0][2], 0.001419) self.assertAlmostEqual(outcar.dielectric_ionic_tensor[2][2], 0.001419) self.assertAlmostEqual(outcar.piezo_tensor[0][0], 0.52799) self.assertAlmostEqual(outcar.piezo_tensor[1][3], 0.35998) self.assertAlmostEqual(outcar.piezo_tensor[2][5], 0.35997) self.assertAlmostEqual(outcar.piezo_ionic_tensor[0][0], 0.05868) self.assertAlmostEqual(outcar.piezo_ionic_tensor[1][3], 0.06241) self.assertAlmostEqual(outcar.piezo_ionic_tensor[2][5], 0.06242) self.assertAlmostEqual(outcar.born[0][1][2], -0.385) self.assertAlmostEqual(outcar.born[1][2][0], 0.36465)