_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q19100
SDOSPlotter.dos_plot_data
train
def dos_plot_data(self, yscale=1, xmin=-6., xmax=6., colours=None, plot_total=True, legend_cutoff=3, subplot=False, zero_to_efermi=True, cache=None): """Get the plotting data. Args: yscale (:obj:`float`, optional): Scaling factor for the y-axis. xmin (:obj:`float`, optional): The minimum energy to mask the energy and density of states data (reduces plotting load). xmax (:obj:`float`, optional): The maximum energy to mask the energy and density of states data (reduces plotting load). colours (:obj:`dict`, optional): Use custom colours for specific element and orbital combinations. Specified as a :obj:`dict` of :obj:`dict` of the colours. For example:: { 'Sn': {'s': 'r', 'p': 'b'}, 'O': {'s': '#000000'} } The colour can be a hex code, series of rgb value, or any other format supported by matplotlib. plot_total (:obj:`bool`, optional): Plot the total density of states. Defaults to ``True``. legend_cutoff (:obj:`float`, optional): The cut-off (in % of the maximum density of states within the plotting range) for an elemental orbital to be labelled in the legend. This prevents the legend from containing labels for orbitals that have very little contribution in the plotting range. subplot (:obj:`bool`, optional): Plot the density of states for each element on separate subplots. Defaults to ``False``. zero_to_efermi (:obj:`bool`, optional): Normalise the plot such that the Fermi level is set as 0 eV. cache (:obj:`dict`, optional): Cache object tracking how colours have been assigned to orbitals. The format is the same as the "colours" dict. This defaults to the module-level sumo.plotting.colour_cache object, but an empty dict can be used as a fresh cache. This object will be modified in-place. Returns: dict: The plotting data. Formatted with the following keys: "energies" (:obj:`numpy.ndarray`) The energies. "mask" (:obj:`numpy.ndarray`) A mask used to trim the density of states data and prevent unwanted data being included in the output file. "lines" (:obj:`list`) A :obj:`list` of :obj:`dict` containing the density data and some metadata. Each line :obj:`dict` contains the keys: "label" (:obj:`str`) The label for the legend. "dens" (:obj:`numpy.ndarray`) The density of states data. "colour" (:obj:`str`) The colour of the line. "alpha" (:obj:`float`) The alpha value for line fill. "ymin" (:obj:`float`) The minimum y-axis limit. "ymax" (:obj:`float`) The maximum y-axis limit. """ if cache is None: cache = colour_cache # mask needed to prevent unwanted data in pdf and for finding y limit
python
{ "resource": "" }
q19101
get_projections_by_branches
train
def get_projections_by_branches(bs, selection, normalise=None): """Returns orbital projections for each branch in a band structure. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): The band structure. selection (list): A list of :obj:`tuple` or :obj:`string` identifying which projections to return. Projections can be specified by both element and orbital, for example:: [('Sn', 's'), ('Bi', 'p'), ('S', 'p')] If just the element is specified then all the orbitals of that element are combined. For example, the following will combine all the S orbitals into a single projection:: [('Bi', 's'), ('Bi', 'p'), 'S'] Particular orbitals can also be combined, for example:: [('Bi', 's'), ('Bi', 'p'), ('S', ('s', 'p', 'd'))] normalise (:obj:`str`, optional): Normalisation the projections. Options are: * ``'all'``: Projections normalised against the sum of all other projections. * ``'select'``: Projections normalised against the sum of the selected projections. * ``None``: No normalisation performed. Defaults to ``None``.
python
{ "resource": "" }
q19102
get_projections
train
def get_projections(bs, selection, normalise=None): """Returns orbital projections from a band structure. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): The band structure. selection (list): A list of :obj:`tuple` or :obj:`string` identifying which projections to return. Projections can be specified by both element and orbital, for example:: [('Bi', 's'), ('Bi', 'p'), ('S', 'p')] If just the element is specified then all the orbitals of that element are combined. For example, the following will combine all the S orbitals into a single projection:: [('Bi', 's'), ('Bi', 'p'), 'S'] Particular orbitals can also be combined, for example:: [('Bi', 's'), ('Bi', 'p'), ('S', ('s', 'p', 'd'))] normalise (:obj:`str`, optional): Normalisation the projections. Options are: * ``'all'``: Projections normalised against the sum of all other projections. * ``'select'``: Projections normalised against the sum of the selected projections. * ``None``: No normalisation performed. Defaults to ``None``. Returns: list: A ``list`` of orbital projections, in the same order as specified in ``selection``, with the format:: [ {spin: projections}, {spin: projections} ... ] Where spin is a :obj:`pymatgen.electronic_structure.core.Spin` object and projections is a :obj:`numpy.array` of:: projections[band_index][kpoint_index] If there are no projections in the band structure, then an array of zeros
python
{ "resource": "" }
q19103
SBSPlotter._makeplot
train
def _makeplot(self, ax, fig, data, zero_to_efermi=True, vbm_cbm_marker=False, ymin=-6., ymax=6., height=None, width=None, dos_plotter=None, dos_options=None, dos_label=None, aspect=None): """Tidy the band structure & add the density of states if required.""" # draw line at Fermi level if not zeroing to e-Fermi if not zero_to_efermi: ytick_color = rcParams['ytick.color'] ef = self._bs.efermi ax.axhline(ef, color=ytick_color) # set x and y limits ax.set_xlim(0, data['distances'][-1][-1]) if self._bs.is_metal() and not zero_to_efermi: ax.set_ylim(self._bs.efermi + ymin, self._bs.efermi + ymax) else: ax.set_ylim(ymin, ymax) if vbm_cbm_marker: for cbm in data['cbm']: ax.scatter(cbm[0], cbm[1], color='C2', marker='o', s=100) for vbm in data['vbm']: ax.scatter(vbm[0], vbm[1], color='C3', marker='o', s=100) if dos_plotter: ax = fig.axes[1]
python
{ "resource": "" }
q19104
SBSPlotter._makedos
train
def _makedos(self, ax, dos_plotter, dos_options, dos_label=None): """This is basically the same as the SDOSPlotter get_plot function.""" # don't use first 4 colours; these are the band structure line colours cycle = cycler( 'color', rcParams['axes.prop_cycle'].by_key()['color'][4:]) with context({'axes.prop_cycle': cycle}): plot_data = dos_plotter.dos_plot_data(**dos_options) mask = plot_data['mask'] energies = plot_data['energies'][mask] lines = plot_data['lines'] spins = [Spin.up] if len(lines[0][0]['dens']) == 1 else \ [Spin.up, Spin.down] for line_set in plot_data['lines']: for line, spin in it.product(line_set, spins): if spin == Spin.up: label = line['label'] densities = line['dens'][spin][mask] else: label = ""
python
{ "resource": "" }
q19105
Kpath.correct_structure
train
def correct_structure(self, atol=1e-8): """Determine if the structure matches the standard primitive structure. The standard primitive will be different between seekpath and pymatgen high-symmetry paths, but this is handled by the specific subclasses. Args:
python
{ "resource": "" }
q19106
Kpath.get_kpoints
train
def get_kpoints(self, line_density=20, cart_coords=False, phonopy=False): r"""Return a list of k-points and labels along the high-symmetry path. The format of the returned data will be different if phonopy is ``True`` or ``False``. This is because phonopy requires the labels and kpoints to be provided in a different format than kgen. Adapted from :obj:`pymatgen.symmetry.bandstructure.HighSymmKpath.get_kpoints`. Args: line_density (:obj:`int`, optional): Density of k-points along the path. cart_coords (:obj:`bool`, optional): Whether the k-points are returned in cartesian or reciprocal coordinates. Defaults to ``False`` (fractional coordinates). phonopy (:obj:`bool`, optional): Format the k-points and labels for use with phonopy. Defaults to ``False``. Returns: tuple: A :obj:`tuple` of the k-points along the high-symmetry path, and k-point labels. Returned as ``(kpoints, labels)``. If ``phonopy == False``, then: * ``kpoints`` is a :obj:`numpy.ndarray` of the k-point coordinates along the high-symmetry path. For example:: [[0, 0, 0], [0.25, 0, 0], [0.5, 0, 0], [0.5, 0, 0.25], [0.5, 0, 0.5]] * ``labels`` is a :obj:`list` of the high symmetry labels for each k-point (will be an empty :obj:`str` if the k-point has no label). For example:: ['\Gamma', '', 'X', '', 'Y'] If ``phonopy == True``, then: * ``kpoints`` is a :obj:`list` of :obj:`numpy.ndarray` containing the k-points for each branch of the band structure. This means that the first and last k-points of a particular branch may be repeated. For example:: [[[0, 0, 0], [0.25, 0, 0], [0.5, 0, 0]], [[0.5, 0, 0], [0.5, 0, 0.25], [0.5, 0, 0.5]]] * ``labels`` is a :obj:`list` of the high symmetry labels. For example:: ['\Gamma', 'X', 'Y'] """ list_k_points = [] sym_point_labels = [] recip_lattice = self.structure.lattice.reciprocal_lattice for b in self.path: for i in range(1, len(b)): start = np.array(self.kpoints[b[i - 1]]) end = np.array(self.kpoints[b[i]]) distance = np.linalg.norm( recip_lattice.get_cartesian_coords(start) - recip_lattice.get_cartesian_coords(end)) nb = int(np.ceil(distance * line_density)) sym_point_labels.extend([b[i - 1]] + [''] * (nb - 1)) limit = nb + 1 if phonopy else nb kpts = [recip_lattice.get_cartesian_coords(start) + float(i) / float(nb) * (recip_lattice.get_cartesian_coords(end) - recip_lattice.get_cartesian_coords(start)) for i in range(0, limit)] if phonopy: list_k_points.append(kpts) else:
python
{ "resource": "" }
q19107
Kpath.get_lattice_type
train
def get_lattice_type(number): """Return the lattice crystal system. Hexagonal cells are differentiated into rhombohedral and hexagonal lattices. Args: number (int): The international space group number. Returns: str: The lattice crystal system. """ f = lambda i, j: i <= number <= j cs = {'triclinic': (1, 2), 'monoclinic': (3, 15), 'orthorhombic': (16, 74), 'tetragonal': (75, 142), 'trigonal': (143, 167), 'hexagonal': (168, 194), 'cubic': (195, 230)} crystal_system
python
{ "resource": "" }
q19108
get_fitting_data
train
def get_fitting_data(bs, spin, band_id, kpoint_id, num_sample_points=3): """Extract fitting data for band extrema based on spin, kpoint and band. Searches forward and backward from the extrema point, but will only sample there data if there are enough points in that direction. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): The band structure. spin (:obj:`~pymatgen.electronic_structure.core.Spin`): Which spin channel to sample. band_id (int): Index of the band to sample. kpoint_id (int): Index of the kpoint to sample. Returns: list: The data necessary to calculate the effective mass, along with some metadata. Formatted as a :obj:`list` of :obj:`dict`, each with the keys: 'energies' (:obj:`numpy.ndarray`) Band eigenvalues in eV. 'distances' (:obj:`numpy.ndarray`) Distances of the k-points in reciprocal space. 'band_id' (:obj:`int`) The index of the band, 'spin' (:obj:`~pymatgen.electronic_structure.core.Spin`) The spin channel 'start_kpoint' (:obj:`int`) The index of the k-point at which the band extrema occurs 'end_kpoint' (:obj:`int`) The k-point towards which the data has been sampled. """ # branch data provides data about the start and end points # of specific band paths branch_data = [b for b in bs.get_branch(kpoint_id)
python
{ "resource": "" }
q19109
fit_effective_mass
train
def fit_effective_mass(distances, energies, parabolic=True): """Fit the effective masses using either a parabolic or nonparabolic fit. Args: distances (:obj:`numpy.ndarray`): The x-distances between k-points in reciprocal Angstroms, normalised to the band extrema. energies (:obj:`numpy.ndarray`): The band eigenvalues normalised to the eigenvalue of the band extrema. parabolic (:obj:`bool`, optional): Use a parabolic fit of the band edges. If ``False`` then nonparabolic fitting will be attempted. Defaults to ``True``. Returns: float: The effective mass in units of electron rest mass, :math:`m_0`. """ if parabolic: fit = np.polyfit(distances, energies, 2) c = 2 * fit[0] # curvature therefore 2 * the exponent on the ^2 term else: # Use non parabolic description of the bands def f(x, alpha, d): top = np.sqrt(4 * alpha * d * x**2 + 1) - 1 bot = 2 * alpha
python
{ "resource": "" }
q19110
get_path_data
train
def get_path_data(structure, mode='bradcrack', symprec=0.01, spg=None, line_density=60, cart_coords=False, kpt_list=None, labels=None, phonopy=False): r"""Get the k-point path, coordinates and symmetry labels for a structure. If a manual :obj:`list` of kpoints is supplied using the ``kpt_list`` variable, the ``mode`` option will be ignored. The format of the returned data will be different if phonopy is ``True`` or ``False``. This is because phonopy requires the labels and kpoints to be provided in a different format than kgen. Args: structure (:obj:`~pymatgen.core.structure.Structure`): The structure. mode (:obj:`str`, optional): Method used for calculating the high-symmetry path. The options are: bradcrack Use the paths from Bradley and Cracknell. See [brad]_. pymatgen Use the paths from pymatgen. See [curt]_. seekpath Use the paths from SeeK-path. See [seek]_. symprec (:obj:`float`, optional): The tolerance for determining the crystal symmetry. spg (:obj:`~pymatgen.symmetry.groups.SpaceGroup`, optional): Space group used to override the symmetry determined by spglib. This is not recommended and only provided for testing purposes. This option will only take effect when ``mode = 'bradcrack'``. line_density (:obj:`int`, optional): Density of k-points along the path. cart_coords (:obj:`bool`, optional): Whether the k-points are returned in cartesian or reciprocal coordinates. Defaults to ``False`` (fractional coordinates). kpt_list (:obj:`list`, optional): List of k-points to use, formatted as a list of subpaths, each containing a list of fractional k-points. For example:: [ [[0., 0., 0.], [0., 0., 0.5]], [[0.5, 0., 0.], [0.5, 0.5, 0.]] ] Will return points along ``0 0 0 -> 0 0 1/2 | 1/2 0 0 -> 1/2 1/2 0`` path_labels (:obj:`list`, optional): The k-point labels. These should be provided as a :obj:`list` of :obj:`str` for each subpath of the
python
{ "resource": "" }
q19111
write_kpoint_files
train
def write_kpoint_files(filename, kpoints, labels, make_folders=False, ibzkpt=None, kpts_per_split=None, directory=None, cart_coords=False): r"""Write the k-points data to VASP KPOINTS files. Folders are named as 'split-01', 'split-02', etc ... KPOINTS files are named KPOINTS_band_split_01 etc ... Args: filename (:obj:`str`): Path to VASP structure file. kpoints (:obj:`numpy.ndarray`): The k-point coordinates along the high-symmetry path. For example:: [[0, 0, 0], [0.25, 0, 0], [0.5, 0, 0], [0.5, 0, 0.25], [0.5, 0, 0.5]] labels (:obj:`list`) The high symmetry labels for each k-point (will be an empty :obj:`str` if the k-point has no label). For example:: ['\Gamma', '', 'X', '', 'Y'] make_folders (:obj:`bool`, optional): Generate folders and copy in required files (INCAR, POTCAR, POSCAR, and possibly CHGCAR) from the current directory. ibzkpt (:obj:`str`, optional): Path to IBZKPT file. If set, the generated k-points will be appended to the k-points in this file and given a weight of 0. This is necessary for hybrid band structure calculations. kpts_per_split (:obj:`int`, optional): If set, the k-points are split into separate k-point files (or folders) each containing the number of k-points specified. This is useful for hybrid band structure calculations where it is often intractable to calculate all k-points in the same calculation. directory (:obj:`str`, optional): The output file directory. cart_coords (:obj:`bool`, optional): Whether the k-points are returned in cartesian or reciprocal coordinates. Defaults to ``False`` (fractional coordinates). """ if kpts_per_split: kpt_splits = [kpoints[i:i+kpts_per_split] for i in range(0, len(kpoints), kpts_per_split)] label_splits = [labels[i:i+kpts_per_split] for i in range(0, len(labels), kpts_per_split)] else: kpt_splits = [kpoints] label_splits = [labels] if cart_coords: coord_type = 'cartesian' style = Kpoints.supported_modes.Cartesian else: coord_type = 'reciprocal' style = Kpoints.supported_modes.Reciprocal kpt_files = [] for kpt_split, label_split in zip(kpt_splits, label_splits): if ibzkpt: # hybrid calculation so set k-point weights to 0 kpt_weights = ibzkpt.kpts_weights + [0] * len(kpt_split) kpt_split = ibzkpt.kpts + kpt_split label_split = [''] *
python
{ "resource": "" }
q19112
styled_plot
train
def styled_plot(*style_sheets): """Return a decorator that will apply matplotlib style sheets to a plot. ``style_sheets`` is a base set of styles, which will be ignored if ``no_base_style`` is set in the decorated function arguments. The style will further be overwritten by any styles in the ``style`` optional argument of the decorated function. Args: style_sheets (:obj:`list`, :obj:`str`, or :obj:`dict`): Any matplotlib supported definition of a style sheet. Can be a list of style of style sheets. """ def decorator(get_plot): def wrapper(*args, fonts=None, style=None, no_base_style=False, **kwargs): if no_base_style: list_style = [] else: list_style = list(style_sheets) if style is not
python
{ "resource": "" }
q19113
power_tick
train
def power_tick(val, pos, times_sign=r'\times'): """Custom power ticker function. """ if val == 0: return r'$\mathregular{0}$' elif val < 0: exponent = int(np.log10(-val))
python
{ "resource": "" }
q19114
rgbline
train
def rgbline(x, y, red, green, blue, alpha=1, linestyles="solid", linewidth=2.5): """Get a RGB coloured line for plotting. Args: x (list): x-axis data. y (list): y-axis data (can be multidimensional array). red (list): Red data (must have same shape as ``y``). green (list): Green data (must have same shape as ``y``). blue (list): blue data (must have same shape as ``y``). alpha (:obj:`list` or :obj:`int`, optional): Alpha (transparency) data (must have same shape as ``y`` or be an :obj:`int`). linestyles (:obj:`str`, optional): Linestyle for plot. Options are ``"solid"`` or ``"dotted"``. """ y = np.array(y) if len(y.shape) == 1: y = np.array([y]) red = np.array([red]) green = np.array([green]) blue = np.array([blue]) alpha = np.array([alpha]) elif isinstance(alpha, int): alpha = [alpha] * len(y) seg = [] colours = [] for yy, rr, gg, bb, aa in zip(y, red, green, blue, alpha):
python
{ "resource": "" }
q19115
broaden_eps
train
def broaden_eps(dielectric, sigma): """Apply gaussian broadening to the dielectric response. Args: dielectric_data (tuple): The high-frequency dielectric data, following the same format as :attr:`pymatgen.io.vasp.outputs.Vasprun.dielectric`. This is a :obj:`tuple` containing the energy, the real part of the dielectric tensor, and the imaginary part of the tensor, as a :obj:`list` of :obj:`floats`. E.g.:: ( [energies], [[real_xx, real_yy, real_zz, real_xy, real_yz, real_xz]], [[imag_xx, imag_yy, imag_zz, imag_xy, imag_yz, imag_xz]] ) sigma (float): Standard deviation for gaussian broadening. Returns: :obj:`tuple` of :obj:`list` of :obj:`list` of :obj:`float`: The broadened dielectric response. Returned as a tuple containing the energy, the real part of the dielectric tensor, and the imaginary part of the tensor. E.g.:: ( [energies],
python
{ "resource": "" }
q19116
write_files
train
def write_files(abs_data, basename='absorption', prefix=None, directory=None): """Write the absorption or loss spectra to a file. Note that this function expects to receive an iterable series of spectra. Args: abs_data (tuple): Series (either :obj:`list` or :obj:`tuple`) of optical absorption or loss spectra. Each spectrum should be formatted as a :obj:`tuple` of :obj:`list` of :obj:`float`. If the data has been averaged, each spectrum should be:: ([energies], [alpha]) Else, if the data has not been averaged, each spectrum should be::
python
{ "resource": "" }
q19117
load_phonopy
train
def load_phonopy(filename, structure, dim, symprec=0.01, primitive_matrix=None, factor=VaspToTHz, symmetrise=True, born=None, write_fc=False): """Load phonopy output and return an ``phonopy.Phonopy`` object. Args: filename (str): Path to phonopy output. Can be any of ``FORCE_SETS``, ``FORCE_CONSTANTS``, or ``force_constants.hdf5``. structure (:obj:`~pymatgen.core.structure.Structure`): The unitcell structure. dim (list): The supercell size, as a :obj:`list` of :obj:`float`. symprec (:obj:`float`, optional): The tolerance for determining the crystal symmetry. primitive_matrix (:obj:`list`, optional): The transformation matrix from the conventional to primitive cell. Only required when the conventional cell was used as the starting structure. Should be provided as a 3x3 :obj:`list` of :obj:`float`. factor (:obj:`float`, optional): The conversion factor for phonon frequency. Defaults to :obj:`phonopy.units.VaspToTHz`. symmetrise (:obj:`bool`, optional): Symmetrise the force constants. Defaults to ``True``. born (:obj:`str`, optional): Path to file containing Born effective charges. Should be in the same format as the file produced by the ``phonopy-vasp-born`` script provided by phonopy. write_fc (:obj:`bool` or :obj:`str`, optional): Write the force constants to disk. If ``True``, a ``FORCE_CONSTANTS`` file will be written. Alternatively, if set to ``"hdf5"``, a ``force_constants.hdf5`` file will be written. Defaults to ``False`` (force constants not written). """ unitcell = get_phonopy_structure(structure) num_atom = unitcell.get_number_of_atoms() num_satom = determinant(dim) * num_atom phonon = Phonopy(unitcell, dim, primitive_matrix=primitive_matrix, factor=factor, symprec=symprec) if 'FORCE_CONSTANTS' == filename or '.hdf5' in filename: # if force constants exist, use these to avoid recalculating them if '.hdf5' in filename: fc = file_IO.read_force_constants_hdf5(filename) elif 'FORCE_CONSTANTS' == filename: fc = file_IO.parse_FORCE_CONSTANTS(filename=filename) if fc.shape[0] != num_satom: msg = ("\nNumber of atoms in supercell is not consistent with the " "matrix shape of\nforce constants read from {}.\nPlease" "carefully check --dim.") logging.error(msg.format(filename))
python
{ "resource": "" }
q19118
load_dos
train
def load_dos(vasprun, elements=None, lm_orbitals=None, atoms=None, gaussian=None, total_only=False, log=False, adjust_fermi=True): """Load a vasprun and extract the total and projected density of states. Args: vasprun (str): Path to a vasprun.xml or vasprun.xml.gz file or a :obj:`pymatgen.io.vasp.outputs.Vasprun` object. elements (:obj:`dict`, optional): The elements and orbitals to extract from the projected density of states. Should be provided as a :obj:`dict` with the keys as the element names and corresponding values as a :obj:`tuple` of orbitals. For example, the following would extract the Bi s, px, py and d orbitals:: {'Bi': ('s', 'px', 'py', 'd')} If an element is included with an empty :obj:`tuple`, all orbitals for that species will be extracted. If ``elements`` is not set or set to ``None``, all elements for all species will be extracted. lm_orbitals (:obj:`dict`, optional): The orbitals to decompose into their lm contributions (e.g. p -> px, py, pz). Should be provided as a :obj:`dict`, with the elements names as keys and a :obj:`tuple` of orbitals as the corresponding values. For example, the following would be used to decompose the oxygen p and d orbitals:: {'O': ('p', 'd')} atoms (:obj:`dict`, optional): Which atomic sites to use when calculating the projected density of states. Should be provided as a :obj:`dict`, with the element names as keys and a :obj:`tuple` of :obj:`int` specifying the atomic indices as the corresponding values. The elemental projected density of states will be summed only over the atom indices specified. If an element is included with an empty :obj:`tuple`, then all sites for that element will be included. The indices are 0 based for each element specified in the POSCAR. For example, the following will calculate the density of states for the first 4 Sn atoms and all O atoms in the structure:: {'Sn': (1, 2, 3, 4), 'O': (, )} If ``atoms`` is not set or set to ``None`` then all atomic sites for all elements will be considered. gaussian (:obj:`float`, optional): Broaden the density of states using convolution with a gaussian function. This parameter controls the sigma or standard deviation of the gaussian distribution. total_only (:obj:`bool`, optional): Only extract the total density of states. Defaults to ``False``. log (:obj:`bool`): Print logging messages. Defaults to ``False``. adjust_fermi (:obj:`bool`, optional): Shift the Fermi level to sit at the valence band maximum (does not affect metals). Returns:
python
{ "resource": "" }
q19119
get_pdos
train
def get_pdos(dos, lm_orbitals=None, atoms=None, elements=None): """Extract the projected density of states from a CompleteDos object. Args: dos (:obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The density of states. elements (:obj:`dict`, optional): The elements and orbitals to extract from the projected density of states. Should be provided as a :obj:`dict` with the keys as the element names and corresponding values as a :obj:`tuple` of orbitals. For example, the following would extract the Bi s, px, py and d orbitals:: {'Bi': ('s', 'px', 'py', 'd')} If an element is included with an empty :obj:`tuple`, all orbitals for that species will be extracted. If ``elements`` is not set or set to ``None``, all elements for all species will be extracted. lm_orbitals (:obj:`dict`, optional): The orbitals to decompose into their lm contributions (e.g. p -> px, py, pz). Should be provided as a :obj:`dict`, with the elements names as keys and a :obj:`tuple` of orbitals as the corresponding values. For example, the following would be used to decompose the oxygen p and d orbitals:: {'O': ('p', 'd')} atoms (:obj:`dict`, optional): Which atomic sites to use when calculating the projected density of states. Should be provided as a :obj:`dict`, with the element names as keys and a :obj:`tuple` of :obj:`int` specifying the atomic indices as the corresponding values. The elemental projected density of states will be summed only over the atom indices specified. If an element is included with an empty :obj:`tuple`, then all sites for that element will be included. The indices are 0 based for each element specified in the POSCAR. For example, the following will calculate the density of states for the first 4 Sn atoms and all O atoms in the structure:: {'Sn': (1, 2, 3, 4), 'O': (, )} If ``atoms`` is not set or set to ``None`` then all atomic sites for all elements will be considered. Returns: dict: The projected density of
python
{ "resource": "" }
q19120
get_element_pdos
train
def get_element_pdos(dos, element, sites, lm_orbitals=None, orbitals=None): """Get the projected density of states for an element. Args: dos (:obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The density of states. element (str): Element symbol. E.g. 'Zn'. sites (tuple): The atomic indices over which to sum the density of states, as a :obj:`tuple`. Indices are zero based for each element. For example, ``(0, 1, 2)`` will sum the density of states for the 1st, 2nd and 3rd sites of the element specified. lm_orbitals (:obj:`tuple`, optional): The orbitals to decompose into their lm contributions (e.g. p -> px, py, pz). Should be provided as a :obj:`tuple` of :obj:`str`. For example, ``('p')``, will extract the projected density of states for the px, py, and pz orbitals. Defaults to ``None``. orbitals (:obj:`tuple`, optional): The orbitals to extract from the projected density of states. Should be provided as
python
{ "resource": "" }
q19121
write_files
train
def write_files(dos, pdos, prefix=None, directory=None, zero_to_efermi=True): """Write the density of states data to disk. Args: dos (:obj:`~pymatgen.electronic_structure.dos.Dos` or \ :obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The total density of states. pdos (dict): The projected density of states. Formatted as a :obj:`dict` of :obj:`dict` mapping the elements and their orbitals to :obj:`~pymatgen.electronic_structure.dos.Dos` objects. For example:: { 'Bi': {'s': Dos, 'p': Dos}, 'S': {'s': Dos} } prefix (:obj:`str`, optional): A prefix for file names. directory (:obj:`str`, optional): The directory in which to save files. zero_to_efermi (:obj:`bool`, optional): Normalise the energy such that the Fermi level is set as 0 eV. """ # defining these cryptic lists makes formatting the data much easier later if len(dos.densities) == 1: sdata = [[Spin.up, 1, '']] else: sdata = [[Spin.up, 1, '(up)'], [Spin.down, -1, '(down)']] header = ['energy'] eners = dos.energies - dos.efermi if zero_to_efermi else dos.energies tdos_data = [eners] for spin, sign, label in sdata: header.append('dos{}'.format(label)) tdos_data.append(dos.densities[spin] * sign) tdos_data = np.stack(tdos_data, axis=1) filename = "{}_total_dos.dat".format(prefix) if prefix else 'total_dos.dat' if
python
{ "resource": "" }
q19122
sort_orbitals
train
def sort_orbitals(element_pdos): """Sort the orbitals of an element's projected density of states. Sorts the orbitals based on a standard format. E.g. s < p < d. Will also sort lm decomposed orbitals. This is useful for plotting/saving. Args: element_pdos (dict): An element's pdos. Should be formatted as a :obj:`dict` of ``{orbital: dos}``. Where dos is a :obj:`~pymatgen.electronic_structure.dos.Dos` object. For example:: {'s': dos, 'px': dos} Returns: list: The sorted orbitals. """ sorted_orbitals = ['s', 'p', 'py',
python
{ "resource": "" }
q19123
bandstats
train
def bandstats(filenames=None, num_sample_points=3, temperature=None, degeneracy_tol=1e-4, parabolic=True): """Calculate the effective masses of the bands of a semiconductor. Args: filenames (:obj:`str` or :obj:`list`, optional): Path to vasprun.xml or vasprun.xml.gz file. If no filenames are provided, the code will search for vasprun.xml or vasprun.xml.gz files in folders named 'split-0*'. Failing that, the code will look for a vasprun in the current directory. If a :obj:`list` of vasprun files is provided, these will be combined into a single band structure. num_sample_points (:obj:`int`, optional): Number of k-points to sample when fitting the effective masses. temperature (:obj:`int`, optional): Find band edges within kB * T of the valence band maximum and conduction band minimum. Not currently implemented. degeneracy_tol (:obj:`float`, optional): Tolerance for determining the degeneracy of the valence band maximum and conduction band minimum. parabolic (:obj:`bool`, optional): Use a parabolic fit of the band edges. If ``False`` then nonparabolic fitting will be attempted. Defaults to ``True``. Returns: dict: The hole and electron effective masses. Formatted as a :obj:`dict` with keys: ``'hole_data'`` and ``'electron_data'``. The data is a :obj:`list` of :obj:`dict` with the keys: 'effective_mass' (:obj:`float`) The effective mass in units of electron rest mass, :math:`m_0`. 'energies' (:obj:`numpy.ndarray`) Band eigenvalues in eV. 'distances' (:obj:`numpy.ndarray`) Distances of the k-points in reciprocal space. 'band_id' (:obj:`int`) The index of the band, 'spin' (:obj:`~pymatgen.electronic_structure.core.Spin`) The spin channel 'start_kpoint' (:obj:`int`) The index of the k-point at which the band extrema occurs 'end_kpoint' (:obj:`int`) """ if not filenames: filenames = find_vasprun_files() elif isinstance(filenames, str): filenames = [filenames] bandstructures = [] for vr_file in filenames: vr = BSVasprun(vr_file, parse_projected_eigen=False) bs = vr.get_band_structure(line_mode=True) bandstructures.append(bs) bs = get_reconstructed_band_structure(bandstructures) if bs.is_metal(): logging.error('ERROR: System is metallic!') sys.exit() _log_band_gap_information(bs) vbm_data = bs.get_vbm() cbm_data = bs.get_cbm() logging.info('\nValence band maximum:') _log_band_edge_information(bs, vbm_data) logging.info('\nConduction band minimum:') _log_band_edge_information(bs, cbm_data) if parabolic: logging.info('\nUsing parabolic fitting of the band edges') else: logging.info('\nUsing nonparabolic fitting of the band edges') if temperature: logging.error('ERROR: This feature is not yet supported!') else: # Work out where the hole and electron band edges are.
python
{ "resource": "" }
q19124
_log_band_gap_information
train
def _log_band_gap_information(bs): """Log data about the direct and indirect band gaps. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): """ bg_data = bs.get_band_gap() if not bg_data['direct']: logging.info('Indirect band gap: {:.3f} eV'.format(bg_data['energy'])) direct_data = bs.get_direct_band_gap_dict() if bs.is_spin_polarized: direct_bg = min((spin_data['value'] for spin_data in direct_data.values())) logging.info('Direct band gap: {:.3f} eV'.format(direct_bg)) for spin, spin_data in direct_data.items(): direct_kindex = spin_data['kpoint_index'] direct_kpoint = bs.kpoints[direct_kindex].frac_coords direct_kpoint = kpt_str.format(k=direct_kpoint) eq_kpoints = bs.get_equivalent_kpoints(direct_kindex) k_indices = ', '.join(map(str, eq_kpoints)) # add 1 to band indices to be consistent with VASP band numbers. b_indices = ', '.join([str(i+1) for i in spin_data['band_indices']]) logging.info(' {}:'.format(spin.name.capitalize())) logging.info(' k-point: {}'.format(direct_kpoint)) logging.info(' k-point indices: {}'.format(k_indices)) logging.info('
python
{ "resource": "" }
q19125
_log_band_edge_information
train
def _log_band_edge_information(bs, edge_data): """Log data about the valence band maximum or conduction band minimum. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): The band structure. edge_data (dict): The :obj:`dict` from ``bs.get_vbm()`` or ``bs.get_cbm()`` """ if bs.is_spin_polarized: spins = edge_data['band_index'].keys() b_indices = [', '.join([str(i+1) for i in edge_data['band_index'][spin]]) + '({})'.format(spin.name.capitalize()) for spin in spins] b_indices = ', '.join(b_indices) else: b_indices = ', '.join([str(i+1) for i in edge_data['band_index'][Spin.up]])
python
{ "resource": "" }
q19126
_log_effective_mass_data
train
def _log_effective_mass_data(data, is_spin_polarized, mass_type='m_e'): """Log data about the effective masses and their directions. Args: data (dict): The effective mass data. Formatted as a :obj:`dict` with the keys: 'effective_mass' (:obj:`float`) The effective mass in units of electron rest mass, :math:`m_0`. 'energies' (:obj:`numpy.ndarray`) Band eigenvalues in eV. 'band_id' (:obj:`int`) The index of the band, 'spin' (:obj:`~pymatgen.electronic_structure.core.Spin`) The spin channel 'start_kpoint' (:obj:`int`)
python
{ "resource": "" }
q19127
SPhononBSPlotter._makeplot
train
def _makeplot(self, ax, fig, data, ymin=None, ymax=None, height=6, width=6, dos=None, color=None): """Utility method to tidy phonon band structure diagrams. """ # Define colours if color is None: color = 'C0' # Default to first colour in matplotlib series # set x and y limits tymax = ymax if (ymax is not None) else max(flatten(data['frequency'])) tymin = ymin if (ymin is not None) else min(flatten(data['frequency'])) pad = (tymax - tymin) * 0.05 if ymin is None: ymin = 0 if tymin >= self.imag_tol else tymin - pad ymax = ymax if ymax else tymax + pad ax.set_ylim(ymin, ymax) ax.set_xlim(0, data['distances'][-1][-1]) if ymin < 0: dashline = True ax.axhline(0, color=rcParams['grid.color'], linestyle='--', dashes=dashes, zorder=0, linewidth=rcParams['ytick.major.width'])
python
{ "resource": "" }
q19128
find_vasprun_files
train
def find_vasprun_files(): """Search for vasprun files from the current directory. The precedence order for file locations is: 1. First search for folders named: 'split-0*' 2. Else, look in the current directory. The split folder names should always be zero based, therefore easily sortable. """ folders = glob.glob('split-*') folders = sorted(folders) if folders else ['.'] filenames = [] for fol in folders: vr_file
python
{ "resource": "" }
q19129
save_data_files
train
def save_data_files(vr, bs, prefix=None, directory=None): """Write the band structure data files to disk. Args: vs (`Vasprun`): Pymatgen `Vasprun` object. bs (`BandStructureSymmLine`): Calculated band structure. prefix (`str`, optional): Prefix for data file. directory (`str`, optional): Directory in which to save the data. Returns: The filename of the written data file. """ filename = '{}_band.dat'.format(prefix) if prefix else 'band.dat' directory = directory if directory else '.' filename =
python
{ "resource": "" }
q19130
save_data_files
train
def save_data_files(bs, prefix=None, directory=None): """Write the phonon band structure data files to disk. Args: bs (:obj:`~pymatgen.phonon.bandstructure.PhononBandStructureSymmLine`): The phonon band structure. prefix (:obj:`str`, optional): Prefix for data file. directory (:obj:`str`, optional): Directory in which to save the data.
python
{ "resource": "" }
q19131
kgen
train
def kgen(filename='POSCAR', directory=None, make_folders=False, symprec=0.01, kpts_per_split=None, ibzkpt=None, spg=None, density=60, mode='bradcrack', cart_coords=False, kpt_list=None, labels=None): """Generate KPOINTS files for VASP band structure calculations. This script provides a wrapper around several frameworks used to generate k-points along a high-symmetry path. The paths found in Bradley and Cracknell, SeeK-path, and pymatgen are all supported. It is important to note that the standard primitive cell symmetry is different between SeeK-path and pymatgen. If the correct the structure is not used, the high-symmetry points (and band path) may be invalid. Args: filename (:obj:`str`, optional): Path to VASP structure file. Default is ``POSCAR``. directory (:obj:`str`, optional): The output file directory. make_folders (:obj:`bool`, optional): Generate folders and copy in required files (INCAR, POTCAR, POSCAR, and possibly CHGCAR) from the current directory. symprec (:obj:`float`, optional): The precision used for determining the cell symmetry. kpts_per_split (:obj:`int`, optional): If set, the k-points are split into separate k-point files (or folders) each containing the number of k-points specified. This is useful for hybrid band structure calculations where it is often intractable to calculate all k-points in the same calculation. ibzkpt (:obj:`str`, optional): Path to IBZKPT file. If set, the generated k-points will be appended to the k-points in this file and given a weight of 0. This is necessary for hybrid band structure calculations. spg (:obj:`str` or :obj:`int`, optional): The space group international number or symbol to override the symmetry determined by spglib. This is not recommended and only provided for testing purposes. This option will only take effect when ``mode = 'bradcrack'``. line_density (:obj:`int`, optional): Density of k-points along the path. mode (:obj:`str`, optional): Method used for
python
{ "resource": "" }
q19132
dosplot
train
def dosplot(filename=None, prefix=None, directory=None, elements=None, lm_orbitals=None, atoms=None, subplot=False, shift=True, total_only=False, plot_total=True, legend_on=True, legend_frame_on=False, legend_cutoff=3., gaussian=None, height=6., width=8., xmin=-6., xmax=6., num_columns=2, colours=None, yscale=1, xlabel='Energy (eV)', ylabel='Arb. units', style=None, no_base_style=False, image_format='pdf', dpi=400, plt=None, fonts=None): """A script to plot the density of states from a vasprun.xml file. Args: filename (:obj:`str`, optional): Path to a vasprun.xml file (can be gzipped). prefix (:obj:`str`, optional): Prefix for file names. directory (:obj:`str`, optional): The directory in which to save files. elements (:obj:`dict`, optional): The elements and orbitals to extract from the projected density of states. Should be provided as a :obj:`dict` with the keys as the element names and corresponding values as a :obj:`tuple` of orbitals. For example, the following would extract the Bi s, px, py and d orbitals:: {'Bi': ('s', 'px', 'py', 'd')} If an element is included with an empty :obj:`tuple`, all orbitals for that species will be extracted. If ``elements`` is not set or set to ``None``, all elements for all species will be extracted. lm_orbitals (:obj:`dict`, optional): The orbitals to decompose into their lm contributions (e.g. p -> px, py, pz). Should be provided as a :obj:`dict`, with the elements names as keys and a :obj:`tuple` of orbitals as the corresponding values. For example, the following would be used to decompose the oxygen p and d orbitals:: {'O': ('p', 'd')} atoms (:obj:`dict`, optional): Which atomic sites to use when calculating the projected density of states. Should be provided as a :obj:`dict`, with the element names as keys and a :obj:`tuple` of :obj:`int` specifying the atomic indices as the corresponding values. The elemental projected density of states will be summed only over the atom indices specified. If an element is included with an empty :obj:`tuple`, then all sites for that element will be included. The indices are 0 based for each element specified in the POSCAR. For example, the following will calculate the density of states for the first 4 Sn atoms and all O atoms in the structure:: {'Sn': (1, 2, 3, 4), 'O': (, )} If ``atoms`` is not set or set to ``None`` then all atomic sites for all elements will be considered. subplot (:obj:`bool`, optional): Plot the density of states for each element on separate subplots. Defaults to ``False``. shift (:obj:`bool`, optional): Shift the energies such that the valence band maximum (or Fermi level for metals) is at 0 eV. Defaults to ``True``. total_only (:obj:`bool`, optional): Only extract the total density of states. Defaults to ``False``. plot_total (:obj:`bool`, optional): Plot the total density of states. Defaults to ``True``. legend_on (:obj:`bool`, optional): Plot the graph legend. Defaults to ``True``. legend_frame_on (:obj:`bool`, optional): Plot a frame around the graph legend. Defaults to ``False``. legend_cutoff (:obj:`float`, optional): The cut-off (in % of the maximum density of states within the plotting range) for an elemental orbital to be labelled in the legend. This prevents the legend from containing labels for orbitals that have very little contribution in the plotting range. gaussian (:obj:`float`, optional): Broaden the density of states using convolution with a gaussian function. This parameter controls the sigma or standard deviation of the gaussian distribution. height (:obj:`float`, optional): The height of the plot. width (:obj:`float`, optional): The width of the plot. xmin (:obj:`float`, optional): The minimum energy on the x-axis. xmax (:obj:`float`, optional): The maximum energy on the x-axis. num_columns (:obj:`int`, optional): The number of columns in the legend. colours (:obj:`dict`, optional): Use custom colours for specific element and orbital combinations. Specified as a :obj:`dict` of :obj:`dict` of the colours. For example:: { 'Sn': {'s': 'r', 'p': 'b'}, 'O': {'s': '#000000'} } The colour can be a hex code, series of rgb value,
python
{ "resource": "" }
q19133
_atoms
train
def _atoms(atoms_string): """Parse the atom string. Args: atoms_string (str): The atoms to plot, in the form ``"C.1.2.3,"``. Returns: dict: The atomic indices over which to sum the DOS. Formatted as:: {Element: [atom_indices]}. Indices are zero indexed for each atomic species. If an element symbol is included with an empty list, then
python
{ "resource": "" }
q19134
f
train
def f(s): """ Basic support for 3.6's f-strings, in 3.5! Formats "s" using appropriate globals and locals dictionaries. This f-string: f"hello a is {a}" simply becomes f("hello a is {a}") In other words, just throw parentheses around the string, and you're done! Implemented internally using str.format_map(). This means it doesn't support expressions: f("two minus three is {2-3}")
python
{ "resource": "" }
q19135
which
train
def which(cmd, path="PATH"): """Find cmd on PATH.""" if os.path.exists(cmd): return cmd if cmd[0] == '/': return None for segment in os.getenv(path).split(":"):
python
{ "resource": "" }
q19136
help
train
def help(subcommand=None): """ Print help for subcommands. Prints the help text for the specified subcommand. If subcommand is not specified, prints one-line summaries for every command. """ if not subcommand: print("blurb version", __version__) print() print("Management tool for CPython Misc/NEWS and Misc/NEWS.d entries.") print() print("Usage:") print(" blurb [subcommand] [options...]") print() # print list of subcommands summaries = [] longest_name_len = -1 for name, fn in subcommands.items(): if name.startswith('-'): continue longest_name_len = max(longest_name_len, len(name)) if not fn.__doc__: error("help is broken, no docstring for " + fn.__name__) fields = fn.__doc__.lstrip().split("\n") if not fields: first_line = "(no help available)" else: first_line = fields[0] summaries.append((name, first_line)) summaries.sort() print("Available subcommands:") print() for name, summary in summaries: print(" ", name.ljust(longest_name_len), " ", summary) print() print("If
python
{ "resource": "" }
q19137
release
train
def release(version): """ Move all new blurbs to a single blurb file for the release. This is used by the release manager when cutting a new release. """ if version == ".": # harvest version number from dirname of repo # I remind you, we're in the Misc subdir right now version = os.path.basename(root) existing_filenames = glob_blurbs(version) if existing_filenames: error("Sorry, can't handle appending 'next' files to an existing version (yet).") output = f("Misc/NEWS.d/{version}.rst") filenames = glob_blurbs("next") blurbs = Blurbs() date = current_date() if not filenames: print(f("No blurbs found. Setting {version} as having no changes.")) body = f("There were no new changes in version {version}.\n") metadata = {"no changes": "True", "bpo": "0", "section": "Library", "date": date, "nonce": nonceify(body)} blurbs.append((metadata, body)) else: no_changes = None count = len(filenames) print(f('Merging {count} blurbs to "{output}".')) for filename in filenames: if not filename.endswith(".rst"): continue
python
{ "resource": "" }
q19138
Blurbs.load
train
def load(self, filename, *, metadata=None): """ Read a blurb file. Broadly equivalent to blurb.parse(open(filename).read()). """ with
python
{ "resource": "" }
q19139
Blurbs._parse_next_filename
train
def _parse_next_filename(filename): """ Parses a "next" filename into its equivalent blurb metadata. Returns a dict. """ components = filename.split(os.sep) section, filename = components[-2:] section = unsanitize_section(section) assert section in sections, f("Unknown section {section}") fields = [x.strip() for x in filename.split(".")] assert len(fields) >= 4, f("Can't parse 'next' filename! filename {filename!r} fields {fields}") assert fields[-1] == "rst" metadata = {"date": fields[0], "nonce": fields[-2], "section": section} for field in fields[1:-2]:
python
{ "resource": "" }
q19140
Blurbs.save_split_next
train
def save_split_next(self): """ Save out blurbs created from "blurb split". They don't have dates, so we have to get creative. """ filenames = [] # the "date" MUST have a leading zero. # this ensures these files sort after all # newly created blurbs. width = int(math.ceil(math.log(len(self), 10))) + 1 i = 1 blurb = Blurbs() while self: metadata, body = self.pop() metadata['date'] = str(i).rjust(width, '0')
python
{ "resource": "" }
q19141
cherry_pick_cli
train
def cherry_pick_cli( ctx, dry_run, pr_remote, abort, status, push, config_path, commit_sha1, branches ): """cherry-pick COMMIT_SHA1 into target BRANCHES.""" click.echo("\U0001F40D \U0001F352 \u26CF") chosen_config_path, config = load_config(config_path) try: cherry_picker = CherryPicker( pr_remote, commit_sha1, branches, dry_run=dry_run, push=push, config=config, chosen_config_path=chosen_config_path, ) except InvalidRepoException: click.echo(f"You're not inside a {config['repo']} repo right now! \U0001F645") sys.exit(-1) except ValueError as exc:
python
{ "resource": "" }
q19142
get_base_branch
train
def get_base_branch(cherry_pick_branch): """ return '2.7' from 'backport-sha-2.7' raises ValueError if the specified branch name is not of a form that cherry_picker would have created """ prefix, sha, base_branch = cherry_pick_branch.split("-", 2) if prefix != "backport": raise ValueError( 'branch name is not prefixed with "backport-". Is
python
{ "resource": "" }
q19143
validate_sha
train
def validate_sha(sha): """ Validate that a hexdigest sha is a valid commit in the repo raises ValueError if the sha does not reference a commit within the repo """ cmd = ["git", "log", "-r", sha] try:
python
{ "resource": "" }
q19144
version_from_branch
train
def version_from_branch(branch): """ return version information from a git branch name """ try: return tuple( map( int, re.match(r"^.*(?P<version>\d+(\.\d+)+).*$", branch) .groupdict()["version"] .split("."),
python
{ "resource": "" }
q19145
get_current_branch
train
def get_current_branch(): """ Return the current branch """ cmd = ["git", "rev-parse",
python
{ "resource": "" }
q19146
normalize_commit_message
train
def normalize_commit_message(commit_message): """ Return a tuple of title and body from the commit message """ split_commit_message = commit_message.split("\n")
python
{ "resource": "" }
q19147
is_git_repo
train
def is_git_repo(): """Check whether the current folder is a Git repo.""" cmd = "git", "rev-parse", "--git-dir"
python
{ "resource": "" }
q19148
find_config
train
def find_config(revision): """Locate and return the default config for current revison.""" if not is_git_repo(): return None cfg_path = f"{revision}:.cherry_picker.toml" cmd =
python
{ "resource": "" }
q19149
load_config
train
def load_config(path=None): """Choose and return the config path and it's contents as dict.""" # NOTE: Initially I wanted to inherit Path to encapsulate Git access # there but there's no easy way to subclass pathlib.Path :( head_sha = get_sha1_from("HEAD") revision = head_sha saved_config_path = load_val_from_git_cfg("config_path") if not path and saved_config_path is not None: path = saved_config_path if path is None: path = find_config(revision=revision) else: if ":" not in path: path = f"{head_sha}:{path}"
python
{ "resource": "" }
q19150
save_cfg_vals_to_git_cfg
train
def save_cfg_vals_to_git_cfg(**cfg_map): """Save a set of options into Git config.""" for cfg_key_suffix, cfg_val in cfg_map.items(): cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}'
python
{ "resource": "" }
q19151
wipe_cfg_vals_from_git_cfg
train
def wipe_cfg_vals_from_git_cfg(*cfg_opts): """Remove a set of options from Git config.""" for cfg_key_suffix in cfg_opts: cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}'
python
{ "resource": "" }
q19152
load_val_from_git_cfg
train
def load_val_from_git_cfg(cfg_key_suffix): """Retrieve one option from Git config.""" cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}' cmd = "git", "config", "--local",
python
{ "resource": "" }
q19153
from_git_rev_read
train
def from_git_rev_read(path): """Retrieve given file path contents of certain Git revision.""" if ":" not in path: raise ValueError("Path identifier must
python
{ "resource": "" }
q19154
CherryPicker.set_paused_state
train
def set_paused_state(self): """Save paused progress state into Git config.""" if self.chosen_config_path is
python
{ "resource": "" }
q19155
CherryPicker.upstream
train
def upstream(self): """Get the remote name to use for upstream branches Uses "upstream" if it exists, "origin" otherwise """
python
{ "resource": "" }
q19156
CherryPicker.checkout_default_branch
train
def checkout_default_branch(self): """ git checkout default branch """ set_state(WORKFLOW_STATES.CHECKING_OUT_DEFAULT_BRANCH)
python
{ "resource": "" }
q19157
CherryPicker.create_gh_pr
train
def create_gh_pr(self, base_branch, head_branch, *, commit_message, gh_auth): """ Create PR in GitHub """ request_headers = sansio.create_headers(self.username, oauth_token=gh_auth) title, body = normalize_commit_message(commit_message) if not self.prefix_commit: title = f"[{base_branch}] {title}" data = { "title": title, "body": body, "head": f"{self.username}:{head_branch}", "base": base_branch, "maintainer_can_modify": True,
python
{ "resource": "" }
q19158
CherryPicker.open_pr
train
def open_pr(self, url): """ open url in the web browser """ if self.dry_run:
python
{ "resource": "" }
q19159
CherryPicker.cleanup_branch
train
def cleanup_branch(self, branch): """Remove the temporary backport branch. Switch to the default branch before that. """ set_state(WORKFLOW_STATES.REMOVING_BACKPORT_BRANCH) self.checkout_default_branch() try: self.delete_branch(branch) except subprocess.CalledProcessError:
python
{ "resource": "" }
q19160
CherryPicker.get_state_and_verify
train
def get_state_and_verify(self): """Return the run progress state stored in the Git config. Raises ValueError if the retrieved state is not of a form that cherry_picker would have stored in the config. """ try: state = get_state() except KeyError as ke: class state: name = str(ke.args[0]) if state not in self.ALLOWED_STATES: raise ValueError(
python
{ "resource": "" }
q19161
openDatFile
train
def openDatFile(datpath): ''' Open a file-like object using a pkg relative path. Example: fd = openDatFile('foopkg.barpkg/wootwoot.bin') ''' pkgname, filename = datpath.split('/', 1)
python
{ "resource": "" }
q19162
scrape
train
def scrape(text, ptype=None): ''' Scrape types from a blob of text and return node tuples. Args: text (str): Text to scrape. ptype (str): Optional ptype to scrape. If present, only scrape rules which match the provided type. Returns: (str, str): Yield tuples of type, valu strings. '''
python
{ "resource": "" }
q19163
en
train
def en(item): ''' Use msgpack to serialize a compatible python object. Args: item (obj): The object to serialize Notes: String objects are encoded using utf8 encoding. In order to handle potentially malformed input, ``unicode_errors='surrogatepass'`` is set to allow encoding bad input strings. Returns: bytes: The serialized bytes in
python
{ "resource": "" }
q19164
un
train
def un(byts): ''' Use msgpack to de-serialize a python object. Args: byts (bytes): The bytes to de-serialize Notes: String objects are decoded using utf8 encoding. In order to handle potentially malformed input, ``unicode_errors='surrogatepass'`` is set to allow decoding bad input strings. Returns:
python
{ "resource": "" }
q19165
iterfd
train
def iterfd(fd): ''' Generator which unpacks a file object of msgpacked content. Args: fd: File object to consume data from. Notes: String objects are decoded using utf8 encoding. In
python
{ "resource": "" }
q19166
iterfile
train
def iterfile(path, since=-1): ''' Generator which yields msgpack objects from a file path. Args: path: File path to open and consume data from. Notes: String objects are decoded using utf8 encoding. In order to handle potentially malformed input, ``unicode_errors='surrogatepass'`` is set to allow decoding bad input strings. Yields:
python
{ "resource": "" }
q19167
dumpfile
train
def dumpfile(item, path): ''' Dump an object to a file by path. Args: item (object): The object to serialize. path (str): The file path to save.
python
{ "resource": "" }
q19168
Unpk.feed
train
def feed(self, byts): ''' Feed bytes to the unpacker and return completed objects. Args: byts (bytes): Bytes to unpack. Notes: It is intended that this function is called multiple times with bytes from some sort of a stream, as it will unpack and return objects as they are available. Returns: list: List of tuples containing the item size and the unpacked item. ''' self.unpk.feed(byts) retn =
python
{ "resource": "" }
q19169
SynModule._onCoreModuleLoad
train
def _onCoreModuleLoad(self, event): ''' Clear the cached model rows and rebuild them only if they have been loaded already. ''' if not self._modelRuntsByBuid: return # Discard previously cached data. It will be computed upon the next
python
{ "resource": "" }
q19170
Log.encodeMsg
train
def encodeMsg(self, mesg): '''Get byts for a message''' fmt = self.locs.get('log:fmt') if fmt == 'jsonl': s = json.dumps(mesg, sort_keys=True) + '\n' buf = s.encode() return buf
python
{ "resource": "" }
q19171
imeicsum
train
def imeicsum(text): ''' Calculate the imei check byte. ''' digs = [] for i in range(14): v = int(text[i]) if i % 2: v *= 2 [digs.append(int(x))
python
{ "resource": "" }
q19172
executor
train
async def executor(func, *args, **kwargs): ''' Execute a function in an executor thread. Args: todo ((func,args,kwargs)): A todo tuple. ''' def syncfunc():
python
{ "resource": "" }
q19173
varget
train
def varget(name, defval=None, task=None): ''' Access a task local variable by name Precondition: If task is None, this must be called from task context ''' taskdict = _taskdict(task) retn = taskdict.get(name, s_common.NoValu) if retn is not s_common.NoValu: return retn
python
{ "resource": "" }
q19174
getPhoneInfo
train
def getPhoneInfo(numb): ''' Walk the phone info tree to find the best-match info for the given number. Example: info = getPhoneInfo(17035551212) country = info.get('cc') ''' text = str(numb) info = {} node = phonetree # make decisions down the tree (but only keep info for #
python
{ "resource": "" }
q19175
Hive.dict
train
async def dict(self, full): ''' Open a HiveDict at the given full path. '''
python
{ "resource": "" }
q19176
Hive.add
train
async def add(self, full, valu): ''' Atomically increments a node's value. ''' node = await self.open(full) oldv = node.valu newv = oldv + valu node.valu = await
python
{ "resource": "" }
q19177
Hive.pop
train
async def pop(self, full): ''' Remove and return the value for the given node. '''
python
{ "resource": "" }
q19178
CryoTank.puts
train
async def puts(self, items, seqn=None): ''' Add the structured data from items to the CryoTank. Args: items (list): A list of objects to store in the CryoTank. seqn (iden, offs): An iden / offset pair to record. Returns: int: The ending offset of the items or seqn. ''' size = 0 for chunk in s_common.chunks(items, 1000): metrics = self._items.save(chunk) self._metrics.add(metrics)
python
{ "resource": "" }
q19179
CryoTank.metrics
train
async def metrics(self, offs, size=None): ''' Yield metrics rows starting at offset. Args: offs (int): The index offset. size (int): The maximum number of records to yield. Yields: ((int, dict)): An index offset, info tuple for metrics.
python
{ "resource": "" }
q19180
CryoTank.slice
train
async def slice(self, offs, size=None, iden=None): ''' Yield a number of items from the CryoTank starting at a given offset. Args: offs (int): The index of the desired datum (starts at 0) size (int): The max number
python
{ "resource": "" }
q19181
CryoTank.rows
train
async def rows(self, offs, size=None, iden=None): ''' Yield a number of raw items from the CryoTank starting at a given offset. Args: offs (int): The index of the desired datum (starts at 0) size (int): The max number
python
{ "resource": "" }
q19182
CryoTank.info
train
async def info(self): ''' Returns information about the CryoTank instance. Returns: dict: A dict containing items and metrics indexes. '''
python
{ "resource": "" }
q19183
CryoCell.init
train
async def init(self, name, conf=None): ''' Generate a new CryoTank with a given name or get an reference to an existing CryoTank. Args: name (str): Name of the CryoTank. Returns: CryoTank: A CryoTank instance. ''' tank = self.tanks.get(name) if tank is not None: return tank iden = s_common.guid() logger.info('Creating new tank: %s', name) path
python
{ "resource": "" }
q19184
hashitem
train
def hashitem(item): ''' Generate a uniq hash for the JSON compatible primitive data structure. ''' norm = normitem(item)
python
{ "resource": "" }
q19185
getVolInfo
train
def getVolInfo(*paths): ''' Retrieve volume usage info for the given path. ''' path = os.path.join(*paths) path = os.path.expanduser(path) st = os.statvfs(path) free = st.f_bavail * st.f_frsize
python
{ "resource": "" }
q19186
parse_cmd_string
train
def parse_cmd_string(text, off, trim=True): ''' Parse in a command line string which may be quoted. ''' if trim: _, off = nom(text, off, whites) if isquote(text, off):
python
{ "resource": "" }
q19187
parse_valu
train
def parse_valu(text, off=0): ''' Special syntax for the right side of equals in a macro ''' _, off = nom(text, off, whites) if nextchar(text, off, '('): return parse_list(text, off) if isquote(text, off): return parse_string(text, off) # since it's not quoted, we can assume we are bound by both # white space and storm syntax chars ( ) , = valu, off = meh(text, off, valmeh)
python
{ "resource": "" }
q19188
Parser.editunivset
train
def editunivset(self): ''' .foo = bar ''' self.ignore(whitespace) if not self.nextstr('.'): self._raiseSyntaxExpects('.') univ = self.univprop()
python
{ "resource": "" }
q19189
parse
train
def parse(text, base=None, chop=False): ''' Parse a time string into an epoch millis value. ''' #TODO: use base to facilitate relative time offsets text = text.strip().lower() text = (''.join([c for c in text if c.isdigit()])) if chop: text = text[:17] # TODO: support relative time offsets here... tlen = len(text) if tlen == 4: dt = datetime.datetime.strptime(text, '%Y') elif tlen == 6: dt = datetime.datetime.strptime(text, '%Y%m') elif tlen == 8: dt = datetime.datetime.strptime(text, '%Y%m%d') elif tlen == 10: dt = datetime.datetime.strptime(text, '%Y%m%d%H') elif tlen == 12: dt = datetime.datetime.strptime(text, '%Y%m%d%H%M')
python
{ "resource": "" }
q19190
repr
train
def repr(tick, pack=False): ''' Return a date string for an epoch-millis timestamp. Args: tick (int): The timestamp in milliseconds since the epoch. Returns: (str): A date time string ''' if tick == 0x7fffffffffffffff: return '?' dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(milliseconds=tick) millis = dt.microsecond / 1000 if
python
{ "resource": "" }
q19191
delta
train
def delta(text): ''' Parse a simple time delta string and return the delta. ''' text = text.strip().lower() _, offs = _noms(text, 0, ' \t\r\n') sign = '+' if text and text[0] in ('+', '-'): sign = text[0] offs += 1 _, offs = _noms(text, offs, ' \t\r\n') sizetext, offs = _noms(text, offs, '0123456789') _, offs = _noms(text, offs, ' \t\r\n') unittext = text[offs:]
python
{ "resource": "" }
q19192
TinFoilHat.enc
train
def enc(self, byts, asscd=None): ''' Encrypt the given bytes and return an envelope dict in msgpack form. Args: byts (bytes): The message to be encrypted. asscd (bytes): Extra data that needs to be authenticated (but not encrypted).
python
{ "resource": "" }
q19193
TinFoilHat.dec
train
def dec(self, byts): ''' Decode an envelope dict and decrypt the given bytes. Args: byts (bytes): Bytes to decrypt. Returns: bytes: Decrypted message. ''' envl = s_msgpack.un(byts) iv = envl.get('iv', b'') asscd = envl.get('asscd', b'') data = envl.get('data', b'')
python
{ "resource": "" }
q19194
CryptSeq.encrypt
train
def encrypt(self, mesg): ''' Wrap a message with a sequence number and encrypt it. Args: mesg: The mesg to encrypt. Returns: bytes: The encrypted message.
python
{ "resource": "" }
q19195
CryptSeq.decrypt
train
def decrypt(self, ciphertext): ''' Decrypt a message, validating its sequence number is as we expect. Args: ciphertext (bytes): The message to decrypt and verify. Returns: mesg: A mesg. Raises: s_exc.CryptoErr: If the message decryption fails or the sequence number was unexpected. ''' plaintext = self._rx_tinh.dec(ciphertext) if plaintext is None: logger.error('Message decryption failure') raise s_exc.CryptoErr(mesg='Message decryption failure')
python
{ "resource": "" }
q19196
parseSemver
train
def parseSemver(text): ''' Parse a Semantic Version string into is component parts. Args: text (str): A text string to parse into semver components. This string has whitespace and leading 'v' characters stripped off of it. Examples: Parse a string into it semvar parts:: parts = parseSemver('v1.2.3') Returns: dict: The dictionary will contain the keys 'major', 'minor' and 'patch' pointing to integer values. The dictionary may also contain keys for 'build' and 'pre' information if that data is parsed out of a semver string. None is returned if the string is not a valid Semver string.
python
{ "resource": "" }
q19197
unpackVersion
train
def unpackVersion(ver): ''' Unpack a system normalized integer representing a softare version into its component parts. Args: ver (int): System normalized integer value to unpack
python
{ "resource": "" }
q19198
fmtVersion
train
def fmtVersion(*vsnparts): ''' Join a string of parts together with a . separator. Args: *vsnparts: Returns: ''' if len(vsnparts) < 1: raise s_exc.BadTypeValu(valu=repr(vsnparts), name='fmtVersion',
python
{ "resource": "" }
q19199
SlabDict.set
train
def set(self, name, valu): ''' Set a name in the SlabDict. Args: name (str): The key name. valu (obj): A msgpack compatible value. Returns: None '''
python
{ "resource": "" }