def setUpClass(cls): cls.bz = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/transp/")) cls.bz_bands = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/bands/")) cls.bz_up = BoltztrapAnalyzer.from_files(os.path.join( test_dir, "boltztrap/dos_up/"), dos_spin=1) cls.bz_dw = BoltztrapAnalyzer.from_files(os.path.join( test_dir, "boltztrap/dos_dw/"), dos_spin=-1)
def setUpClass(cls): cls.bz = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/transp/")) cls.bz_bands = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/bands/")) cls.bz_up = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/dos_up/"), dos_spin=1) cls.bz_dw = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/dos_dw/"), dos_spin=-1) cls.bz_fermi = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/fermi/"))
def setUp(self): self.bz = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/transp/")) self.bz_bands = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/bands/")) self.bz_up = BoltztrapAnalyzer.from_files(os.path.join( test_dir, "boltztrap/dos_up/"), dos_spin=1) self.bz_dw = BoltztrapAnalyzer.from_files(os.path.join( test_dir, "boltztrap/dos_dw/"), dos_spin=-1) self.bz_fermi = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/fermi/"))
def _update_material(self, m_id, doc): """ Update a material document based on a new task Args: m_id (int): material_id for material document to update doc (dict): a JSON-like Boltztrap document """ bta = BoltztrapAnalyzer.from_dict(doc) d = {} d["zt"] = bta.get_extreme("zt") d["pf"] = bta.get_extreme("power factor") d["seebeck"] = bta.get_extreme("seebeck") d["conductivity"] = bta.get_extreme("conductivity") d["kappa_max"] = bta.get_extreme("kappa") d["kappa_min"] = bta.get_extreme("kappa", maximize=False) self._materials.update_one({"material_id": m_id}, {"$set": { "transport": d }}) self._materials.update_one( {"material_id": m_id}, {"$push": { "_boltztrapbuilder.all_object_ids": doc["_id"] }})
def setUp(self): self.bz = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/transp/")) self.bz_bands = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/bands/")) self.bz_up = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/dos_up/"), dos_spin=1) self.bz_dw = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/dos_dw/"), dos_spin=-1) self.bz_fermi = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/fermi/")) with open(os.path.join(test_dir, "Cu2O_361_bandstructure.json"), "rt") as f: d = json.load(f) self.bs = BandStructure.from_dict(d) self.btr = BoltztrapRunner(self.bs, 1)
def boltz_run(vrun=""): """ Helper function to run and store Bolztrap Please note high denske k-point mesh is needed The automatic k-point convergene in JARVIS-DFT is generally good enough Args: vrun: path to vasprun.xml Returns: BoltztrapAnalyzer object """ if which("x_trans") is None or which("BoltzTraP") is None: print("Please install BoltzTrap") v = Vasprun(vrun) kp = vrun.replace("vasprun.xml", "KPOINTS") out = vrun.replace("vasprun.xml", "OUTCAR") for line in open(out, "r"): if "NELECT" in line: nelect = float(line.split()[2]) bs = v.get_band_structure(kp, line_mode=False) brun = BoltztrapRunner(bs, nelect) path = vrun.split("vasprun.xml")[0] folder = str(path) + str("/boltztrap") out_trans = str(folder) + str("/boltztrap.outputtrans") if not os.path.exists(out_trans): brun.run(path_dir=path) print("doesnt exist", out_trans) bana = BoltztrapAnalyzer.from_files(folder) return bana
def run_task(self, fw_spec): additional_fields = self.get("additional_fields", {}) # pass the additional_fields first to avoid overriding BoltztrapAnalyzer items d = additional_fields.copy() btrap_dir = os.path.join(os.getcwd(), "boltztrap") d["boltztrap_dir"] = btrap_dir bta = BoltztrapAnalyzer.from_files(btrap_dir) d.update(bta.as_dict()) d["scissor"] = bta.intrans["scissor"] # trim the output for x in ['cond', 'seebeck', 'kappa', 'hall', 'mu_steps', 'mu_doping', 'carrier_conc']: del d[x] if not self.get("hall_doping"): del d["hall_doping"] bandstructure_dir = os.getcwd() d["bandstructure_dir"] = bandstructure_dir # add the structure v, o = get_vasprun_outcar(bandstructure_dir, parse_eigen=False, parse_dos=False) structure = v.final_structure d["structure"] = structure.as_dict() d["formula_pretty"] = structure.composition.reduced_formula d.update(get_meta_from_structure(structure)) # add the spacegroup sg = SpacegroupAnalyzer(Structure.from_dict(d["structure"]), 0.1) d["spacegroup"] = {"symbol": sg.get_space_group_symbol(), "number": sg.get_space_group_number(), "point_group": sg.get_point_group_symbol(), "source": "spglib", "crystal_system": sg.get_crystal_system(), "hall": sg.get_hall()} d["created_at"] = datetime.utcnow() db_file = env_chk(self.get('db_file'), fw_spec) if not db_file: del d["dos"] with open(os.path.join(btrap_dir, "boltztrap.json"), "w") as f: f.write(json.dumps(d, default=DATETIME_HANDLER)) else: mmdb = VaspCalcDb.from_db_file(db_file, admin=True) # dos gets inserted into GridFS dos = json.dumps(d["dos"], cls=MontyEncoder) fsid, compression = mmdb.insert_gridfs(dos, collection="dos_boltztrap_fs", compress=True) d["dos_boltztrap_fs_id"] = fsid del d["dos"] mmdb.db.boltztrap.insert(d)
def setUpClass(cls): cls.bz = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/transp/")) cls.bz_bands = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/bands/")) cls.bz_up = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/dos_up/"), dos_spin=1) cls.bz_dw = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/dos_dw/"), dos_spin=-1) cls.bz_fermi = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/fermi/")) with open(os.path.join(test_dir, "Cu2O_361_bandstructure.json"), "rt") as f: d = json.load(f) cls.bs = BandStructure.from_dict(d) cls.btr = BoltztrapRunner(cls.bs, 1) warnings.simplefilter("ignore")
def test_plots(self): bz = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/transp/")) plotter = BoltztrapPlotter(bz) plotter.plot_seebeck_eff_mass_mu().close() plotter.plot_complexity_factor_mu().close() plotter.plot_conductivity_mu().close() plotter.plot_power_factor_mu().close() plotter.plot_zt_mu().close() plotter.plot_dos().close()
def get_interpolated_dos(self, mat): nelect = mat["calc_settings"]["nelect"] bs_dict = mat["bandstructure"]["uniform_bs"] bs_dict["structure"] = mat['structure'] bs = BandStructure.from_dict(bs_dict) if bs.is_spin_polarized: with ScratchDir("."): BoltztrapRunner(bs=bs, nelec=nelect, run_type="DOS", dos_type="TETRA", spin=1, timeout=60).run(path_dir=os.getcwd()) an_up = BoltztrapAnalyzer.from_files("boltztrap/", dos_spin=1) with ScratchDir("."): BoltztrapRunner(bs=bs, nelec=nelect, run_type="DOS", dos_type="TETRA", spin=-1, timeout=60).run(path_dir=os.getcwd()) an_dw = BoltztrapAnalyzer.from_files("boltztrap/", dos_spin=-1) cdos = an_up.get_complete_dos(bs.structure, an_dw) else: with ScratchDir("."): BoltztrapRunner(bs=bs, nelec=nelect, run_type="DOS", dos_type="TETRA", timeout=60).run(path_dir=os.getcwd()) an = BoltztrapAnalyzer.from_files("boltztrap/") cdos = an.get_complete_dos(bs.structure) return cdos
def _update_material(self, m_id, doc): """ Update a material document based on a new task Args: m_id: (int) material_id for material document to update doc: a JSON-like Boltztrap document """ bta = BoltztrapAnalyzer.from_dict(doc) d = {} d["zt"] = bta.get_extreme("zt") d["pf"] = bta.get_extreme("power factor") d["seebeck"] = bta.get_extreme("seebeck") d["conductivity"] = bta.get_extreme("conductivity") d["kappa_max"] = bta.get_extreme("kappa") d["kappa_min"] = bta.get_extreme("kappa", maximize=False) self._materials.update_one({"material_id": m_id}, {"$set": {"transport": d}}) self._materials.update_one({"material_id": m_id}, {"$push": {"_boltztrapbuilder.all_object_ids": doc["_id"]}}) self._materials.update_one({"material_id": m_id}, {"$set": {"_boltztrapbuilder.blessed_object_id": doc["_id"]}})
from pymatgen.io.vasp.outputs import Vasprun from pymatgen.electronic_structure.plotter import BSPlotter, DosPlotter, BSDOSPlotter, BoltztrapPlotter from pymatgen.electronic_structure.core import Spin, Orbital, OrbitalType from pymatgen.electronic_structure.dos import Dos from pymatgen.electronic_structure.boltztrap import BoltztrapRunner, BoltztrapAnalyzer v_dos = Vasprun("vasprun.xml") bs = v_dos.get_band_structure() nelect = v_dos.parameters['NELECT'] vbm = int(nelect / 2 - 1) BoltztrapRunner(bs=bs, nelec=nelect, lpfac=100, run_type='FERMI', band_nb=24, cond_band=False, spin=1).run(path_dir='./b24/') an = BoltztrapAnalyzer.from_files("b24/boltztrap/") BoltztrapPlotter.plot_fermi_surface(an.fermi_surface_data, bs.structure, cbm=False, energy_levels=[-0.01])
while i < len(bs._kpoints): if any( numpy.array_equal(bs._kpoints[i].frac_coords, kpt) for kpt in existkpoints): for band in bs._bands[Spin.up]: band.pop(i) bs._kpoints.pop(i) else: existkpoints.append(bs._kpoints[i].frac_coords) i = i + 1 nelec = 38 x = BoltztrapRunner(bs, nelec, dos_type="HISTO", energy_grid=0.005, lpfac=10, type="BOLTZ", band_nb=None, tauref=0, tauexp=0, tauen=0, soc=False) #goes to nonetype... band structure objects have a ._structure attribute but not .structure outfile = x.run(prev_sigma=None, path_dir=os.getcwd(), convergence=True) y = BoltztrapAnalyzer.from_files(outfile) #adjusted doping levels in boltztrap.outputtrans file in CoSb3 folder EffMass = y.get_eig_average_eff_mass_tensor(temperature=300, doping=1e+18)
def boltztrap(tmax=1001, tstep=50, tmin=None, doping=np.logspace(18, 21, 17), ke_mode='boltzmann', vasprun='vasprun.xml', kpoints=None, relaxation_time=1e-14, lpfac=10, run=True, analyse=True, output='boltztrap.hdf5', **kwargs): """Runs BoltzTraP from a VASP density of states (DoS). Runs quicker and more robustly than the pymatgen from_files version, and outputs an hdf5 file. Note: BoltzTraP can be a fickle friend, so if you're getting errors, it may be worth reinstalling or trying on a different machine. Arguments --------- tmax : float, optional maximum temperature in K. Default: 1000. tstep : float, optional temperature step in K. Default: 50. tmin : float, optional minimum temperature in K. This does not reduce how many temperatures are run in BoltzTraP, only how many are saved to hdf5. Default: tstep. doping : array-like, optional doping concentrations in cm-1. Default: np.logspace(18, 21, 17). k_mode : str, optional method for calculating the electronic thermal conductivity. Options: boltzmann (default): standard boltztrap method. Madsen and Singh, Comput. Phys. Commun. 2006, 175, 67. wiedemann: Wiedemann-Franz law with constant L = 2.44E-8. Franz and Wiedemann, Ann. Phys. 1853, 165, 497. snyder: Wiedemann-Franz law, with L varying with Seebeck. Kim et al., APL Mat. 2015, 3, 041506. vasprun : str, optional path to vasprun. Default: vasprun.xml. kpoints : str, optional path to KPOINTS file if there are zero-weighted k-points. Default: KPOINTS. relaxation_time : float, optional charge carrier relaxation time. Default: 1e-14. lpfac : int, optional DoS interpolation factor. Default: 10. run : bool, optional run BoltzTraP. Default: True. analyse : bool, optional analyse BoltzTraP. Default: True. output : str, optional output hdf5 filename. Default: boltztrap.hdf5. kwargs passed to pymatgen.electronic.structure.boltztrap.BoltztrapRunner. Returns ------- None instead prints to hdf5 (see below). hdf5 File Contents ------------------ average_eff_mass : dict the charge carrier effective mass in units of m_e, taking into account all bands, as opposed to the single parabolic band model. Data is a dictionary with an array each for n and p doping, of shape (temperatures, concentrations, 3, 3). conductivity : dict electric conductivity in S m-1. Data is a dictionary with an array each for n and p doping, of shape (temperatures, concentrations, 3, 3). doping : array-like carrier concentration in cm-1. Identical to input. electronic_thermal_conductivity : dict electronic thermal conductivity in W m-1 K-1. Data is a dictionary with an array each for n and p doping, of shape (temperatures, concentrations, 3, 3). fermi_level : dict fermi level at different temperatures in units of eV. Data is a dictionary with an array each for n and p doping, of shape (temperatures, concentrations). power_factor : dict power factor in W m-1 K-2. Data is a dictionary with an array each for n and p doping, of shape (temperatures, concentrations, 3, 3). seebeck : dict Seebeck coefficient in muV K-1. Data is a dictionary with an array each for n and p doping, of shape (temperatures, concentrations, 3, 3). temperature : numpy array temperatures in K. meta : dict metadata: interpolation_factor : int lpfac. ke_mode : str as input. relaxation_time : float as input. soc : bool spin-orbit coupling calculation. units : dict units of each property above. """ import h5py import os from pymatgen.electronic_structure.boltztrap \ import BoltztrapRunner, BoltztrapAnalyzer, BoltztrapError from pymatgen.io.vasp.outputs import Vasprun from scipy import constants # check inputs for name, value in zip(['run', 'analyse'], [run, analyse]): assert isinstance(value, bool), '{} must be True or False'.format(name) ke_mode = ke_mode.lower() ke_modes = ['boltzmann', 'wiedemann', 'snyder'] assert ke_mode in ke_modes, 'ke_mode must be {} or {}.'.format( ', '.join(ke_modes[:-1]), ke_modes[-1]) tmax += tstep tmin = tstep if tmin is None else tmin temperature = np.arange(tmin, tmax, tstep) if run: # run boltztrap from vasprun.xml -> boltztrap directory doping = np.array(doping) vr = Vasprun(vasprun, parse_potcar_file=False) soc = vr.as_dict()['input']['parameters']['LSORBIT'] try: bs = vr.get_band_structure(line_mode=False) nelect = vr.parameters['NELECT'] btr = BoltztrapRunner(bs, nelect, doping=list(doping), tmax=tmax, tgrid=tstep, soc=soc, lpfac=lpfac, **kwargs) print('Running Boltztrap...', end='') btr_dir = btr.run(path_dir='.') print('Done.') except BoltztrapError: bs = vr.get_band_structure(line_mode=True, kpoints_filename=kpoints) nelect = vr.parameters['NELECT'] btr = BoltztrapRunner(bs, nelect, doping=list(doping), tmax=tmax, tgrid=tstep, soc=soc, lpfac=lpfac, **kwargs) btr_dir = btr.run(path_dir='.') print('Done.') """ Detects whether the BoltzTraP build on this computer writes the doping concentrations correctly, and if it doesn't, writes them. """ with open('boltztrap/boltztrap.outputtrans', 'r') as f: line = f.readlines()[-2] if len(line) >= 23 and line[:23] == ' Calling FermiIntegrals': with open(os.path.join(btr_dir, 'boltztrap.outputtrans'), 'a') as f: for i, x in enumerate(np.concatenate((doping, -doping))): f.write( 'Doping level number {} n = {} carriers/cm3\n'.format( i, x)) else: btr_dir = 'boltztrap' if analyse: # run boltztrap from boltztrap directory -> hdf5 file print('Analysing Boltztrap...', end='') bta = BoltztrapAnalyzer.from_files(btr_dir) print('Done.') data = { 'average_eff_mass': {}, 'conductivity': {}, 'doping': doping, 'electronic_thermal_conductivity': {}, 'power_factor': {}, 'seebeck': {}, 'temperature': temperature, 'meta': { 'units': { 'average_eff_mass': 'm_e', 'conductivity': 'S m-1', 'doping': 'cm-1', 'electronic_thermal_conductivity': 'W m-1 K-1', 'fermi_level': 'eV', 'power_factor': 'W m-1 K-2', 'seebeck': 'muV K-1', 'temperature': 'K' }, 'interpolation_factor': lpfac, 'ke_mode': ke_mode, 'relaxation_time': relaxation_time, 'soc': soc } } # load data print('Calculating transport...', end='') c = bta._cond_doping dp = bta.doping e = constants.e f = bta.mu_doping k = bta._kappa_doping me = constants.m_e s = bta._seebeck_doping # calculate transport properties for d in ['n', 'p']: c[d] = np.array([c[d][t] for t in temperature]) dp[d] = np.array(dp[d]) k[d] = np.array([k[d][t] for t in temperature]) f[d] = np.array([f[d][t] for t in temperature]) s[d] = np.array([s[d][t] for t in temperature]) data['average_eff_mass'][d] = np.linalg.inv(c[d]) \ * dp[d][None, :, None, None] \ * 1e6 * e ** 2 / me data['conductivity'][d] = np.multiply(c[d], relaxation_time) data['seebeck'][d] = np.multiply(s[d], 1e6) data['power_factor'][d] = tp.calculate.power_factor( data['conductivity'][d], data['seebeck'][d]) if ke_mode == 'boltztrap': data['electronic_thermal_conductivity'][d] = \ k[d] * relaxation_time \ - data['power_factor'][d] * temperature[:,None,None,None] else: if ke_mode == 'wiedemann': L = 2.44E-8 else: L = (1.5 + np.exp(-np.abs(data['seebeck'][d]) / 116)) * 1e-8 data['electronic_thermal_conductivity'][d] = \ L * data['conductivity'][d] * temperature[:,None,None,None] data['fermi_level'] = f print('Done.') tp.data.save.hdf5(data, output) return
def boltztrap(tmax=1000, tstep=10, doping=np.logspace(18, 21, 100), vasprun='vasprun.xml', soc=False, zero_weighted=False, kpoints=None, lpfac=10, relaxation_time=1e-14, run=True, analyse=True, output='boltztrap.hdf5'): """Runs BoltzTraP Runs quicker than the pymatgen from_files version. Also writes to a hdf5 file. Minimum temperature is always 200 K, because BoltzTraP. Note: BoltzTraP can be a fickle friend, so if you're getting errors, it may be worth reinstalling or trying on a different machine. Testing with a small number of temperature/ doping combinations is also recommended Arguments: tmax : float, optional maximum temperature in K. Default: 1000. tstep : float, optional temperature step in K. Default: 10. doping : array-like, optional doping concentrations in cm-1. Default: np.logspace(18, 21, 101). vasprun : str, optional path to vasprun. Default: vasprun.xml. soc : bool, optional spin orbit coupling used. Default: False. zero_weighted : bool, optional zero weighted kpoints used. Default: False. kpoints : str, optional path to KPOINTS file if zero_weighted. Default: KPOINTS. lpfac : int, optional interpolate the DoS k-points by lpfac times. Default: 10. relaxation_time : float, optional charge carrier relaxation time. Default: 1e-14. run : bool, optional run BoltzTraP. Default: True. analyse : bool, optional analyse BoltzTraP. Default: True. output : str, optional output hdf5 filename. Default: boltztrap.hdf5. """ import h5py import os from multiprocessing import Pool from pymatgen.electronic_structure.boltztrap import BoltztrapRunner, BoltztrapAnalyzer from pymatgen.io.vasp.outputs import Vasprun from scipy import constants for v, w in zip(['tmax', 'tstep', 'lpfac', 'relaxation_time'], [tmax, tstep, lpfac, relaxation_time]): assert isinstance(w, (float, int)), '{} must be a number'.forpmat(v) for v, w in zip(['soc,', 'zero_weighted', 'run', 'analyse'], [soc, zero_weighted, run, analyse]): assert isinstance(w, bool), '{} must be True or False'.forpmat(v) temperature = np.arange(200, tmax, tstep) if run: # run boltztrap from vasprun.xml -> boltztrap directory doping = np.array(doping) vr = Vasprun(vasprun) bs = vr.get_band_structure(line_mode=zero_weighted, kpoints_filename=kpoints) nelect = vr.parameters['NELECT'] btr = BoltztrapRunner(bs, nelect, doping=list(doping), tmax=tmax, tgrid=tstep, lpfac=lpfac) print('Running Boltztrap...', end='') btr_dir = btr.run(path_dir='.') print('Done.') else: btr_dir = 'boltztrap' if analyse: # run boltztrap from boltztrap directory -> hdf5 file print('Analysing Boltztrap...', end='') bta = BoltztrapAnalyzer.from_files(btr_dir) print('Done.') data = { 'average_eff_mass': {}, 'conductivity': {}, 'doping': doping, 'power_factor': {}, 'seebeck': {}, 'temperature': temperature, 'thermal_conductivity': {} } # load data print('Calculating transport...', end='') c = bta._cond_doping dp = bta.doping e = constants.e f = bta.mu_doping k = bta._kappa_doping me = constants.m_e s = bta._seebeck_doping # calculate transport properties for d in ['n', 'p']: c[d] = np.array([c[d][t] for t in temperature]) dp[d] = np.array(dp[d]) k[d] = np.array([k[d][t] for t in temperature]) f[d] = np.array([f[d][t] for t in temperature]) s[d] = np.array([s[d][t] for t in temperature]) data['average_eff_mass'][d] = np.linalg.inv(c[d]) \ * dp[d][None, :, None, None] \ * 1e6 * e ** 2 / me data['conductivity'][d] = np.multiply(c[d], relaxation_time) data['seebeck'][d] = np.multiply(s[d], 1e6) data['power_factor'][d] = tp.calculate.power_factor(c[d], s[d]) data['thermal_conductivity'][d] = (k[d] - s[d] ** 2 * c[d] \ * temperature[:,None,None,None]) \ * relaxation_time data['fermi_level'] = f print('Done.') # write data datafile = h5py.File(output, 'w') for key in data.keys(): if isinstance(data[key], dict): group = datafile.create_group(key) for k in data[key].keys(): group[k] = data[key][k] else: datafile.create_dataset(key, np.shape(data[key]), data=data[key]) datafile.close() return
def boltztrap(tmax=1001, tstep=50, doping=np.logspace(18, 21, 17), vasprun='vasprun.xml', zero_weighted=False, kpoints=None, relaxation_time=1e-14, run=True, analyse=True, output='boltztrap.hdf5', **kwargs): """Runs BoltzTraP Runs quicker than the pymatgen from_files version. Also writes to a hdf5 file. Minimum temperature is 200 K or tstep, whichever is larger. Note: BoltzTraP can be a fickle friend, so if you're getting errors, it may be worth reinstalling or trying on a different machine. Testing with a small number of temperature/ doping combinations is also recommended. Arguments --------- tmax : float, optional maximum temperature in K. Default: 1000. tstep : float, optional temperature step in K. Default: 10. doping : array-like, optional doping concentrations in cm-1. Default: np.logspace(18, 21, 101). vasprun : str, optional path to vasprun. Default: vasprun.xml. zero_weighted : bool, optional zero weighted kpoints used. Default: False. kpoints : str, optional path to KPOINTS file if zero_weighted. Default: KPOINTS. relaxation_time : float, optional charge carrier relaxation time. Default: 1e-14. run : bool, optional run BoltzTraP. Default: True. analyse : bool, optional analyse BoltzTraP. Default: True. output : str, optional output hdf5 filename. Default: boltztrap.hdf5. **kwargs passed to pymatgen.electronic.structure.boltztrap.BoltztrapRunner. Recommended arguments include: soc : bool, optional spin orbit coupling. Default: False. lpfac : int, optional interpolation factor. Default: 10. timeout : float, optional Convergence time limit in seconds. Default: 7200. """ import h5py import os from pymatgen.electronic_structure.boltztrap import BoltztrapRunner, BoltztrapAnalyzer from pymatgen.io.vasp.outputs import Vasprun from scipy import constants # check inputs for name, value in zip(['zero_weighted', 'run', 'analyse'], [zero_weighted, run, analyse]): assert isinstance(value, bool), '{} must be True or False'.format(name) tmax += tstep tmin = 200 if tstep > tmin: tmin = tstep temperature = np.arange(tmin, tmax, tstep) if run: # run boltztrap from vasprun.xml -> boltztrap directory doping = np.array(doping) vr = Vasprun(vasprun) bs = vr.get_band_structure(line_mode=zero_weighted, kpoints_filename=kpoints) nelect = vr.parameters['NELECT'] btr = BoltztrapRunner(bs, nelect, doping=list(doping), tmax=tmax, tgrid=tstep, **kwargs) print('Running Boltztrap...', end='') btr_dir = btr.run(path_dir='.') print('Done.') """ Detects whether the BoltzTraP build on this computer writes the doping concentrations correctly, and if it doesn't, writes them. """ with open('boltztrap/boltztrap.outputtrans', 'r') as f: line = f.readlines()[-2] if len(line) >= 23 and line[:23] == ' Calling FermiIntegrals': with open(os.path.join(btr_dir, 'boltztrap.outputtrans'), 'a') as f: for i, x in enumerate(np.concatenate((doping, -doping))): f.write( 'Doping level number {} n = {} carriers/cm3\n'.format( i, x)) else: btr_dir = 'boltztrap' if analyse: # run boltztrap from boltztrap directory -> hdf5 file print('Analysing Boltztrap...', end='') bta = BoltztrapAnalyzer.from_files(btr_dir) print('Done.') data = { 'average_eff_mass': {}, 'conductivity': {}, 'doping': doping, 'power_factor': {}, 'seebeck': {}, 'temperature': temperature, 'thermal_conductivity': {} } # load data print('Calculating transport...', end='') c = bta._cond_doping dp = bta.doping e = constants.e f = bta.mu_doping k = bta._kappa_doping me = constants.m_e s = bta._seebeck_doping # calculate transport properties for d in ['n', 'p']: c[d] = np.array([c[d][t] for t in temperature]) dp[d] = np.array(dp[d]) k[d] = np.array([k[d][t] for t in temperature]) f[d] = np.array([f[d][t] for t in temperature]) s[d] = np.array([s[d][t] for t in temperature]) data['average_eff_mass'][d] = np.linalg.inv(c[d]) \ * dp[d][None, :, None, None] \ * 1e6 * e ** 2 / me data['conductivity'][d] = np.multiply(c[d], relaxation_time) data['seebeck'][d] = np.multiply(s[d], 1e6) data['power_factor'][d] = tp.calculate.power_factor(c[d], s[d]) data['thermal_conductivity'][d] = (k[d] - s[d] ** 2 * c[d] \ * temperature[:,None,None,None]) \ * relaxation_time data['fermi_level'] = f print('Done.') tp.data.save.hdf5(data, output) return
def run_task(self, fw_spec): # import here to prevent import errors in bigger MPCollab # get the band structure and nelect from files """ prev_dir = get_loc(fw_spec['prev_vasp_dir']) vasprun_loc = zpath(os.path.join(prev_dir, 'vasprun.xml')) kpoints_loc = zpath(os.path.join(prev_dir, 'KPOINTS')) vr = Vasprun(vasprun_loc) bs = vr.get_band_structure(kpoints_filename=kpoints_loc) """ filename = get_slug( 'JOB--' + fw_spec['mpsnl'].structure.composition.reduced_formula + '--' + fw_spec['task_type']) with open(filename, 'w+') as f: f.write('') # get the band structure and nelect from DB block_part = get_block_part(fw_spec['prev_vasp_dir']) db_dir = os.environ['DB_LOC'] assert isinstance(db_dir, object) db_path = os.path.join(db_dir, 'tasks_db.json') with open(db_path) as f: creds = json.load(f) connection = MongoClient(creds['host'], creds['port']) tdb = connection[creds['database']] tdb.authenticate(creds['admin_user'], creds['admin_password']) props = { "calculations": 1, "task_id": 1, "state": 1, "pseudo_potential": 1, "run_type": 1, "is_hubbard": 1, "hubbards": 1, "unit_cell_formula": 1 } m_task = tdb.tasks.find_one({"dir_name": block_part}, props) if not m_task: time.sleep( 60) # only thing to think of is wait for DB insertion(?) m_task = tdb.tasks.find_one({"dir_name": block_part}, props) if not m_task: raise ValueError( "Could not find task with dir_name: {}".format(block_part)) if m_task['state'] != 'successful': raise ValueError( "Cannot run Boltztrap; parent job unsuccessful") nelect = m_task['calculations'][0]['input']['parameters']['NELECT'] bs_id = m_task['calculations'][0]['band_structure_fs_id'] print bs_id, type(bs_id) fs = gridfs.GridFS(tdb, 'band_structure_fs') bs_dict = json.loads(fs.get(bs_id).read()) bs_dict['structure'] = m_task['calculations'][0]['output'][ 'crystal'] bs = BandStructure.from_dict(bs_dict) print("find previous run with block_part {}".format(block_part)) print 'Band Structure found:', bool(bs) print(bs.as_dict()) print("nelect: {}".format(nelect)) # run Boltztrap doping = [] for d in [1e16, 1e17, 1e18, 1e19, 1e20]: doping.extend([1 * d, 2.5 * d, 5 * d, 7.5 * d]) doping.append(1e21) runner = BoltztrapRunner(bs, nelect, doping=doping) dir = runner.run(path_dir=os.getcwd()) # put the data in the database bta = BoltztrapAnalyzer.from_files(dir) # 8/21/15 - Anubhav removed fs_id (also see line further below, ted['boltztrap_full_fs_id'] ...) # 8/21/15 - this is to save space in MongoDB, as well as non-use of full Boltztrap output (vs rerun) """ data = bta.as_dict() data.update(get_meta_from_structure(bs._structure)) data['snlgroup_id'] = fw_spec['snlgroup_id'] data['run_tags'] = fw_spec['run_tags'] data['snl'] = fw_spec['mpsnl'] data['dir_name_full'] = dir data['dir_name'] = get_block_part(dir) data['task_id'] = m_task['task_id'] del data['hall'] # remove because it is too large and not useful fs = gridfs.GridFS(tdb, "boltztrap_full_fs") btid = fs.put(json.dumps(jsanitize(data))) """ # now for the "sanitized" data ted = bta.as_dict() del ted['seebeck'] del ted['hall'] del ted['kappa'] del ted['cond'] # ted['boltztrap_full_fs_id'] = btid ted['snlgroup_id'] = fw_spec['snlgroup_id'] ted['run_tags'] = fw_spec['run_tags'] ted['snl'] = fw_spec['mpsnl'].as_dict() ted['dir_name_full'] = dir ted['dir_name'] = get_block_part(dir) ted['task_id'] = m_task['task_id'] ted['pf_doping'] = bta.get_power_factor(output='tensor', relaxation_time=self.TAU) ted['zt_doping'] = bta.get_zt(output='tensor', relaxation_time=self.TAU, kl=self.KAPPAL) ted['pf_eigs'] = self.get_eigs(ted, 'pf_doping') ted['pf_best'] = self.get_extreme(ted, 'pf_eigs') ted['pf_best_dope18'] = self.get_extreme(ted, 'pf_eigs', max_didx=3) ted['pf_best_dope19'] = self.get_extreme(ted, 'pf_eigs', max_didx=4) ted['zt_eigs'] = self.get_eigs(ted, 'zt_doping') ted['zt_best'] = self.get_extreme(ted, 'zt_eigs') ted['zt_best_dope18'] = self.get_extreme(ted, 'zt_eigs', max_didx=3) ted['zt_best_dope19'] = self.get_extreme(ted, 'zt_eigs', max_didx=4) ted['seebeck_eigs'] = self.get_eigs(ted, 'seebeck_doping') ted['seebeck_best'] = self.get_extreme(ted, 'seebeck_eigs') ted['seebeck_best_dope18'] = self.get_extreme(ted, 'seebeck_eigs', max_didx=3) ted['seebeck_best_dope19'] = self.get_extreme(ted, 'seebeck_eigs', max_didx=4) ted['cond_eigs'] = self.get_eigs(ted, 'cond_doping') ted['cond_best'] = self.get_extreme(ted, 'cond_eigs') ted['cond_best_dope18'] = self.get_extreme(ted, 'cond_eigs', max_didx=3) ted['cond_best_dope19'] = self.get_extreme(ted, 'cond_eigs', max_didx=4) ted['kappa_eigs'] = self.get_eigs(ted, 'kappa_doping') ted['kappa_best'] = self.get_extreme(ted, 'kappa_eigs', maximize=False) ted['kappa_best_dope18'] = self.get_extreme(ted, 'kappa_eigs', maximize=False, max_didx=3) ted['kappa_best_dope19'] = self.get_extreme(ted, 'kappa_eigs', maximize=False, max_didx=4) try: from mpcollab.thermoelectrics.boltztrap_TE import BoltzSPB bzspb = BoltzSPB(ted) maxpf_p = bzspb.get_maximum_power_factor( 'p', temperature=0, tau=1E-14, ZT=False, kappal=0.5, otherprops=('get_seebeck_mu_eig', 'get_conductivity_mu_eig', 'get_thermal_conductivity_mu_eig', 'get_average_eff_mass_tensor_mu')) maxpf_n = bzspb.get_maximum_power_factor( 'n', temperature=0, tau=1E-14, ZT=False, kappal=0.5, otherprops=('get_seebeck_mu_eig', 'get_conductivity_mu_eig', 'get_thermal_conductivity_mu_eig', 'get_average_eff_mass_tensor_mu')) maxzt_p = bzspb.get_maximum_power_factor( 'p', temperature=0, tau=1E-14, ZT=True, kappal=0.5, otherprops=('get_seebeck_mu_eig', 'get_conductivity_mu_eig', 'get_thermal_conductivity_mu_eig', 'get_average_eff_mass_tensor_mu')) maxzt_n = bzspb.get_maximum_power_factor( 'n', temperature=0, tau=1E-14, ZT=True, kappal=0.5, otherprops=('get_seebeck_mu_eig', 'get_conductivity_mu_eig', 'get_thermal_conductivity_mu_eig', 'get_average_eff_mass_tensor_mu')) ted['zt_best_finemesh'] = {'p': maxzt_p, 'n': maxzt_n} ted['pf_best_finemesh'] = {'p': maxpf_p, 'n': maxpf_n} except: import traceback traceback.print_exc() print 'COULD NOT GET FINE MESH DATA' # add is_compatible mpc = MaterialsProjectCompatibility("Advanced") try: func = m_task["pseudo_potential"]["functional"] labels = m_task["pseudo_potential"]["labels"] symbols = ["{} {}".format(func, label) for label in labels] parameters = { "run_type": m_task["run_type"], "is_hubbard": m_task["is_hubbard"], "hubbards": m_task["hubbards"], "potcar_symbols": symbols } entry = ComputedEntry(Composition(m_task["unit_cell_formula"]), 0.0, 0.0, parameters=parameters, entry_id=m_task["task_id"]) ted["is_compatible"] = bool(mpc.process_entry(entry)) except: traceback.print_exc() print 'ERROR in getting compatibility, task_id: {}'.format( m_task["task_id"]) ted["is_compatible"] = None tdb.boltztrap.insert(jsanitize(ted)) update_spec = { 'prev_vasp_dir': fw_spec['prev_vasp_dir'], 'boltztrap_dir': os.getcwd(), 'prev_task_type': fw_spec['task_type'], 'mpsnl': fw_spec['mpsnl'].as_dict(), 'snlgroup_id': fw_spec['snlgroup_id'], 'run_tags': fw_spec['run_tags'], 'parameters': fw_spec.get('parameters') } return FWAction(update_spec=update_spec)
def setUp(self): self.bz = BoltztrapAnalyzer.from_files(os.path.join(test_dir, "boltztrap"))
def setUp(self): bz = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap/transp/")) self.plotter = BoltztrapPlotter(bz) warnings.simplefilter("ignore")
#bs = mp.get_bandstructure_by_material_id('mp-804') i = 0 while i < len(bs._kpoints): for band in bs._bands[Spin.up]: band.pop(i) bs._kpoints.pop(i) i = i + 1 existkpoints = [] i = 0 while i < len(bs._kpoints): if any(numpy.array_equal(bs._kpoints[i].frac_coords, kpt) for kpt in existkpoints): for band in bs._bands[Spin.up]: band.pop(i) bs._kpoints.pop(i) else: existkpoints.append(bs._kpoints[i].frac_coords) i = i + 1 nelec = 38 x = BoltztrapRunner(bs, nelec, dos_type="HISTO", energy_grid=0.005, lpfac=10, type="BOLTZ", band_nb=None, tauref=0, tauexp=0, tauen=0, soc=False) #goes to nonetype... band structure objects have a ._structure attribute but not .structure outfile = x.run(prev_sigma=None, path_dir=os.getcwd(), convergence=True) y = BoltztrapAnalyzer.from_files(outfile) #adjusted doping levels in boltztrap.outputtrans file in CoSb3 folder EffMass = y.get_eig_average_eff_mass_tensor(temperature=300, doping=1e+18)
def setUp(self): bz = BoltztrapAnalyzer.from_files( os.path.join(PymatgenTest.TEST_FILES_DIR, "boltztrap/transp/")) self.plotter = BoltztrapPlotter(bz) warnings.simplefilter("ignore")
def run_task(self, fw_spec): # get the band structure and nelect from files """ prev_dir = get_loc(fw_spec['prev_vasp_dir']) vasprun_loc = zpath(os.path.join(prev_dir, 'vasprun.xml')) kpoints_loc = zpath(os.path.join(prev_dir, 'KPOINTS')) vr = Vasprun(vasprun_loc) bs = vr.get_band_structure(kpoints_filename=kpoints_loc) """ # get the band structure and nelect from DB block_part = get_block_part(fw_spec['prev_vasp_dir']) db_dir = os.environ['DB_LOC'] assert isinstance(db_dir, object) db_path = os.path.join(db_dir, 'tasks_db.json') with open(db_path) as f: creds = json.load(f) connection = MongoClient(creds['host'], creds['port']) tdb = connection[creds['database']] tdb.authenticate(creds['admin_user'], creds['admin_password']) m_task = tdb.tasks.find_one({"dir_name": block_part}, { "calculations": 1, "task_id": 1 }) nelect = m_task['calculations'][0]['input']['parameters']['NELECT'] bs_id = m_task['calculations'][0]['band_structure_fs_id'] print bs_id, type(bs_id) fs = gridfs.GridFS(tdb, 'band_structure_fs') bs_dict = json.loads(fs.get(bs_id).read()) bs_dict['structure'] = m_task['calculations'][0]['output'][ 'crystal'] bs = BandStructure.from_dict(bs_dict) print 'Band Structure found:', bool(bs) print nelect # run Boltztrap runner = BoltztrapRunner(bs, nelect) dir = runner.run(path_dir=os.getcwd()) # put the data in the database bta = BoltztrapAnalyzer.from_files(dir) data = bta.to_dict data.update(get_meta_from_structure(bs._structure)) data['snlgroup_id'] = fw_spec['snlgroup_id'] data['run_tags'] = fw_spec['run_tags'] data['snl'] = fw_spec['mpsnl'] data['dir_name_full'] = dir data['dir_name'] = get_block_part(dir) data['task_id'] = m_task['task_id'] data['hall'] = {} # remove because it is too large and not useful data['hall_doping'] = { } # remove because it is too large and not useful tdb.boltztrap.insert(clean_json(data)) update_spec = { 'prev_vasp_dir': fw_spec['prev_vasp_dir'], 'boltztrap_dir': os.getcwd(), 'prev_task_type': fw_spec['task_type'], 'mpsnl': fw_spec['mpsnl'], 'snlgroup_id': fw_spec['snlgroup_id'], 'run_tags': fw_spec['run_tags'], 'parameters': fw_spec.get('parameters') } return FWAction(update_spec=update_spec)
def setUp(self): self.bz = BoltztrapAnalyzer.from_files( os.path.join(test_dir, "boltztrap"))
def run_task(self, fw_spec): # import here to prevent import errors in bigger MPCollab # get the band structure and nelect from files """ prev_dir = get_loc(fw_spec['prev_vasp_dir']) vasprun_loc = zpath(os.path.join(prev_dir, 'vasprun.xml')) kpoints_loc = zpath(os.path.join(prev_dir, 'KPOINTS')) vr = Vasprun(vasprun_loc) bs = vr.get_band_structure(kpoints_filename=kpoints_loc) """ filename = get_slug( 'JOB--' + fw_spec['mpsnl'].structure.composition.reduced_formula + '--' + fw_spec['task_type']) with open(filename, 'w+') as f: f.write('') # get the band structure and nelect from DB block_part = get_block_part(fw_spec['prev_vasp_dir']) db_dir = os.environ['DB_LOC'] assert isinstance(db_dir, object) db_path = os.path.join(db_dir, 'tasks_db.json') with open(db_path) as f: creds = json.load(f) connection = MongoClient(creds['host'], creds['port']) tdb = connection[creds['database']] tdb.authenticate(creds['admin_user'], creds['admin_password']) props = {"calculations": 1, "task_id": 1, "state": 1, "pseudo_potential": 1, "run_type": 1, "is_hubbard": 1, "hubbards": 1, "unit_cell_formula": 1} m_task = tdb.tasks.find_one({"dir_name": block_part}, props) if not m_task: time.sleep(60) # only thing to think of is wait for DB insertion(?) m_task = tdb.tasks.find_one({"dir_name": block_part}, props) if not m_task: raise ValueError("Could not find task with dir_name: {}".format(block_part)) if m_task['state'] != 'successful': raise ValueError("Cannot run Boltztrap; parent job unsuccessful") nelect = m_task['calculations'][0]['input']['parameters']['NELECT'] bs_id = m_task['calculations'][0]['band_structure_fs_id'] print bs_id, type(bs_id) fs = gridfs.GridFS(tdb, 'band_structure_fs') bs_dict = json.loads(fs.get(bs_id).read()) bs_dict['structure'] = m_task['calculations'][0]['output']['crystal'] bs = BandStructure.from_dict(bs_dict) print 'Band Structure found:', bool(bs) print nelect # run Boltztrap runner = BoltztrapRunner(bs, nelect) dir = runner.run(path_dir=os.getcwd()) # put the data in the database bta = BoltztrapAnalyzer.from_files(dir) # 8/21/15 - Anubhav removed fs_id (also see line further below, ted['boltztrap_full_fs_id'] ...) # 8/21/15 - this is to save space in MongoDB, as well as non-use of full Boltztrap output (vs rerun) """ data = bta.as_dict() data.update(get_meta_from_structure(bs._structure)) data['snlgroup_id'] = fw_spec['snlgroup_id'] data['run_tags'] = fw_spec['run_tags'] data['snl'] = fw_spec['mpsnl'] data['dir_name_full'] = dir data['dir_name'] = get_block_part(dir) data['task_id'] = m_task['task_id'] del data['hall'] # remove because it is too large and not useful fs = gridfs.GridFS(tdb, "boltztrap_full_fs") btid = fs.put(json.dumps(jsanitize(data))) """ # now for the "sanitized" data ted = bta.as_dict() del ted['seebeck'] del ted['hall'] del ted['kappa'] del ted['cond'] # ted['boltztrap_full_fs_id'] = btid ted['snlgroup_id'] = fw_spec['snlgroup_id'] ted['run_tags'] = fw_spec['run_tags'] ted['snl'] = fw_spec['mpsnl'].as_dict() ted['dir_name_full'] = dir ted['dir_name'] = get_block_part(dir) ted['task_id'] = m_task['task_id'] ted['pf_doping'] = bta.get_power_factor(output='tensor', relaxation_time=self.TAU) ted['zt_doping'] = bta.get_zt(output='tensor', relaxation_time=self.TAU, kl=self.KAPPAL) ted['pf_eigs'] = self.get_eigs(ted, 'pf_doping') ted['pf_best'] = self.get_extreme(ted, 'pf_eigs') ted['pf_best_dope18'] = self.get_extreme(ted, 'pf_eigs', max_didx=3) ted['pf_best_dope19'] = self.get_extreme(ted, 'pf_eigs', max_didx=4) ted['zt_eigs'] = self.get_eigs(ted, 'zt_doping') ted['zt_best'] = self.get_extreme(ted, 'zt_eigs') ted['zt_best_dope18'] = self.get_extreme(ted, 'zt_eigs', max_didx=3) ted['zt_best_dope19'] = self.get_extreme(ted, 'zt_eigs', max_didx=4) ted['seebeck_eigs'] = self.get_eigs(ted, 'seebeck_doping') ted['seebeck_best'] = self.get_extreme(ted, 'seebeck_eigs') ted['seebeck_best_dope18'] = self.get_extreme(ted, 'seebeck_eigs', max_didx=3) ted['seebeck_best_dope19'] = self.get_extreme(ted, 'seebeck_eigs', max_didx=4) ted['cond_eigs'] = self.get_eigs(ted, 'cond_doping') ted['cond_best'] = self.get_extreme(ted, 'cond_eigs') ted['cond_best_dope18'] = self.get_extreme(ted, 'cond_eigs', max_didx=3) ted['cond_best_dope19'] = self.get_extreme(ted, 'cond_eigs', max_didx=4) ted['kappa_eigs'] = self.get_eigs(ted, 'kappa_doping') ted['kappa_best'] = self.get_extreme(ted, 'kappa_eigs', maximize=False) ted['kappa_best_dope18'] = self.get_extreme(ted, 'kappa_eigs', maximize=False, max_didx=3) ted['kappa_best_dope19'] = self.get_extreme(ted, 'kappa_eigs', maximize=False, max_didx=4) try: from mpcollab.thermoelectrics.boltztrap_TE import BoltzSPB bzspb = BoltzSPB(ted) maxpf_p = bzspb.get_maximum_power_factor('p', temperature=0, tau=1E-14, ZT=False, kappal=0.5,\ otherprops=('get_seebeck_mu_eig', 'get_conductivity_mu_eig', \ 'get_thermal_conductivity_mu_eig', 'get_average_eff_mass_tensor_mu')) maxpf_n = bzspb.get_maximum_power_factor('n', temperature=0, tau=1E-14, ZT=False, kappal=0.5,\ otherprops=('get_seebeck_mu_eig', 'get_conductivity_mu_eig', \ 'get_thermal_conductivity_mu_eig', 'get_average_eff_mass_tensor_mu')) maxzt_p = bzspb.get_maximum_power_factor('p', temperature=0, tau=1E-14, ZT=True, kappal=0.5, otherprops=('get_seebeck_mu_eig', 'get_conductivity_mu_eig', \ 'get_thermal_conductivity_mu_eig', 'get_average_eff_mass_tensor_mu')) maxzt_n = bzspb.get_maximum_power_factor('n', temperature=0, tau=1E-14, ZT=True, kappal=0.5, otherprops=('get_seebeck_mu_eig', 'get_conductivity_mu_eig', \ 'get_thermal_conductivity_mu_eig', 'get_average_eff_mass_tensor_mu')) ted['zt_best_finemesh'] = {'p': maxzt_p, 'n': maxzt_n} ted['pf_best_finemesh'] = {'p': maxpf_p, 'n': maxpf_n} except: import traceback traceback.print_exc() print 'COULD NOT GET FINE MESH DATA' # add is_compatible mpc = MaterialsProjectCompatibility("Advanced") try: func = m_task["pseudo_potential"]["functional"] labels = m_task["pseudo_potential"]["labels"] symbols = ["{} {}".format(func, label) for label in labels] parameters = {"run_type": m_task["run_type"], "is_hubbard": m_task["is_hubbard"], "hubbards": m_task["hubbards"], "potcar_symbols": symbols} entry = ComputedEntry(Composition(m_task["unit_cell_formula"]), 0.0, 0.0, parameters=parameters, entry_id=m_task["task_id"]) ted["is_compatible"] = bool(mpc.process_entry(entry)) except: traceback.print_exc() print 'ERROR in getting compatibility, task_id: {}'.format(m_task["task_id"]) ted["is_compatible"] = None tdb.boltztrap.insert(jsanitize(ted)) update_spec = {'prev_vasp_dir': fw_spec['prev_vasp_dir'], 'boltztrap_dir': os.getcwd(), 'prev_task_type': fw_spec['task_type'], 'mpsnl': fw_spec['mpsnl'].as_dict(), 'snlgroup_id': fw_spec['snlgroup_id'], 'run_tags': fw_spec['run_tags'], 'parameters': fw_spec.get('parameters')} return FWAction(update_spec=update_spec)
def run_task(self, fw_spec): # get the band structure and nelect from files """ prev_dir = get_loc(fw_spec['prev_vasp_dir']) vasprun_loc = zpath(os.path.join(prev_dir, 'vasprun.xml')) kpoints_loc = zpath(os.path.join(prev_dir, 'KPOINTS')) vr = Vasprun(vasprun_loc) bs = vr.get_band_structure(kpoints_filename=kpoints_loc) """ # get the band structure and nelect from DB block_part = get_block_part(fw_spec['prev_vasp_dir']) db_dir = os.environ['DB_LOC'] assert isinstance(db_dir, object) db_path = os.path.join(db_dir, 'tasks_db.json') with open(db_path) as f: creds = json.load(f) connection = MongoClient(creds['host'], creds['port']) tdb = connection[creds['database']] tdb.authenticate(creds['admin_user'], creds['admin_password']) m_task = tdb.tasks.find_one({"dir_name": block_part}, {"calculations": 1, "task_id": 1}) nelect = m_task['calculations'][0]['input']['parameters']['NELECT'] bs_id = m_task['calculations'][0]['band_structure_fs_id'] print bs_id, type(bs_id) fs = gridfs.GridFS(tdb, 'band_structure_fs') bs_dict = json.loads(fs.get(bs_id).read()) bs_dict['structure'] = m_task['calculations'][0]['output']['crystal'] bs = BandStructure.from_dict(bs_dict) print 'Band Structure found:', bool(bs) print nelect # run Boltztrap runner = BoltztrapRunner(bs, nelect) dir = runner.run(path_dir=os.getcwd()) # put the data in the database bta = BoltztrapAnalyzer.from_files(dir) data = bta.to_dict data.update(get_meta_from_structure(bs._structure)) data['snlgroup_id'] = fw_spec['snlgroup_id'] data['run_tags'] = fw_spec['run_tags'] data['snl'] = fw_spec['mpsnl'] data['dir_name_full'] = dir data['dir_name'] = get_block_part(dir) data['task_id'] = m_task['task_id'] data['hall'] = {} # remove because it is too large and not useful data['hall_doping'] = {} # remove because it is too large and not useful tdb.boltztrap.insert(clean_json(data)) update_spec = {'prev_vasp_dir': fw_spec['prev_vasp_dir'], 'boltztrap_dir': os.getcwd(), 'prev_task_type': fw_spec['task_type'], 'mpsnl': fw_spec['mpsnl'], 'snlgroup_id': fw_spec['snlgroup_id'], 'run_tags': fw_spec['run_tags'], 'parameters': fw_spec.get('parameters')} return FWAction(update_spec=update_spec)
def setUp(self): self.bz = BoltztrapAnalyzer.from_files(os.path.join(test_dir, "boltztrap/transp/")) self.bz_bands = BoltztrapAnalyzer.from_files(os.path.join(test_dir, "boltztrap/bands/")) self.bz_up = BoltztrapAnalyzer.from_files(os.path.join(test_dir, "boltztrap/dos_up/"),dos_spin=1) self.bz_dw = BoltztrapAnalyzer.from_files(os.path.join(test_dir, "boltztrap/dos_dw/"),dos_spin=-1) self.bz_fermi = BoltztrapAnalyzer.from_files(os.path.join(test_dir, "boltztrap/fermi/"))