INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Set the flow associated to this: class: Work.
def set_flow(self, flow): """Set the flow associated to this :class:`Work`.""" if not hasattr(self, "_flow"): self._flow = flow else: if self._flow != flow: raise ValueError("self._flow != flow")
Returns a Counter object that counts the number of task with given status ( use the string representation of the status as key ).
def status_counter(self): """ Returns a `Counter` object that counts the number of task with given status (use the string representation of the status as key). """ counter = collections.Counter() for task in self: counter[str(task.status)] += 1 retur...
This function is called once we have completed the initialization of the: class: Work. It sets the manager of each task ( if not already done ) and defines the working directories of the tasks.
def allocate(self, manager=None): """ This function is called once we have completed the initialization of the :class:`Work`. It sets the manager of each task (if not already done) and defines the working directories of the tasks. Args: manager: :class:`TaskManager` ...
Registers a new: class: Task and add it to the internal list taking into account possible dependencies.
def register(self, obj, deps=None, required_files=None, manager=None, task_class=None): """ Registers a new :class:`Task` and add it to the internal list, taking into account possible dependencies. Args: obj: :class:`AbinitInput` instance or `Task` object. deps: Dictiona...
Creates the top level directory.
def build(self, *args, **kwargs): """Creates the top level directory.""" # Create the directories of the work. self.indir.makedirs() self.outdir.makedirs() self.tmpdir.makedirs() # Build dirs and files of each task. for task in self: task.build(*args,...
Returns a list with the status of the tasks in self.
def get_all_status(self, only_min=False): """ Returns a list with the status of the tasks in self. Args: only_min: If True, the minimum of the status is returned. """ if len(self) == 0: # The work will be created in the future. if only_min: ...
Check the status of the tasks.
def check_status(self): """Check the status of the tasks.""" # Recompute the status of the tasks # Ignore OK and LOCKED tasks. for task in self: if task.status in (task.S_OK, task.S_LOCKED): continue task.check_status() # Take into account possible depend...
Remove all files and directories in the working directory
def rmtree(self, exclude_wildcard=""): """ Remove all files and directories in the working directory Args: exclude_wildcard: Optional string with regular expressions separated by `|`. Files matching one of the regular expressions will be preserved. ex...
Recursively move self. workdir to another location. This is similar to the Unix mv command. The destination path must not already exist. If the destination already exists but is not a directory it may be overwritten depending on os. rename () semantics.
def move(self, dest, isabspath=False): """ Recursively move self.workdir to another location. This is similar to the Unix "mv" command. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() se...
Submits the task in self and wait. TODO: change name.
def submit_tasks(self, wait=False): """ Submits the task in self and wait. TODO: change name. """ for task in self: task.start() if wait: for task in self: task.wait()
Start the work. Calls build and _setup first then submit the tasks. Non - blocking call unless wait is set to True
def start(self, *args, **kwargs): """ Start the work. Calls build and _setup first, then submit the tasks. Non-blocking call unless wait is set to True """ wait = kwargs.pop("wait", False) # Initial setup self._setup(*args, **kwargs) # Build dirs and fil...
Reads the total energy from the GSR file produced by the task.
def read_etotals(self, unit="Ha"): """ Reads the total energy from the GSR file produced by the task. Return a numpy array with the total energies in Hartree The array element is set to np.inf if an exception is raised while reading the GSR file. """ if not self.all_done...
Parse the TIMER section reported in the ABINIT output files.
def parse_timers(self): """ Parse the TIMER section reported in the ABINIT output files. Returns: :class:`AbinitTimerParser` object """ filenames = list(filter(os.path.exists, [task.output_file.path for task in self])) parser = AbinitTimerParser() pa...
Plot the band structure. kwargs are passed to the plot method of: class: ElectronBands.
def plot_ebands(self, **kwargs): """ Plot the band structure. kwargs are passed to the plot method of :class:`ElectronBands`. Returns: `matplotlib` figure """ with self.nscf_task.open_gsr() as gsr: return gsr.ebands.plot(**kwargs)
Plot the band structure and the DOS.
def plot_ebands_with_edos(self, dos_pos=0, method="gaussian", step=0.01, width=0.1, **kwargs): """ Plot the band structure and the DOS. Args: dos_pos: Index of the task from which the DOS should be obtained (note: 0 refers to the first DOS task). method: String defining ...
Plot the band structure and the DOS.
def plot_edoses(self, dos_pos=None, method="gaussian", step=0.01, width=0.1, **kwargs): """ Plot the band structure and the DOS. Args: dos_pos: Index of the task from which the DOS should be obtained. None is all DOSes should be displayed. Accepts integer or lis...
This callback is called when one task reaches status S_OK. If sender == self. ion_task we update the initial structure used by self. ioncell_task and we unlock it so that the job can be submitted.
def on_ok(self, sender): """ This callback is called when one task reaches status S_OK. If sender == self.ion_task, we update the initial structure used by self.ioncell_task and we unlock it so that the job can be submitted. """ logger.debug("in on_ok with sender %s" % se...
Plot the history of the ion - cell relaxation. kwargs are passed to the plot method of: class: HistFile
def plot_ion_relaxation(self, **kwargs): """ Plot the history of the ion-cell relaxation. kwargs are passed to the plot method of :class:`HistFile` Return `matplotlib` figure or None if hist file is not found. """ with self.ion_task.open_hist() as hist: retur...
Plot the history of the ion - cell relaxation. kwargs are passed to the plot method of: class: HistFile
def plot_ioncell_relaxation(self, **kwargs): """ Plot the history of the ion-cell relaxation. kwargs are passed to the plot method of :class:`HistFile` Return `matplotlib` figure or None if hist file is not found. """ with self.ioncell_task.open_hist() as hist: ...
Builds and returns a: class: MdfRobot for analyzing the results in the MDF files.
def get_mdf_robot(self): """Builds and returns a :class:`MdfRobot` for analyzing the results in the MDF files.""" from abilab.robots import MdfRobot robot = MdfRobot() for task in self[2:]: mdf_path = task.outdir.has_abiext(robot.EXT) if mdf_path: ...
Create the SCR tasks and register them in self.
def create_tasks(self, wfk_file, scr_input): """ Create the SCR tasks and register them in self. Args: wfk_file: Path to the ABINIT WFK file to use for the computation of the screening. scr_input: Input for the screening calculation. """ assert len(self) ...
This method is called when all the q - points have been computed. It runs mrgscr in sequential on the local machine to produce the final SCR file in the outdir of the Work. If remove_scrfiles is True the partial SCR files are removed after the merge.
def merge_scrfiles(self, remove_scrfiles=True): """ This method is called when all the q-points have been computed. It runs `mrgscr` in sequential on the local machine to produce the final SCR file in the outdir of the `Work`. If remove_scrfiles is True, the partial SCR files are...
This method is called when all the q - points have been computed. It runs mrgscr in sequential on the local machine to produce the final SCR file in the outdir of the Work.
def on_all_ok(self): """ This method is called when all the q-points have been computed. It runs `mrgscr` in sequential on the local machine to produce the final SCR file in the outdir of the `Work`. """ final_scr = self.merge_scrfiles() return self.Results(node=s...
Build tasks for the computation of Born effective charges and add them to the work.
def add_becs_from_scf_task(self, scf_task, ddk_tolerance, ph_tolerance): """ Build tasks for the computation of Born effective charges and add them to the work. Args: scf_task: ScfTask object. ddk_tolerance: dict {"varname": value} with the tolerance used in the DDK run....
This method is called when all the q - points have been computed. It runs mrgddb in sequential on the local machine to produce the final DDB file in the outdir of the Work.
def merge_ddb_files(self, delete_source_ddbs=True, only_dfpt_tasks=True, exclude_tasks=None, include_tasks=None): """ This method is called when all the q-points have been computed. It runs `mrgddb` in sequential on the local machine to produce the final DDB file ...
This method is called when all the q - points have been computed. It runs mrgdvdb in sequential on the local machine to produce the final DVDB file in the outdir of the Work.
def merge_pot1_files(self, delete_source=True): """ This method is called when all the q-points have been computed. It runs `mrgdvdb` in sequential on the local machine to produce the final DVDB file in the outdir of the `Work`. Args: delete_source: True if POT1 file...
Construct a PhononWork from a: class: ScfTask object. The input file for phonons is automatically generated from the input of the ScfTask. Each phonon task depends on the WFK file produced by the scf_task.
def from_scf_task(cls, scf_task, qpoints, is_ngqpt=False, tolerance=None, with_becs=False, ddk_tolerance=None, manager=None): """ Construct a `PhononWork` from a :class:`ScfTask` object. The input file for phonons is automatically generated from the input of the ScfTask. ...
Similar to from_scf_task the difference is that this method requires an input for SCF calculation. A new ScfTask is created and added to the Work. This API should be used if the DDB of the GS task should be merged.
def from_scf_input(cls, scf_input, qpoints, is_ngqpt=False, tolerance=None, with_becs=False, ddk_tolerance=None, manager=None): """ Similar to `from_scf_task`, the difference is that this method requires an input for SCF calculation. A new ScfTask is created and added to t...
Construct a PhononWfkqWork from a: class: ScfTask object. The input files for WFQ and phonons are automatically generated from the input of the ScfTask. Each phonon task depends on the WFK file produced by scf_task and the associated WFQ file.
def from_scf_task(cls, scf_task, ngqpt, ph_tolerance=None, tolwfr=1.0e-22, nband=None, with_becs=False, ddk_tolerance=None, shiftq=(0, 0, 0), is_ngqpt=True, remove_wfkq=True, manager=None): """ Construct a `PhononWfkqWork` from a :class:`ScfTask` object. ...
This callback is called when one task reaches status S_OK. It removes the WFKQ file if all its children have reached S_OK.
def on_ok(self, sender): """ This callback is called when one task reaches status `S_OK`. It removes the WFKQ file if all its children have reached `S_OK`. """ if self.remove_wfkq: for task in self.wfkq_tasks: if task.status != task.S_OK: continue ...
Construct a PhononWfkqWork from a DDB and DVDB file. For each q found a WFQ task and an EPH task computing the matrix elements are created.
def from_den_ddb_dvdb(cls, inp, den_path, ddb_path, dvdb_path, mpiprocs=1, remove_wfkq=True, qpath=None, with_ddk=True, expand=True, manager=None): """ Construct a `PhononWfkqWork` from a DDB and DVDB file. For each q found, a WFQ task and an EPH task computing the matr...
Construct a GKKPWork from a PhononWfkqWork object. The WFQ are the ones used for PhononWfkqWork so in principle have only valence bands
def from_phononwfkq_work(cls, phononwfkq_work, nscf_vars={}, remove_wfkq=True, with_ddk=True, manager=None): """ Construct a `GKKPWork` from a `PhononWfkqWork` object. The WFQ are the ones used for PhononWfkqWork so in principle have only valence bands """ # Get list of qpoints f...
This callback is called when one task reaches status S_OK. It removes the WFKQ file if all its children have reached S_OK.
def on_ok(self, sender): """ This callback is called when one task reaches status `S_OK`. It removes the WFKQ file if all its children have reached `S_OK`. """ if self.remove_wfkq: for task in self.wfkq_tasks: if task.status != task.S_OK: continue ...
Build tasks for the computation of Born effective charges from a ground - state task.
def from_scf_task(cls, scf_task, ddk_tolerance=None, ph_tolerance=None, manager=None): """ Build tasks for the computation of Born effective charges from a ground-state task. Args: scf_task: ScfTask object. ddk_tolerance: tolerance used in the DDK run if with_becs. None ...
This method is called when all tasks reach S_OK Ir runs mrgddb in sequential on the local machine to produce the final DDB file in the outdir of the Work.
def on_all_ok(self): """ This method is called when all tasks reach S_OK Ir runs `mrgddb` in sequential on the local machine to produce the final DDB file in the outdir of the `Work`. """ # Merge DDB files. out_ddb = self.merge_ddb_files() return self.Resu...
Build a DteWork from a ground - state task.
def from_scf_task(cls, scf_task, ddk_tolerance=None, manager=None): """ Build a DteWork from a ground-state task. Args: scf_task: ScfTask object. ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default. manager: :class:`TaskManager` obje...
this takes a Interstitial defect object and generates the sublattice for it based on the structure s space group. Useful for understanding multiplicity of an interstitial defect in thermodynamic analysis.
def create_saturated_interstitial_structure( interstitial_def, dist_tol=0.1): """ this takes a Interstitial defect object and generates the sublattice for it based on the structure's space group. Useful for understanding multiplicity of an interstitial defect in thermodynamic analysis. NOTE: if...
Returns Defective Vacancy structure decorated with charge Args: supercell ( int [ 3x1 ] or [[ ]] ( 3x3 )): supercell integer vector or scaling matrix
def generate_defect_structure(self, supercell=(1, 1, 1)): """ Returns Defective Vacancy structure, decorated with charge Args: supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix """ defect_structure = self.bulk_structure.copy() ...
Returns the multiplicity of a defect site within the structure ( needed for concentration analysis )
def multiplicity(self): """ Returns the multiplicity of a defect site within the structure (needed for concentration analysis) """ sga = SpacegroupAnalyzer(self.bulk_structure) periodic_struc = sga.get_symmetrized_structure() poss_deflist = sorted( periodic_st...
Returns Defective Substitution structure decorated with charge Args: supercell ( int [ 3x1 ] or [[ ]] ( 3x3 )): supercell integer vector or scaling matrix
def generate_defect_structure(self, supercell=(1, 1, 1)): """ Returns Defective Substitution structure, decorated with charge Args: supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix """ defect_structure = self.bulk_structure.copy() ...
Returns a name for this defect
def name(self): """ Returns a name for this defect """ poss_deflist = sorted( self.bulk_structure.get_sites_in_sphere(self.site.coords, 2, include_index=True), key=lambda x: x[1]) defindex = poss_deflist[0][2] return "Sub_{}_on_{}_mult{}".format(self.site.spec...
Returns Defective Interstitial structure decorated with charge Args: supercell ( int [ 3x1 ] or [[ ]] ( 3x3 )): supercell integer vector or scaling matrix
def generate_defect_structure(self, supercell=(1, 1, 1)): """ Returns Defective Interstitial structure, decorated with charge Args: supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix """ defect_structure = self.bulk_structure.copy() ...
Returns the multiplicity of a defect site within the structure ( needed for concentration analysis )
def multiplicity(self): """ Returns the multiplicity of a defect site within the structure (needed for concentration analysis) """ if self._multiplicity is None: # generate multiplicity based on space group symmetry operations performed on defect coordinates try: ...
Returns a name for this defect
def name(self): """ Returns a name for this defect """ if self.site_name: return "Int_{}_{}_mult{}".format(self.site.specie, self.site_name, self.multiplicity) else: return "Int_{}_mult{}".format(self.site.specie, self.multiplicity)
Json - serializable dict representation of DefectEntry
def as_dict(self): """ Json-serializable dict representation of DefectEntry """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "defect": self.defect.as_dict(), "uncorrected_energy": self.uncorrected_energy, ...
Reconstitute a DefectEntry object from a dict representation created using as_dict (). Args: d ( dict ): dict representation of DefectEntry. Returns: DefectEntry object
def from_dict(cls, d): """ Reconstitute a DefectEntry object from a dict representation created using as_dict(). Args: d (dict): dict representation of DefectEntry. Returns: DefectEntry object """ defect = MontyDecoder().process_decoded( ...
Returns the * corrected * energy of the entry
def energy(self): """ Returns the *corrected* energy of the entry """ return self.uncorrected_energy + np.sum(list(self.corrections.values()))
Computes the formation energy for a defect taking into account a given chemical potential and fermi_level
def formation_energy(self, chemical_potentials=None, fermi_level=0): """ Computes the formation energy for a defect taking into account a given chemical potential and fermi_level """ chemical_potentials = chemical_potentials if chemical_potentials else {} chempot_correction = su...
Get the defect concentration for a temperature and Fermi level. Args: temperature: the temperature in K fermi_level: the fermi level in eV ( with respect to the VBM ) Returns: defects concentration in cm^ - 3
def defect_concentration(self, chemical_potentials, temperature=300, fermi_level=0.0): """ Get the defect concentration for a temperature and Fermi level. Args: temperature: the temperature in K fermi_level: the fermi level in eV (with resp...
Corrects a single entry.
def correct_entry(self, entry): """ Corrects a single entry. Args: entry: A DefectEntry object. Returns: An processed entry. Raises: CompatibilityError if entry is not compatible. """ entry.correction.update(self.get_correcti...
Convenience method to run Bader analysis on a folder containing typical VASP output files.
def bader_analysis_from_path(path, suffix=''): """ Convenience method to run Bader analysis on a folder containing typical VASP output files. This method will: 1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped counterparts. 2. If AECCAR* files are present, constructs a temp...
Convenience method to run Bader analysis from a set of pymatgen Chgcar and Potcar objects.
def bader_analysis_from_objects(chgcar, potcar=None, aeccar0=None, aeccar2=None): """ Convenience method to run Bader analysis from a set of pymatgen Chgcar and Potcar objects. This method will: 1. If aeccar objects are present, constructs a temporary reference file as AECCAR0 + AECCAR2 2....
Returns the charge transferred for a particular atom. Requires POTCAR to be supplied.
def get_charge_transfer(self, atom_index): """ Returns the charge transferred for a particular atom. Requires POTCAR to be supplied. Args: atom_index: Index of atom. Returns: Charge transfer associated with atom from the Bader analysis. ...
Returns an oxidation state decorated structure.
def get_oxidation_state_decorated_structure(self): """ Returns an oxidation state decorated structure. Returns: Returns an oxidation state decorated structure. Requires POTCAR to be supplied. """ structure = self.chgcar.structure charges = [-self....
Convenient constructor that takes in the path name of VASP run to perform Bader analysis.
def from_path(cls, path, suffix=""): """ Convenient constructor that takes in the path name of VASP run to perform Bader analysis. Args: path (str): Name of directory where VASP output files are stored. suffix (str): specific suffix to look for (e...
return the derivatives of y ( x ) at the points x if scipy is available a spline is generated to calculate the derivatives if scipy is not available the left and right slopes are calculated if both exist the average is returned putting fd to zero always returns the finite difference slopes
def get_derivatives(xs, ys, fd=False): """ return the derivatives of y(x) at the points x if scipy is available a spline is generated to calculate the derivatives if scipy is not available the left and right slopes are calculated, if both exist the average is returned putting fd to zero always retur...
reciprocal function to the power n to fit convergence data
def reciprocal(x, a, b, n): """ reciprocal function to the power n to fit convergence data """ if n < 1: n = 1 elif n > 5: n = 5 if isinstance(x, list): y_l = [] for x_v in x: y_l.append(a + b / x_v ** n) y = np.array(y_l) else: y =...
predictor for first guess for reciprocal
def p0_reciprocal(xs, ys): """ predictor for first guess for reciprocal """ a0 = ys[len(ys) - 1] b0 = ys[0]*xs[0] - a0*xs[0] return [a0, b0, 1]
reciprocal function to fit convergence data
def single_reciprocal(x, a, b, c): """ reciprocal function to fit convergence data """ if isinstance(x, list): y_l = [] for x_v in x: y_l.append(a + b / (x_v - c)) y = np.array(y_l) else: y = a + b / (x - c) return y
reciprocal function to fit convergence data
def simple_reciprocal(x, a, b): """ reciprocal function to fit convergence data """ if isinstance(x, list): y_l = [] for x_v in x: y_l.append(a + b / x_v) y = np.array(y_l) else: y = a + b / x return y
return the parameters such that a + b/ x^n hits the last two data points
def extrapolate_reciprocal(xs, ys, n, noise): """ return the parameters such that a + b / x^n hits the last two data points """ if len(xs) > 4 and noise: y1 = (ys[-3] + ys[-4]) / 2 y2 = (ys[-1] + ys[-2]) / 2 x1 = (xs[-3] + xs[-4]) / 2 x2 = (xs[-1] + xs[-2]) / 2 tr...
measure the quality of a fit
def measure(function, xs, ys, popt, weights): """ measure the quality of a fit """ m = 0 n = 0 for x in xs: try: if len(popt) == 2: m += (ys[n] - function(x, popt[0], popt[1]))**2 * weights[n] elif len(popt) == 3: m += (ys[n] - func...
fit multiple functions to the x y data return the best fit
def multi_curve_fit(xs, ys, verbose): """ fit multiple functions to the x, y data, return the best fit """ #functions = {exponential: p0_exponential, reciprocal: p0_reciprocal, single_reciprocal: p0_single_reciprocal} functions = { exponential: p0_exponential, reciprocal: p0_reciproc...
Calculates for a series of powers ns the parameters for which the last two points are at the curve. With these parameters measure how well the other data points fit. return the best fit.
def multi_reciprocal_extra(xs, ys, noise=False): """ Calculates for a series of powers ns the parameters for which the last two points are at the curve. With these parameters measure how well the other data points fit. return the best fit. """ ns = np.linspace(0.5, 6.0, num=56) best = ['', n...
print the gnuplot command line to plot the x y data with the fitted function using the popt parameters
def print_plot_line(function, popt, xs, ys, name, tol=0.05, extra=''): """ print the gnuplot command line to plot the x, y data with the fitted function using the popt parameters """ idp = id_generator() f = open('convdat.'+str(idp), mode='w') for n in range(0, len(ys), 1): f.write(str(x...
test it and at which x_value dy ( x )/ dx < tol for all x > = x_value conv is true is such a x_value exists.
def determine_convergence(xs, ys, name, tol=0.0001, extra='', verbose=False, mode='extra', plots=True): """ test it and at which x_value dy(x)/dx < tol for all x >= x_value, conv is true is such a x_value exists. """ if len(xs) != len(ys): raise RuntimeError('the range of x and y are not equal')...
Lists prime factors of a given natural integer from greatest to smallest: param n: Natural integer: rtype: list of all prime factors of the given natural n
def prime_factors(n): """Lists prime factors of a given natural integer, from greatest to smallest :param n: Natural integer :rtype : list of all prime factors of the given natural n """ i = 2 while i <= sqrt(n): if n % i == 0: l = prime_factors(n/i) l.append(i) ...
From a given natural integer returns the prime factors and their multiplicity: param n: Natural integer: return:
def _factor_generator(n): """ From a given natural integer, returns the prime factors and their multiplicity :param n: Natural integer :return: """ p = prime_factors(n) factors = {} for p1 in p: try: factors[p1] += 1 except KeyError: factors[p1] = ...
From a given natural integer returns the list of divisors in ascending order: param n: Natural integer: return: List of divisors of n in ascending order
def divisors(n): """ From a given natural integer, returns the list of divisors in ascending order :param n: Natural integer :return: List of divisors of n in ascending order """ factors = _factor_generator(n) _divisors = [] listexponents = [[k**x for x in range(0, factors[k]+1)] for k i...
Given a tuple of tuples generate a delimited string form. >>> results = [[ a b c ] [ d e f ] [ 1 2 3 ]] >>> print ( str_delimited ( results delimiter = )) a b c d e f 1 2 3
def str_delimited(results, header=None, delimiter="\t"): """ Given a tuple of tuples, generate a delimited string form. >>> results = [["a","b","c"],["d","e","f"],[1,2,3]] >>> print(str_delimited(results,delimiter=",")) a,b,c d,e,f 1,2,3 Args: result: 2d sequence of arbitrary ty...
This function is used to make pretty formulas by formatting the amounts. Instead of Li1. 0 Fe1. 0 P1. 0 O4. 0 you get LiFePO4.
def formula_double_format(afloat, ignore_ones=True, tol=1e-8): """ This function is used to make pretty formulas by formatting the amounts. Instead of Li1.0 Fe1.0 P1.0 O4.0, you get LiFePO4. Args: afloat (float): a float ignore_ones (bool): if true, floats of 1 are ignored. tol ...
Generates a formula with unicode subscripts e. g. Fe2O3 is transformed to Fe₂O₃. Does not support formulae with decimal points.
def unicodeify(formula): """ Generates a formula with unicode subscripts, e.g. Fe2O3 is transformed to Fe₂O₃. Does not support formulae with decimal points. :param formula: :return: """ if '.' in formula: raise ValueError('No unicode character exists for subscript period.') su...
Generates a latex formatted spacegroup. E. g. P2_1/ c is converted to P2$_ { 1 } $/ c and P - 1 is converted to P$ \\ overline { 1 } $.
def latexify_spacegroup(spacegroup_symbol): """ Generates a latex formatted spacegroup. E.g., P2_1/c is converted to P2$_{1}$/c and P-1 is converted to P$\\overline{1}$. Args: spacegroup_symbol (str): A spacegroup symbol Returns: A latex formatted spacegroup with proper subscripts ...
True if stream supports colours. Python cookbook #475186
def stream_has_colours(stream): """ True if stream supports colours. Python cookbook, #475186 """ if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return c...
Convenience method. Given matrix returns string e. g. x + 2y + 1/ 4: param matrix: param translation_vec: param components: either ( x y z ) or ( a b c ): param c: optional additional character to print ( used for magmoms ): param delim: delimiter: return: xyz string
def transformation_to_string(matrix, translation_vec=(0, 0, 0), components=('x', 'y', 'z'), c='', delim=','): """ Convenience method. Given matrix returns string, e.g. x+2y+1/4 :param matrix :param translation_vec :param components: either ('x', 'y', 'z') or ('a', 'b', 'c') :param c: optional ad...
Returns a formula of a form like AxB1 - x ( x = 0. 5 ) for disordered structures. Will only return a formula for disordered structures with one kind of disordered site at present.
def disordered_formula(disordered_struct, symbols=('x', 'y', 'z'), fmt='plain'): """ Returns a formula of a form like AxB1-x (x=0.5) for disordered structures. Will only return a formula for disordered structures with one kind of disordered site at present. Args: disordered_struct: a di...
Compare the bond table of the two molecules.
def are_equal(self, mol1, mol2): """ Compare the bond table of the two molecules. Args: mol1: first molecule. pymatgen Molecule object. mol2: second moleculs. pymatgen Molecule objec. """ b1 = set(self._get_bonds(mol1)) b2 = set(self._get_bonds(mo...
Find all the bond in a molcule
def _get_bonds(self, mol): """ Find all the bond in a molcule Args: mol: the molecule. pymatgen Molecule object Returns: List of tuple. Each tuple correspond to a bond represented by the id of the two end atoms. """ num_atoms = len(mo...
Compute the mean of correlation between bzt and vasp bandstructure on sym line for all bands and locally ( for each branches ) the difference squared ( % ) if nb is specified.
def compare_sym_bands(bands_obj, bands_ref_obj, nb=None): """ Compute the mean of correlation between bzt and vasp bandstructure on sym line, for all bands and locally (for each branches) the difference squared (%) if nb is specified. """ nkpt = len(bands_obj.kpoints) if bands_ref_obj.is_sp...
Seebeck analytic formula in the single parabolic model
def seebeck_spb(eta,Lambda=0.5): """ Seebeck analytic formula in the single parabolic model """ from fdint import fdk return constants.k/constants.e * ((2. + Lambda) * fdk( 1.+ Lambda, eta)/ ((1.+Lambda)*fdk(Lambda, eta))- eta) * 1e+6
It takes a value of seebeck and adjusts the analytic seebeck until it s equal Returns: eta where the two seebeck coefficients are equal ( reduced chemical potential )
def eta_from_seebeck(seeb,Lambda): """ It takes a value of seebeck and adjusts the analytic seebeck until it's equal Returns: eta where the two seebeck coefficients are equal (reduced chemical potential) """ from scipy.optimize import fsolve out = fsolve(lambda x: (seebeck_spb(...
Calculate seebeck effective mass at a certain carrier concentration eta in kB * T units n in cm - 3 T in K returns mass in m0 units
def seebeck_eff_mass_from_carr(eta, n, T, Lambda): """ Calculate seebeck effective mass at a certain carrier concentration eta in kB*T units, n in cm-3, T in K, returns mass in m0 units """ from fdint import fdk return (2 * np.pi**2 * abs(n) * 10 ** 6 / (fdk(0.5,eta))) ** (2. / 3)\ ...
Find the chemical potential where analytic and calculated seebeck are identical and then calculate the seebeck effective mass at that chemical potential and a certain carrier concentration n
def seebeck_eff_mass_from_seebeck_carr(seeb, n, T, Lambda): """ Find the chemical potential where analytic and calculated seebeck are identical and then calculate the seebeck effective mass at that chemical potential and a certain carrier concentration n """ try: from fdint ...
automatically determine the energy range as min/ max eigenvalue minus/ plus the buffer_in_ev
def _auto_set_energy_range(self): """ automatically determine the energy range as min/max eigenvalue minus/plus the buffer_in_ev """ emins = [min([e_k[0] for e_k in self._bs.bands[Spin.up]])] emaxs = [max([e_k[0] for e_k in self._bs.bands[Spin.up]])] if self._bs....
Write inputs ( optional ) run BoltzTraP and ensure convergence ( optional ) Args: path_dir ( str ): directory in which to run BoltzTraP convergence ( bool ): whether to check convergence and make corrections if needed write_input: ( bool ) whether to write input files before the run ( required for convergence mode ) cl...
def run(self, path_dir=None, convergence=True, write_input=True, clear_dir=False, max_lpfac=150, min_egrid=0.00005): """ Write inputs (optional), run BoltzTraP, and ensure convergence (optional) Args: path_dir (str): directory in which to run BoltzTraP ...
Function useful to read bands from Boltztrap output and get a BandStructureSymmLine object comparable with that one from a DFT calculation ( if the same kpt_line is provided ). Default kpt_line and labels_dict is the standard path of high symmetry k - point for the specified structure. They could be extracted from the ...
def get_symm_bands(self, structure, efermi, kpt_line=None, labels_dict=None): """ Function useful to read bands from Boltztrap output and get a BandStructureSymmLine object comparable with that one from a DFT calculation (if the same kpt_line is provide...
Compare sbs_bz BandStructureSymmLine calculated with boltztrap with the sbs_ref BandStructureSymmLine as reference ( from MP for instance ) computing correlation and energy difference for eight bands around the gap ( semiconductors ) or fermi level ( metals ). warn_thr is a threshold to get a warning in the accuracy of...
def check_acc_bzt_bands(sbs_bz, sbs_ref, warn_thr=(0.03, 0.03)): """ Compare sbs_bz BandStructureSymmLine calculated with boltztrap with the sbs_ref BandStructureSymmLine as reference (from MP for instance), computing correlation and energy difference for eight bands ...
Gives the seebeck coefficient ( microV/ K ) in either a full 3x3 tensor form as 3 eigenvalues or as the average value ( trace/ 3. 0 ) If doping_levels = True the results are given at different p and n doping levels ( given by self. doping ) otherwise it is given as a series of electron chemical potential values
def get_seebeck(self, output='eigs', doping_levels=True): """ Gives the seebeck coefficient (microV/K) in either a full 3x3 tensor form, as 3 eigenvalues, or as the average value (trace/3.0) If doping_levels=True, the results are given at different p and n doping ...
Gives the conductivity ( 1/ Ohm * m ) in either a full 3x3 tensor form as 3 eigenvalues or as the average value ( trace/ 3. 0 ) If doping_levels = True the results are given at different p and n doping levels ( given by self. doping ) otherwise it is given as a series of electron chemical potential values
def get_conductivity(self, output='eigs', doping_levels=True, relaxation_time=1e-14): """ Gives the conductivity (1/Ohm*m) in either a full 3x3 tensor form, as 3 eigenvalues, or as the average value (trace/3.0) If doping_levels=True, the results are g...
Gives the power factor ( Seebeck^2 * conductivity ) in units microW/ ( m * K^2 ) in either a full 3x3 tensor form as 3 eigenvalues or as the average value ( trace/ 3. 0 ) If doping_levels = True the results are given at different p and n doping levels ( given by self. doping ) otherwise it is given as a series of elect...
def get_power_factor(self, output='eigs', doping_levels=True, relaxation_time=1e-14): """ Gives the power factor (Seebeck^2 * conductivity) in units microW/(m*K^2) in either a full 3x3 tensor form, as 3 eigenvalues, or as the average value (trace/3.0) If ...
Gives the electronic part of the thermal conductivity in either a full 3x3 tensor form as 3 eigenvalues or as the average value ( trace/ 3. 0 ) If doping_levels = True the results are given at different p and n doping levels ( given by self. doping ) otherwise it is given as a series of electron chemical potential valu...
def get_thermal_conductivity(self, output='eigs', doping_levels=True, k_el=True, relaxation_time=1e-14): """ Gives the electronic part of the thermal conductivity in either a full 3x3 tensor form, as 3 eigenvalues, or as the average value (trace/3.0) If ...
Gives the ZT coefficient ( S^2 * cond * T/ thermal cond ) in either a full 3x3 tensor form as 3 eigenvalues or as the average value ( trace/ 3. 0 ) If doping_levels = True the results are given at different p and n doping levels ( given by self. doping ) otherwise it is given as a series of electron chemical potential ...
def get_zt(self, output='eigs', doping_levels=True, relaxation_time=1e-14, kl=1.0): """ Gives the ZT coefficient (S^2*cond*T/thermal cond) in either a full 3x3 tensor form, as 3 eigenvalues, or as the average value (trace/3.0) If doping_levels=True, the results are...
Gives the average effective mass tensor. We call it average because it takes into account all the bands and regions in the Brillouin zone. This is different than the standard textbook effective mass which relates often to only one ( parabolic ) band. The average effective mass tensor is defined as the integrated averag...
def get_average_eff_mass(self, output='eigs', doping_levels=True): """ Gives the average effective mass tensor. We call it average because it takes into account all the bands and regions in the Brillouin zone. This is different than the standard textbook effective mass which rela...
Seebeck effective mass calculated as explained in Ref. Gibbs Z. M. et al. Effective mass and fermi surface complexity factor from ab initio band structure calculations. npj Computational Materials 3 8 ( 2017 ).
def get_seebeck_eff_mass(self, output='average', temp=300, doping_levels=False, Lambda=0.5): """ Seebeck effective mass calculated as explained in Ref. Gibbs, Z. M. et al., Effective mass and fermi surface complexity factor from ab initio band structure c...
Fermi surface complexity factor respect to calculated as explained in Ref. Gibbs Z. M. et al. Effective mass and fermi surface complexity factor from ab initio band structure calculations. npj Computational Materials 3 8 ( 2017 ). Args: output: average returns the complexity factor calculated using the average of the t...
def get_complexity_factor(self, output='average', temp=300, doping_levels=False, Lambda=0.5): """ Fermi surface complexity factor respect to calculated as explained in Ref. Gibbs, Z. M. et al., Effective mass and fermi surface complexity factor from ab init...
This method takes in eigenvalues over a range of carriers temperatures and doping levels and tells you what is the best value that can be achieved for the given target_property. Note that this method searches the doping dict only not the full mu dict.
def get_extreme(self, target_prop, maximize=True, min_temp=None, max_temp=None, min_doping=None, max_doping=None, isotropy_tolerance=0.05, use_average=True): """ This method takes in eigenvalues over a range of carriers, temperatures, and doping levels, a...
Gives a CompleteDos object with the DOS from the interpolated projected band structure Args: the structure ( necessary to identify sites for projection ) analyzer_for_second_spin must be specified to have a CompleteDos with both Spin components Returns: a CompleteDos object Example of use in case of spin polarized case...
def get_complete_dos(self, structure, analyzer_for_second_spin=None): """ Gives a CompleteDos object with the DOS from the interpolated projected band structure Args: the structure (necessary to identify sites for projection) analyzer_for_secon...
gives the carrier concentration ( in cm^ - 3 )
def get_carrier_concentration(self): """ gives the carrier concentration (in cm^-3) Returns a dictionary {temp:[]} with an array of carrier concentration (in cm^-3) at each temperature The array relates to each step of electron chemical potential """ ...
gives the Hall carrier concentration ( in cm^ - 3 ). This is the trace of the Hall tensor ( see Boltztrap source code ) Hall carrier concentration are not always exactly the same than carrier concentration.
def get_hall_carrier_concentration(self): """ gives the Hall carrier concentration (in cm^-3). This is the trace of the Hall tensor (see Boltztrap source code) Hall carrier concentration are not always exactly the same than carrier concentration. Returns a dictionary...
Parses. outputtrans file
def parse_outputtrans(path_dir): """ Parses .outputtrans file Args: path_dir: dir containing boltztrap.outputtrans Returns: tuple - (run_type, warning, efermi, gap, doping_levels) """ run_type = None warning = None efermi = None ...