INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
For performing planar averaging potential alignment title is for name of plot, if you dont want a plot then leave it as None widthsample is the width (in Angstroms) of the region in between defects where the potential alignment correction is averaged
def perform_pot_corr(self, axis_grid, pureavg, defavg, lattice, q, defect_position, axis, madetol=0.0001, ...
Plots the planar average electrostatic potential against the Long range and short range models from Freysoldt
def plot(self, axis, title=None, saved=False): """ Plots the planar average electrostatic potential against the Long range and short range models from Freysoldt """ x = self.metadata['pot_plot_data'][axis]['x'] v_R = self.metadata['pot_plot_data'][axis]['Vr'] dft_diff =...
Gets the BandFilling correction for a defect entry
def get_correction(self, entry): """ Gets the BandFilling correction for a defect entry """ eigenvalues = entry.parameters["eigenvalues"] kpoint_weights = entry.parameters["kpoint_weights"] potalign = entry.parameters["potalign"] vbm = entry.parameters["vbm"] ...
This calculates the band filling correction based on excess of electrons/holes in CB/VB... Note that the total free holes and electrons may also be used for a "shallow donor/acceptor" correction with specified band shifts: +num_elec_cbm * Delta E_CBM (or -num_hole_vbm * Delta E_VBM) ...
def perform_bandfill_corr(self, eigenvalues, kpoint_weights, potalign, vbm, cbm): """ This calculates the band filling correction based on excess of electrons/holes in CB/VB... Note that the total free holes and electrons may also be used for a "shallow donor/acceptor" correction...
Gets the BandEdge correction for a defect entry
def get_correction(self, entry): """ Gets the BandEdge correction for a defect entry """ # TODO: add smarter defect level shifting based on defect level projection onto host bands hybrid_cbm = entry.parameters["hybrid_cbm"] hybrid_vbm = entry.parameters["hybrid_vbm"] ...
Return a :class:`JobStatus` instance from its string representation.
def from_string(cls, s): """Return a :class:`JobStatus` instance from its string representation.""" for num, text in cls._STATUS_TABLE.items(): if text == s: return cls(num) else: #raise ValueError("Wrong string %s" % s) logger.warning("Got unknown status: %s"...
Return a new istance of the appropriate subclass. Args: qtype: String specifying the Resource manager type. queue_id: Job identifier. qname: Name of the queue (optional).
def from_qtype_and_id(qtype, queue_id, qname=None): """ Return a new istance of the appropriate subclass. Args: qtype: String specifying the Resource manager type. queue_id: Job identifier. qname: Name of the queue (optional). """ for cls in a...
Get the stable entries. Args: charge_to_discharge: order from most charge to most discharged state? Default to True. Returns: A list of stable entries in the electrode, ordered by amount of the working ion.
def get_stable_entries(self, charge_to_discharge=True): """ Get the stable entries. Args: charge_to_discharge: order from most charge to most discharged state? Default to True. Returns: A list of stable entries in the electrode, ordered by amount...
Returns the unstable entries for the electrode. Args: charge_to_discharge: Order from most charge to most discharged state? Defaults to True. Returns: A list of unstable entries in the electrode, ordered by amount of the working ion.
def get_unstable_entries(self, charge_to_discharge=True): """ Returns the unstable entries for the electrode. Args: charge_to_discharge: Order from most charge to most discharged state? Defaults to True. Returns: A list of unstable entries in the...
Return all entries input for the electrode. Args: charge_to_discharge: order from most charge to most discharged state? Defaults to True. Returns: A list of all entries in the electrode (both stable and unstable), ordered by amount of...
def get_all_entries(self, charge_to_discharge=True): """ Return all entries input for the electrode. Args: charge_to_discharge: order from most charge to most discharged state? Defaults to True. Returns: A list of all entries in t...
The maximum instability along a path for a specific voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum decomposition energy of all compounds along the insertion path (a subset of ...
def get_max_instability(self, min_voltage=None, max_voltage=None): """ The maximum instability along a path for a specific voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum d...
The minimum instability along a path for a specific voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Minimum decomposition energy of all compounds along the insertion path (a subset of ...
def get_min_instability(self, min_voltage=None, max_voltage=None): """ The minimum instability along a path for a specific voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Minimum d...
Maximum critical oxygen chemical potential along path. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum critical oxygen chemical of all compounds along the insertion path (a subset of the path...
def get_max_muO2(self, min_voltage=None, max_voltage=None): """ Maximum critical oxygen chemical potential along path. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum critical oxygen chem...
Minimum critical oxygen chemical potential along path. Args: min_voltage: The minimum allowable voltage for a given step max_voltage: The maximum allowable voltage allowable for a given step Returns: Minimum critical oxygen chemical of all compounds ...
def get_min_muO2(self, min_voltage=None, max_voltage=None): """ Minimum critical oxygen chemical potential along path. Args: min_voltage: The minimum allowable voltage for a given step max_voltage: The maximum allowable voltage allowable for a given step ...
If this electrode contains multiple voltage steps, then it is possible to use only a subset of the voltage steps to define other electrodes. For example, an LiTiO2 electrode might contain three subelectrodes: [LiTiO2 --> TiO2, LiTiO2 --> Li0.5TiO2, Li0.5TiO2 --> TiO2] This method can be ...
def get_sub_electrodes(self, adjacent_only=True, include_myself=True): """ If this electrode contains multiple voltage steps, then it is possible to use only a subset of the voltage steps to define other electrodes. For example, an LiTiO2 electrode might contain three subelectrodes: ...
Generate a summary dict. Args: print_subelectrodes: Also print data on all the possible subelectrodes. Returns: A summary of this electrode"s properties in dict format.
def as_dict_summary(self, print_subelectrodes=True): """ Generate a summary dict. Args: print_subelectrodes: Also print data on all the possible subelectrodes. Returns: A summary of this electrode"s properties in dict format. """ ...
Creates zval_dictionary for calculating the ionic polarization from Potcar object potcar: Potcar object
def zval_dict_from_potcar(potcar): """ Creates zval_dictionary for calculating the ionic polarization from Potcar object potcar: Potcar object """ zval_dict = {} for p in potcar: zval_dict.update({p.element: p.ZVAL}) return zval_dict
Calculate the ionic dipole moment using ZVAL from pseudopotential site: PeriodicSite structure: Structure zval: Charge value for ion (ZVAL for VASP pseudopotential) Returns polarization in electron Angstroms.
def calc_ionic(site, structure, zval): """ Calculate the ionic dipole moment using ZVAL from pseudopotential site: PeriodicSite structure: Structure zval: Charge value for ion (ZVAL for VASP pseudopotential) Returns polarization in electron Angstroms. """ norms = structure.lattice.leng...
Get the total ionic dipole moment for a structure. structure: pymatgen Structure zval_dict: specie, zval dictionary pairs center (np.array with shape [3,1]) : dipole center used by VASP tiny (float) : tolerance for determining boundary of calculation.
def get_total_ionic_dipole(structure, zval_dict): """ Get the total ionic dipole moment for a structure. structure: pymatgen Structure zval_dict: specie, zval dictionary pairs center (np.array with shape [3,1]) : dipole center used by VASP tiny (float) : tolerance for determining boundary of ca...
Given coords and a site, find closet site to coords. Args: coords (3x1 array): cartesian coords of center of sphere site: site to find closest to coords r: radius of sphere. Defaults to diagonal of unit cell Returns: Closest site and distance.
def get_nearest_site(self, coords, site, r=None): """ Given coords and a site, find closet site to coords. Args: coords (3x1 array): cartesian coords of center of sphere site: site to find closest to coords r: radius of sphere. Defaults to diagonal of unit cel...
Create Polarization object from list of Outcars and Structures in order of nonpolar to polar. Note, we recommend calculating the ionic dipole moment using calc_ionic than using the values in Outcar (see module comments). To do this set calc_ionic_from_zval = True
def from_outcars_and_structures(cls, outcars, structures, calc_ionic_from_zval=False): """ Create Polarization object from list of Outcars and Structures in order of nonpolar to polar. Note, we recommend calculating the ionic dipole moment using calc_...
Get the electronic and ionic dipole moments / polarizations. convert_to_muC_per_cm2: Convert from electron * Angstroms to microCoulomb per centimeter**2
def get_pelecs_and_pions(self, convert_to_muC_per_cm2=False): """ Get the electronic and ionic dipole moments / polarizations. convert_to_muC_per_cm2: Convert from electron * Angstroms to microCoulomb per centimeter**2 """ if not convert_to_muC_per_cm2: ...
Get same branch dipole moment (convert_to_muC_per_cm2=False) or polarization for given polarization data (convert_to_muC_per_cm2=True). Polarization is a lattice vector, meaning it is only defined modulo the quantum of polarization: P = P_0 + \\sum_i \\frac{n_i e R_i}{\\Omega} ...
def get_same_branch_polarization_data(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Get same branch dipole moment (convert_to_muC_per_cm2=False) or polarization for given polarization data (convert_to_muC_per_cm2=True). Polarization is a lattice vector, meaning it is only d...
Returns the dipole / polarization quanta along a, b, and c for all structures.
def get_lattice_quanta(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Returns the dipole / polarization quanta along a, b, and c for all structures. """ lattices = [s.lattice for s in self.structures] volumes = np.array([s.lattice.volume for s in self.structur...
Get difference between nonpolar and polar same branch polarization.
def get_polarization_change(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Get difference between nonpolar and polar same branch polarization. """ tot = self.get_same_branch_polarization_data( convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_pola...
Get magnitude of difference between nonpolar and polar same branch polarization.
def get_polarization_change_norm(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Get magnitude of difference between nonpolar and polar same branch polarization. """ polar = self.structures[-1] a, b, c = polar.lattice.matrix a, b, c = a / np.linalg.norm...
Fit splines to same branch polarization. This is used to assess any jumps in the same branch polarizaiton.
def same_branch_splines(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Fit splines to same branch polarization. This is used to assess any jumps in the same branch polarizaiton. """ from scipy.interpolate import UnivariateSpline tot = self.get_same_branch_pola...
Get maximum difference between spline and same branch polarization data.
def max_spline_jumps(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Get maximum difference between spline and same branch polarization data. """ tot = self.get_same_branch_polarization_data( convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_polar)...
Get rms average difference between spline and same branch polarization data.
def smoothness(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Get rms average difference between spline and same branch polarization data. """ tot = self.get_same_branch_polarization_data( convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_polar) ...
Fit spline to energy trend data.
def spline(self): """ Fit spline to energy trend data. """ from scipy.interpolate import UnivariateSpline sp = UnivariateSpline(range(len(self.energies)), self.energies, k=4) return sp
Get rms average difference between spline and energy trend.
def smoothness(self): """ Get rms average difference between spline and energy trend. """ energies = self.energies try: sp = self.spline() except: print("Energy spline failed.") return None spline_energies = sp(range(len(energie...
Get maximum difference between spline and energy trend.
def max_spline_jump(self): """ Get maximum difference between spline and energy trend. """ sp = self.spline() return max(self.energies - sp(range(len(self.energies))))
Test if spline endpoints are at minima for a given slope cutoff.
def endpoints_minima(self, slope_cutoff=5e-3): """ Test if spline endpoints are at minima for a given slope cutoff. """ energies = self.energies try: sp = self.spline() except: print("Energy spline failed.") return None der = sp...
Process a single entry with the chosen Corrections. Args: entry: A ComputedEntry object. Returns: An adjusted entry if entry is compatible, otherwise None is returned.
def process_entry(self, entry): """ Process a single entry with the chosen Corrections. Args: entry: A ComputedEntry object. Returns: An adjusted entry if entry is compatible, otherwise None is returned. """ try: correctio...
Returns the corrections applied to a particular entry. Args: entry: A ComputedEntry object. Returns: ({correction_name: value})
def get_corrections_dict(self, entry): """ Returns the corrections applied to a particular entry. Args: entry: A ComputedEntry object. Returns: ({correction_name: value}) """ corrections = {} for c in self.corrections: val = c...
Provides an explanation dict of the corrections that are being applied for a given compatibility scheme. Inspired by the "explain" methods in many database methodologies. Args: entry: A ComputedEntry. Returns: (dict) of the form {"Compatibility": "st...
def get_explanation_dict(self, entry): """ Provides an explanation dict of the corrections that are being applied for a given compatibility scheme. Inspired by the "explain" methods in many database methodologies. Args: entry: A ComputedEntry. Returns: ...
Prints an explanation of the corrections that are being applied for a given compatibility scheme. Inspired by the "explain" methods in many database methodologies. Args: entry: A ComputedEntry.
def explain(self, entry): """ Prints an explanation of the corrections that are being applied for a given compatibility scheme. Inspired by the "explain" methods in many database methodologies. Args: entry: A ComputedEntry. """ d = self.get_explanatio...
Reads a string representation to a Cssr object. Args: string (str): A string representation of a CSSR. Returns: Cssr object.
def from_string(string): """ Reads a string representation to a Cssr object. Args: string (str): A string representation of a CSSR. Returns: Cssr object. """ lines = string.split("\n") toks = lines[0].split() lengths = [float(i) f...
Returns conversion factor from THz to the requred units and the label in the form of a namedtuple Accepted values: thz, ev, mev, ha, cm-1, cm^-1
def freq_units(units): """ Returns conversion factor from THz to the requred units and the label in the form of a namedtuple Accepted values: thz, ev, mev, ha, cm-1, cm^-1 """ d = {"thz": FreqUnits(1, "THz"), "ev": FreqUnits(const.value("hertz-electron volt relationship") * const.tera, "eV...
Adds a dos for plotting. Args: label: label for the DOS. Must be unique. dos: PhononDos object
def add_dos(self, label, dos): """ Adds a dos for plotting. Args: label: label for the DOS. Must be unique. dos: PhononDos object """ densities = dos.get_smeared_densities(self.sigma) if self.sigma \ else dos.d...
Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys.
def add_dos_dict(self, dos_dict, key_sort_func=None): """ Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys. """ if key_sort_func:...
Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1.
def get_plot(self, xlim=None, ylim=None, units="thz"): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. units: units for the frequen...
Show the plot using matplotlib. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1.
def show(self, xlim=None, ylim=None, units="thz"): """ Show the plot using matplotlib. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. units: units for the frequencies. Accep...
utility private method to add ticks to a band structure
def _maketicks(self, plt): """ utility private method to add ticks to a band structure """ ticks = self.get_ticks() # Sanitize only plot the uniq values uniq_d = [] uniq_l = [] temp_ticks = list(zip(ticks['distance'], ticks['label'])) for i in rang...
Get the data nicely formatted for a plot Returns: A dict of the following format: ticks: A dict with the 'distances' at which there is a qpoint (the x axis) and the labels (None if no label) frequencies: A list (one element for each branch) of frequencies for ...
def bs_plot_data(self): """ Get the data nicely formatted for a plot Returns: A dict of the following format: ticks: A dict with the 'distances' at which there is a qpoint (the x axis) and the labels (None if no label) frequencies: A list (one el...
Get a matplotlib object for the bandstructure plot. Args: ylim: Specify the y-axis (frequency) limits; by default None let the code choose. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1.
def get_plot(self, ylim=None, units="thz"): """ Get a matplotlib object for the bandstructure plot. Args: ylim: Specify the y-axis (frequency) limits; by default None let the code choose. units: units for the frequencies. Accepted values thz, ev, mev, ha,...
Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. ylim: Specifies the y-axis limits. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1.
def save_plot(self, filename, img_format="eps", ylim=None, units="thz"): """ Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. ylim: Specifies the y-axis limits. units: units fo...
Get all ticks and labels for a band structure plot. Returns: A dict with 'distance': a list of distance at which ticks should be set and 'label': a list of label for each of those ticks.
def get_ticks(self): """ Get all ticks and labels for a band structure plot. Returns: A dict with 'distance': a list of distance at which ticks should be set and 'label': a list of label for each of those ticks. """ tick_distance = [] tick_labels ...
plot two band structure for comparison. One is in red the other in blue. The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the PhononBSPlotter Args: another PhononBSPl...
def plot_compare(self, other_plotter): """ plot two band structure for comparison. One is in red the other in blue. The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the Ph...
plot the Brillouin zone
def plot_brillouin(self): """ plot the Brillouin zone """ # get labels and lines labels = {} for q in self._bs.qpoints: if q.label: labels[q.label] = q.frac_coords lines = [] for b in self._bs.branches: lines.appen...
Plots a thermodynamic property for a generic function from a PhononDos instance. Args: func: the thermodynamic function to be used to calculate the property temperatures: a list of temperatures factor: a multiplicative factor applied to the thermodynamic property calculated....
def _plot_thermo(self, func, temperatures, factor=1, ax=None, ylabel=None, label=None, ylim=None, **kwargs): """ Plots a thermodynamic property for a generic function from a PhononDos instance. Args: func: the thermodynamic function to be used to calculate the property t...
Plots the constant volume specific heat C_v in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib function 'plot'. ...
def plot_cv(self, tmin, tmax, ntemp, ylim=None, **kwargs): """ Plots the constant volume specific heat C_v in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis l...
Plots the vibrational entrpy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib function 'plot'. Returns: ...
def plot_entropy(self, tmin, tmax, ntemp, ylim=None, **kwargs): """ Plots the vibrational entrpy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. ...
Plots the vibrational internal energy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib function 'plot'. R...
def plot_internal_energy(self, tmin, tmax, ntemp, ylim=None, **kwargs): """ Plots the vibrational internal energy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y...
Plots the vibrational contribution to the Helmoltz free energy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib f...
def plot_helmholtz_free_energy(self, tmin, tmax, ntemp, ylim=None, **kwargs): """ Plots the vibrational contribution to the Helmoltz free energy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ...
Plots all the thermodynamic properties in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib function 'plot'. ...
def plot_thermodynamic_properties(self, tmin, tmax, ntemp, ylim=None, **kwargs): """ Plots all the thermodynamic properties in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specif...
Create a dictionary representation of a PWInput object Returns: dict
def as_dict(self): """ Create a dictionary representation of a PWInput object Returns: dict """ pwinput_dict = {'structure': self.structure.as_dict(), 'pseudo': self.pseudo, 'sections': self.sections, ...
Load a PWInput object from a dictionary. Args: pwinput_dict (dict): dictionary with PWInput data Returns: PWInput object
def from_dict(cls, pwinput_dict): """ Load a PWInput object from a dictionary. Args: pwinput_dict (dict): dictionary with PWInput data Returns: PWInput object """ pwinput = cls(structure=Structure.from_dict(pwinput_dict['struc...
Write the PWSCF input file. Args: filename (str): The string filename to output to.
def write_file(self, filename): """ Write the PWSCF input file. Args: filename (str): The string filename to output to. """ with open(filename, "w") as f: f.write(self.__str__())
Reads an PWInput object from a string. Args: string (str): PWInput string Returns: PWInput object
def from_string(string): """ Reads an PWInput object from a string. Args: string (str): PWInput string Returns: PWInput object """ lines = list(clean_lines(string.splitlines())) def input_mode(line): if line[0] == "&": ...
Static helper method to convert PWINPUT parameters to proper type, e.g., integers, floats, etc. Args: key: PWINPUT parameter key val: Actual value of PWINPUT parameter.
def proc_val(key, val): """ Static helper method to convert PWINPUT parameters to proper type, e.g., integers, floats, etc. Args: key: PWINPUT parameter key val: Actual value of PWINPUT parameter. """ float_keys = ('etot_conv_thr','forc_conv_thr',...
General pattern reading. Uses monty's regrep method. Takes the same arguments. Args: patterns (dict): A dict of patterns, e.g., {"energy": r"energy\\(sigma->0\\)\\s+=\\s+([\\d\\-.]+)"}. reverse (bool): Read files in reverse. Defaults to false. Useful for ...
def read_pattern(self, patterns, reverse=False, terminate_on_match=False, postprocess=str): """ General pattern reading. Uses monty's regrep method. Takes the same arguments. Args: patterns (dict): A dict of patterns, e.g., {"energy": r"e...
Print to the given stream the template of the :class:`QueueAdapter` of type `qtype`.
def show_qparams(qtype, stream=sys.stdout): """Print to the given stream the template of the :class:`QueueAdapter` of type `qtype`.""" for cls in all_subclasses(QueueAdapter): if cls.QTYPE == qtype: return stream.write(cls.QTEMPLATE) raise ValueError("Cannot find class associated to qtype %s" % qty...
Return the concrete :class:`QueueAdapter` class from a string. Note that one can register a customized version with: .. example:: from qadapters import SlurmAdapter class MyAdapter(SlurmAdapter): QTYPE = "myslurm" # Add your customized code here # Register you...
def make_qadapter(**kwargs): """ Return the concrete :class:`QueueAdapter` class from a string. Note that one can register a customized version with: .. example:: from qadapters import SlurmAdapter class MyAdapter(SlurmAdapter): QTYPE = "myslurm" # Add your cus...
Convert an object into a OmpEnv
def as_ompenv(cls, obj): """Convert an object into a OmpEnv""" if isinstance(obj, cls): return obj if obj is None: return cls() return cls(**obj)
Build and return a string with the command required to launch `executable` with the qadapter `qad`. Args qad: Qadapter instance. executable (str): Executable name or path stdin (str): Name of the file to be used as standard input. None means no redirection. stdou...
def string_to_run(self, qad, executable, stdin=None, stdout=None, stderr=None, exec_args=None): """ Build and return a string with the command required to launch `executable` with the qadapter `qad`. Args qad: Qadapter instance. executable (str): Executable name or path ...
Provides a simple though not complete dict serialization of the object (OMP missing, not all limits are kept in the dictionary, ... other things to be checked) Raise: `ValueError` if errors.
def as_dict(self): """ Provides a simple though not complete dict serialization of the object (OMP missing, not all limits are kept in the dictionary, ... other things to be checked) Raise: `ValueError` if errors. """ if self.has_omp: raise NotImp...
Check if the keys specified by the user in qparams are supported. Raise: `ValueError` if errors.
def validate_qparams(self): """ Check if the keys specified by the user in qparams are supported. Raise: `ValueError` if errors. """ # No validation for ShellAdapter. if isinstance(self, ShellAdapter): return # Parse the template so that we know the ...
Save submission
def record_launch(self, queue_id): # retcode): """Save submission""" self.launches.append( AttrDict(queue_id=queue_id, mpi_procs=self.mpi_procs, omp_threads=self.omp_threads, mem_per_proc=self.mem_per_proc, timelimit=self.timelimit)) return len(self.launches)
Validate the parameters of the run. Raises self.Error if invalid parameters.
def validate(self): """Validate the parameters of the run. Raises self.Error if invalid parameters.""" errors = [] app = errors.append if not self.hint_cores >= self.mpi_procs * self.omp_threads >= self.min_cores: app("self.hint_cores >= mpi_procs * omp_threads >= self.min_c...
True if the qadapter in principle is able to run the :class:`ParalConf` pconf
def can_run_pconf(self, pconf): """True if the qadapter in principle is able to run the :class:`ParalConf` pconf""" if not self.hint_cores >= pconf.num_cores >= self.min_cores: return False if not self.hw.can_use_omp_threads(self.omp_threads): return False if pconf.mem_per_proc > self.hw...
Returns (num_nodes, mpi_per_node) Aggressive: When Open MPI thinks that it is in an exactly- or under-subscribed mode (i.e., the number of running processes is equal to or less than the number of available processors), MPI processes will automatically run in aggressive mode, meaning that they w...
def distribute(self, mpi_procs, omp_threads, mem_per_proc): """ Returns (num_nodes, mpi_per_node) Aggressive: When Open MPI thinks that it is in an exactly- or under-subscribed mode (i.e., the number of running processes is equal to or less than the number of available processors), ...
Return substitution dict for replacements into the template Subclasses may want to customize this method.
def get_subs_dict(self, qnodes=None): """ Return substitution dict for replacements into the template Subclasses may want to customize this method. """ #d = self.qparams.copy() d = self.qparams d.update(self.optimize_params(qnodes=qnodes)) # clean null val...
Return a string with the options that are passed to the resource manager.
def _make_qheader(self, job_name, qout_path, qerr_path): """Return a string with the options that are passed to the resource manager.""" # get substitution dict for replacements into the template subs_dict = self.get_subs_dict() # Set job_name and the names for the stderr and stdout of ...
Returns a (multi-line) String representing the queue script, e.g. PBS script. Uses the template_file along with internal parameters to create the script. Args: job_name: Name of the job. launch_dir: (str) The directory the job will be launched in. executable: String ...
def get_script_str(self, job_name, launch_dir, executable, qout_path, qerr_path, stdin=None, stdout=None, stderr=None, exec_args=None): """ Returns a (multi-line) String representing the queue script, e.g. PBS script. Uses the template_file along with internal parameters t...
Public API: wraps the concrete implementation _submit_to_queue Raises: `self.MaxNumLaunchesError` if we have already tried to submit the job max_num_launches `self.Error` if generic error
def submit_to_queue(self, script_file): """ Public API: wraps the concrete implementation _submit_to_queue Raises: `self.MaxNumLaunchesError` if we have already tried to submit the job max_num_launches `self.Error` if generic error """ if not os.path.exis...
returns the number of jobs in the queue, probably using subprocess or shutil to call a command like 'qstat'. returns None when the number of jobs cannot be determined. Args: username: (str) the username of the jobs to count (default is to autodetect)
def get_njobs_in_queue(self, username=None): """ returns the number of jobs in the queue, probably using subprocess or shutil to call a command like 'qstat'. returns None when the number of jobs cannot be determined. Args: username: (str) the username of the jobs to count (d...
Method to increase the amount of memory asked for, by factor. Return: new memory if success, 0 if memory cannot be increased.
def more_mem_per_proc(self, factor=1): """ Method to increase the amount of memory asked for, by factor. Return: new memory if success, 0 if memory cannot be increased. """ base_increase = 2000 old_mem = self.mem_per_proc new_mem = old_mem + factor*base_increase ...
Method to increase the amount of memory overheaded asked for the master node. Return: new master memory overhead if success, 0 if it cannot be increased.
def more_master_mem_overhead(self, mem_increase_mb=1000): """ Method to increase the amount of memory overheaded asked for the master node. Return: new master memory overhead if success, 0 if it cannot be increased. """ old_master_mem_overhead = self.master_mem_overhead n...
Method to increase the number of MPI procs. Return: new number of processors if success, 0 if processors cannot be increased.
def more_cores(self, factor=1): """ Method to increase the number of MPI procs. Return: new number of processors if success, 0 if processors cannot be increased. """ # TODO : find a formula that works for all max_cores if self.max_cores > 40: base_increase = 4 *...
Method to increase the wall time
def more_time(self, factor=1): """ Method to increase the wall time """ base_increase = int(self.timelimit_hard / 10) new_time = self.timelimit + base_increase*factor print('qadapter: trying to increase time') if new_time < self.timelimit_hard: self.s...
Set the memory per process in megabytes
def set_mem_per_proc(self, mem_mb): """Set the memory per process in megabytes""" super().set_mem_per_proc(mem_mb) self.qparams["mem_per_cpu"] = self.mem_per_proc
Select is not the most intuitive command. For more info see: * http://www.cardiff.ac.uk/arcca/services/equipment/User-Guide/pbs.html * https://portal.ivec.org/docs/Supercomputers/PBS_Pro
def get_select(self, ret_dict=False, qnodes=None, memory_policy=None): """ Select is not the most intuitive command. For more info see: * http://www.cardiff.ac.uk/arcca/services/equipment/User-Guide/pbs.html * https://portal.ivec.org/docs/Supercomputers/PBS_Pro """ ...
Submit a job script to the queue.
def _submit_to_queue(self, script_file): """Submit a job script to the queue.""" if sys.version_info[0] < 3: process = Popen(['qsub', script_file], stdout=PIPE, stderr=PIPE) else: # need string not bytes so must use universal_newlines process = Popen(['qsub', ...
Set the number of CPUs used for MPI.
def set_mpi_procs(self, mpi_procs): """Set the number of CPUs used for MPI.""" QueueAdapter.set_mpi_procs(self, mpi_procs) num_nodes, rest_cores = self.hw.divmod_node(mpi_procs, omp_threads=1) if num_nodes == 0: self.qparams["nodes"] = 1 self.qparams["ppn"] = mpi...
Set the memory per process in megabytes
def set_mem_per_proc(self, mem_mb): """Set the memory per process in megabytes""" super().set_mem_per_proc(mem_mb) self.qparams["mem_per_slot"] = str(int(self.mem_per_proc)) + "M"
Limits are specified with the format hh:mm:ss (hours:minutes:seconds)
def set_timelimit(self, timelimit): """Limits are specified with the format hh:mm:ss (hours:minutes:seconds)""" super().set_timelimit(timelimit) self.qparams["wall_clock_limit"] = qu.time2loadlever(timelimit)
Return (bg_size, ranks_per_node) from mpi_procs and omp_threads.
def bgsize_rankspernode(self): """Return (bg_size, ranks_per_node) from mpi_procs and omp_threads.""" bg_size = int(math.ceil((self.mpi_procs * self.omp_threads)/ self.hw.cores_per_node)) bg_size = max(bg_size, 32) # TODO hardcoded ranks_per_node = int(math.ceil(self.mpi_procs / bg_size)) retu...
[a[0], b[0], ... , a[1], b[1], ..., a[n], b[n] ...] >>> alternate([1,4], [2,5], [3,6]) [1, 2, 3, 4, 5, 6]
def alternate(*iterables): """ [a[0], b[0], ... , a[1], b[1], ..., a[n], b[n] ...] >>> alternate([1,4], [2,5], [3,6]) [1, 2, 3, 4, 5, 6] """ items = [] for tup in zip(*iterables): items.extend([item for item in tup]) return items
Scan directory tree starting from top, look for files with extension `ext` and parse timing data. Return: (parser, paths, okfiles) where `parser` is the new object, `paths` is the list of files found and `okfiles` is the list of files that have been parsed successfully. ...
def walk(cls, top=".", ext=".abo"): """ Scan directory tree starting from top, look for files with extension `ext` and parse timing data. Return: (parser, paths, okfiles) where `parser` is the new object, `paths` is the list of files found and `okfiles` is the li...
Read and parse a filename or a list of filenames. Files that cannot be opened are ignored. A single filename may also be given. Return: list of successfully read files.
def parse(self, filenames): """ Read and parse a filename or a list of filenames. Files that cannot be opened are ignored. A single filename may also be given. Return: list of successfully read files. """ filenames = list_strings(filenames) read_ok = [] ...
Parse the TIMER section
def _read(self, fh, fname): """Parse the TIMER section""" if fname in self._timers: raise self.Error("Cannot overwrite timer associated to: %s " % fname) def parse_line(line): """Parse single line.""" name, vals = line[:25], line[25:].split() try:...
Return the list of timers associated to the given `filename` and MPI rank mpi_rank.
def timers(self, filename=None, mpi_rank="0"): """ Return the list of timers associated to the given `filename` and MPI rank mpi_rank. """ if filename is not None: return [self._timers[filename][mpi_rank]] else: return [self._timers[filename][mpi_rank] for...
Return the names of sections ordered by ordkey. For the time being, the values are taken from the first timer.
def section_names(self, ordkey="wall_time"): """ Return the names of sections ordered by ordkey. For the time being, the values are taken from the first timer. """ section_names = [] # FIXME this is not trivial for idx, timer in enumerate(self.timers()): ...
Return the list of sections stored in self.timers() given `section_name` A fake section is returned if the timer does not have section_name.
def get_sections(self, section_name): """ Return the list of sections stored in self.timers() given `section_name` A fake section is returned if the timer does not have section_name. """ sections = [] for timer in self.timers(): for sect in timer.sections: ...
Analyze the parallel efficiency. Return: :class:`ParallelEfficiency` object.
def pefficiency(self): """ Analyze the parallel efficiency. Return: :class:`ParallelEfficiency` object. """ timers = self.timers() # Number of CPUs employed in each calculation. ncpus = [timer.ncpus for timer in timers] # Find the minimum nu...
Return pandas DataFrame with the most important results stored in the timers.
def summarize(self, **kwargs): """ Return pandas DataFrame with the most important results stored in the timers. """ import pandas as pd colnames = ["fname", "wall_time", "cpu_time", "mpi_nprocs", "omp_nthreads", "mpi_rank"] frame = pd.DataFrame(columns=colnames) ...
Plot the parallel efficiency Args: key: Parallel efficiency is computed using the wall_time. what: Specifies what to plot: `good` for sections with good parallel efficiency. `bad` for sections with bad efficiency. Options can be concatenated with `+`. nmax: M...
def plot_efficiency(self, key="wall_time", what="good+bad", nmax=5, ax=None, **kwargs): """ Plot the parallel efficiency Args: key: Parallel efficiency is computed using the wall_time. what: Specifies what to plot: `good` for sections with good parallel efficiency. ...
Plot pie charts of the different timers. Args: key: Keyword used to extract data from timers. minfract: Don't show sections whose relative weight is less that minfract. Returns: `matplotlib` figure
def plot_pie(self, key="wall_time", minfract=0.05, **kwargs): """ Plot pie charts of the different timers. Args: key: Keyword used to extract data from timers. minfract: Don't show sections whose relative weight is less that minfract. Returns: `matpl...
Plot stacked histogram of the different timers. Args: key: Keyword used to extract data from the timers. Only the first `nmax` sections with largest value are show. mmax: Maximum nuber of sections to show. Other entries are grouped together in the `others...
def plot_stacked_hist(self, key="wall_time", nmax=5, ax=None, **kwargs): """ Plot stacked histogram of the different timers. Args: key: Keyword used to extract data from the timers. Only the first `nmax` sections with largest value are show. mmax: Maximum...