code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
try: index = self.atoms.index(atom) except ValueError: raise CycleError("atom %s not in cycle"%(atom)) self.atoms = self.atoms[index:] + self.atoms[:index] self.bonds = self.bonds[index:] + self.bonds[:index]
def rotate(self, atom)
(atom)->start the cycle at position atom, assumes that atom is in the cycle
2.510857
2.234576
1.123639
#XXX FIX ME # this probably shouldn't be here for atom in self.atoms: atom.aromatic = 1 for bond in self.bonds: bond.aromatic = 1 bond.bondorder = 1.5 bond.bondtype = 4 bond.symbol = ":" bond.fi...
def set_aromatic(self)
set the cycle to be an aromatic ring
4.298194
4.273508
1.005777
global _DEBUG_ENABLED if not enabled: log('Disabling debug output...', logger_name=_LOGGER_NAME) _DEBUG_ENABLED = False else: _DEBUG_ENABLED = True log('Enabling debug output...', logger_name=_LOGGER_NAME)
def set_debug(enabled: bool)
Enable or disable debug logs for the entire package. Parameters ---------- enabled: bool Whether debug should be enabled or not.
3.465642
4.049279
0.855866
# Get logger logger = logging.getLogger(name) # Set logger level old_level = logger.level logger.setLevel(level) # Setup handler and add to logger handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s %(levelname)-5s [%(name)s]: %(message)s') h...
def _create_logger(name: str, level: int) -> Generator[logging.Logger, None, None]
Create a context-based logger. Parameters ---------- name: str Name of logger to use when logging. level: int Logging level, one of logging's levels (e.g. INFO, ERROR, etc.). Returns ------- logging.Logger Named logger that may be used for logging.
1.93566
2.160002
0.896138
global _DEBUG_ENABLED if _DEBUG_ENABLED: level = logging.INFO else: level = logging.CRITICAL + 1 with _create_logger(logger_name, level) as logger: log_fn = getattr(logger, category, None) if log_fn is None: raise ValueError('Invalid log category "{}"'....
def log(message: str, *args: str, category: str='info', logger_name: str='pgevents')
Log a message to the given logger. If debug has not been enabled, this method will not log a message. Parameters ---------- message: str Message, with or without formatters, to print. args: Any Arguments to use with the message. args must either be a series of arguments tha...
3.242901
3.631766
0.892927
results = {} lookup = {} fullSet = {} oatoms = {} # XXX FIX ME # copy atom.oatoms to atom._oatoms # atom._oatoms will be modified my the routine for atom in molecule.atoms: atom.rings = [] fullSet[atom.handle] = 1 lookup[atom.handle] = atom oatoms[atom.handle] = a...
def sssr(molecule)
molecule -> generate the molecule.cycles that contain the smallest set of smallest rings
4.056742
4.023173
1.008344
atoms = [] a_append = atoms.append bonds = [] b_append = bonds.append # for the atom and bond hashes # we ignore the first atom since we # would have deleted it from the hash anyway ahash = {} bhash = {} for atom in initialAtoms[1:]: ahash[atom.handle] = 1 ...
def toposort(initialAtoms, initialBonds)
initialAtoms, initialBonds -> atoms, bonds Given the list of atoms and bonds in a ring return the topologically sorted atoms and bonds. That is each atom is connected to the following atom and each bond is connected to the following bond in the following manner a1 - b1 - a2 - b2 - ...
4.46927
4.520135
0.988747
path = {} bpaths = {} for atomID in atomSet.keys(): # initially the paths are empty path[atomID] = None bpaths[atomID] = [] q = [] handle = startAtom.handle for atom in oatoms[handle]: q.append((atom, handle)) path[atom.handle] = {atom.handle:1, handle:1} bp...
def getRing(startAtom, atomSet, lookup, oatoms)
getRing(startAtom, atomSet, lookup, oatoms)->atoms, bonds starting at startAtom do a bfs traversal through the atoms in atomSet and return the smallest ring found returns (), () on failure note: atoms and bonds are not returned in traversal order
3.41679
3.301627
1.03488
bondedAtoms = map( None, ringSet[:-1], ringSet[1:] ) bondedAtoms += [ (ringSet[-1], ringSet[0]) ] # form a lookup for the ringSet list atomSet = {} for atomID in ringSet: atomSet[atomID] = 1 results = [] # for each bond in the ring, break it and find the smallest # rings star...
def checkEdges(ringSet, lookup, oatoms)
atoms, lookup -> ring atoms must be in the order of traversal around a ring! break an optimal non N2 node and return the largest ring found
3.483455
3.524415
0.988378
if not isinstance(n, str): raise ValueError('%r is not a string' % n) try: n = int(n) except: raise ValueError('%s is not an integer' % n) if n < 0: raise ValueError('%d is not non-negative' % n) else: return n
def NonNegativeInt(n)
If *n* is non-negative integer returns it, otherwise an error. >>> print("%d" % NonNegativeInt('8')) 8 >>> NonNegativeInt('8.1') Traceback (most recent call last): ... ValueError: 8.1 is not an integer >>> print("%d" % NonNegativeInt('0')) 0 >>> NonNegativeInt('-1') Traceb...
2.293303
2.360358
0.971591
try: n = int(n) except: raise ValueError("%s is not an integer" % n) if n <= 0: raise ValueError("%d is not > 0" % n) else: return n
def IntGreaterThanZero(n)
If *n* is an integer > 0, returns it, otherwise an error.
2.347627
2.297354
1.021883
try: n = int(n) except: raise ValueError("%s is not an integer" % n) if n <= 1: raise ValueError("%d is not > 1" % n) else: return n
def IntGreaterThanOne(n)
If *n* is an integer > 1, returns it, otherwise an error.
2.409045
2.256742
1.067488
try: x = float(x) except: raise ValueError("%r not float greater than or equal to zero" % x) if x >= 0: return x else: raise ValueError("%r not float greater than or equal to zero" % x)
def FloatGreaterThanEqualToZero(x)
If *x* is a float >= 0, returns it, otherwise raises and error. >>> print('%.1f' % FloatGreaterThanEqualToZero('1.5')) 1.5 >>> print('%.1f' % FloatGreaterThanEqualToZero('-1.1')) Traceback (most recent call last): ... ValueError: -1.1 not float greater than or equal to zero
2.654551
2.444485
1.085934
x = float(x) if 0 <= x <= 1: return x else: raise ValueError("{0} not a float between 0 and 1.".format(x))
def FloatBetweenZeroAndOne(x)
Returns *x* only if *0 <= x <= 1*, otherwise raises error.
2.767233
2.370769
1.167231
assert isinstance(priorstring, str) prior = priorstring.split(',') if len(prior) == 3 and prior[0] == 'invquadratic': [c1, c2] = [float(x) for x in prior[1 : ]] assert c1 > 0 and c2 > 0, "C1 and C2 must be > 1 for invquadratic prior" return ('invquadratic', c1, c2) else: ...
def diffPrefsPrior(priorstring)
Parses `priorstring` and returns `prior` tuple.
3.483532
3.486964
0.999016
if os.path.isfile(fname): return fname elif fname.lower() == 'none': return None else: raise ValueError("%s must specify a valid file name or 'None'" % fname)
def ExistingFileOrNone(fname)
Like `Existingfile`, but if `fname` is string "None" then return `None`.
3.045894
3.132421
0.972377
yngkpmatch = re.compile('^YNGKP_M[{0}]$'.format(''.join([m[1 : ] for m in yngkp_modelvariants]))) if yngkpmatch.search(model): return model elif len(model) > 6 and model[ : 6] == 'ExpCM_': fname = model[6 : ] if os.path.isfile(fname): return ('ExpCM', fname) ...
def ModelOption(model)
Returns *model* if a valid choice. Returns the string if it specifies a ``YNGKP_`` model variant. Returns *('ExpCM', prefsfile)* if it specifies an ``ExpCM_`` model.
6.907589
4.356742
1.585494
parser = ArgumentParserNoArgHelp(formatter_class=ArgumentDefaultsRawDescriptionFormatter, description='\n'.join([ "Prepare alignment of protein-coding DNA sequences.\n", "Steps:", " * Any sequences specified by '--purgeseqs' are removed.", " * Sequenc...
def PhyDMSPrepAlignmentParser()
Returns *argparse.ArgumentParser* for ``phydms_prepalignment``.
6.362614
6.290476
1.011468
parser = ArgumentParserNoArgHelp(description= "Make logo plot of preferences or differential preferences. " "Uses weblogo (http://weblogo.threeplusone.com/). " "{0} Version {1}. Full documentation at {2}".format( phydmslib.__acknowledgments__, phydmsl...
def PhyDMSLogoPlotParser()
Returns `argparse.ArgumentParser` for ``phydms_logoplot``.
4.949406
4.869929
1.01632
parser = ArgumentParserNoArgHelp(description=("Comprehensive phylogenetic " "model comparison and detection of selection informed by deep " "mutational scanning data. This program runs 'phydms' repeatedly " "to compare substitution models and detect selection. " ...
def PhyDMSComprehensiveParser()
Returns *argparse.ArgumentParser* for ``phdyms_comprehensive`` script.
3.976493
3.95781
1.004721
sys.stderr.write('error: %s\n\n' % message) self.print_help() sys.exit(2)
def error(self, message)
Prints error message, then help.
3.143209
2.788436
1.12723
'''Symmetrizes (ignores method). Returns a copy if copy=True.''' if copy: return SymmEdgePairGraph(self._pairs.copy(), num_vertices=self._num_vertices) shape = (self._num_vertices, self._num_vertices) flat_inds = np.union1d(np.ravel_multi_index(self._pairs.T, shape),...
def symmetrize(self, method=None, copy=False)
Symmetrizes (ignores method). Returns a copy if copy=True.
3.901051
3.406354
1.145227
'''Removes all from->to and to->from edges. Note: the symmetric kwarg is unused.''' flat_inds = self._pairs.dot((self._num_vertices, 1)) # convert to sorted order and flatten to_remove = (np.minimum(from_idx, to_idx) * self._num_vertices + np.maximum(from_idx, to_idx)) mask = np...
def remove_edges(self, from_idx, to_idx, symmetric=False, copy=False)
Removes all from->to and to->from edges. Note: the symmetric kwarg is unused.
4.672653
3.519521
1.327639
'''Adds all from->to edges. weight may be a scalar or 1d array. If symmetric=True, also adds to->from edges with the same weights.''' raise NotImplementedError()
def add_edges(self, from_idx, to_idx, weight=1, symmetric=False, copy=False)
Adds all from->to edges. weight may be a scalar or 1d array. If symmetric=True, also adds to->from edges with the same weights.
12.91597
2.79615
4.619197
'''Adds all i->i edges. weight may be a scalar or 1d array.''' ii = np.arange(self.num_vertices()) return self.add_edges(ii, ii, weight=weight, symmetric=False, copy=copy)
def add_self_edges(self, weight=None, copy=False)
Adds all i->i edges. weight may be a scalar or 1d array.
6.286253
3.691041
1.703111
'''Replaces existing edge weights. weight may be a scalar or 1d array. edges is a mask or index array that specifies a subset of edges to modify''' if not self.is_weighted(): warnings.warn('Cannot supply weights for unweighted graph; ' 'ignoring call to reweight') return self...
def reweight(self, weight, edges=None, copy=False)
Replaces existing edge weights. weight may be a scalar or 1d array. edges is a mask or index array that specifies a subset of edges to modify
5.816363
3.631865
1.601481
'''Replaces existing edge weights by distances between connected vertices. The new weight of edge (i,j) is given by: metric(coords[i], coords[j]). coords : (num_vertices x d) array of coordinates, in vertex order metric : str or callable, see sklearn.metrics.pairwise.paired_distances''' if not self....
def reweight_by_distance(self, coords, metric='l2', copy=False)
Replaces existing edge weights by distances between connected vertices. The new weight of edge (i,j) is given by: metric(coords[i], coords[j]). coords : (num_vertices x d) array of coordinates, in vertex order metric : str or callable, see sklearn.metrics.pairwise.paired_distances
4.671652
2.702457
1.728669
'''Returns an array of vertex degrees. kind : either 'in' or 'out', useful for directed graphs weighted : controls whether to count edges or sum their weights ''' if kind == 'out': axis = 1 adj = self.matrix('dense', 'csc') else: axis = 0 adj = self.matrix('dense', 'csr')...
def degree(self, kind='out', weighted=True)
Returns an array of vertex degrees. kind : either 'in' or 'out', useful for directed graphs weighted : controls whether to count edges or sum their weights
4.732234
3.172324
1.491725
'''Converts this Graph object to an igraph-compatible object. Requires the python-igraph library.''' # Import here to avoid ImportErrors when igraph isn't available. import igraph ig = igraph.Graph(n=self.num_vertices(), edges=self.pairs().tolist(), directed=self.is_directed())...
def to_igraph(self, weighted=None)
Converts this Graph object to an igraph-compatible object. Requires the python-igraph library.
4.343972
3.278683
1.324914
'''Converts this Graph object to a graph_tool-compatible object. Requires the graph_tool library. Note that the internal ordering of graph_tool seems to be column-major.''' # Import here to avoid ImportErrors when graph_tool isn't available. import graph_tool gt = graph_tool.Graph(directed=self....
def to_graph_tool(self)
Converts this Graph object to a graph_tool-compatible object. Requires the graph_tool library. Note that the internal ordering of graph_tool seems to be column-major.
3.757961
2.343073
1.60386
'''Converts this Graph object to a networkx-compatible object. Requires the networkx library.''' import networkx as nx directed = directed if directed is not None else self.is_directed() cls = nx.DiGraph if directed else nx.Graph adj = self.matrix() if ss.issparse(adj): return nx.from_...
def to_networkx(self, directed=None)
Converts this Graph object to a networkx-compatible object. Requires the networkx library.
3.160907
2.422697
1.304706
try: nz = len(z) z = np.array(z) except TypeError: z = np.array([z]) nz = len(z) try: nm = len(m) m = np.array(m) except TypeError: m = np.array([m]) nm = len(m) if (z < 0).any() or (m < 0).any(): raise ValueError('z and m...
def _check_inputs(z, m)
Check inputs are arrays of same length or array and a scalar.
2.412697
2.307405
1.045632
z, m = _check_inputs(z, m) a = 0.52 + 0.385 * np.exp(-0.617 * (z**1.21)) # EQ 10 b = -0.101 + 0.026 * z # EQ 11 logc200 = a + b * np.log10(m * h / (10.**12)) # EQ 7 concentration = 10.**logc200 return concentration
def c_DuttonMaccio(z, m, h=h)
Concentration from c(M) relation in Dutton & Maccio (2014). Parameters ---------- z : float or array_like Redshift(s) of halos. m : float or array_like Mass(es) of halos (m200 definition), in units of solar masses. h : float, optional Hubble parameter. Default is from Planck...
4.674171
4.697784
0.994974
z, m = _check_inputs(z, m) M_pivot = 2.e12 / h # [M_solar] A = 5.71 B = -0.084 C = -0.47 concentration = A * ((m / M_pivot)**B) * (1 + z)**C return concentration
def c_Duffy(z, m, h=h)
Concentration from c(M) relation published in Duffy et al. (2008). Parameters ---------- z : float or array_like Redshift(s) of halos. m : float or array_like Mass(es) of halos (m200 definition), in units of solar masses. h : float, optional Hubble parameter. Default is from...
6.303048
3.838231
1.642175
prop_default = { 'fontsize': 18, } for prop, default in prop_default.items(): kwargs[prop] = kwargs.get(prop, default) setattr(self.label, which, label) setattr(self.label, which + '_kwargs', kwargs) return
def _set_label(self, which, label, **kwargs)
Private method for setting labels. Args: which (str): The indicator of which part of the plots to adjust. This currently handles `xlabel`/`ylabel`, and `title`. label (str): The label to be added. fontsize (int, optional): Fontsize for associa...
3.629889
4.324605
0.839357
setattr(self.limits, which + 'lims', lims) setattr(self.limits, 'd' + which, d) setattr(self.limits, which + 'scale', scale) if reverse: setattr(self.limits, 'reverse_' + which + '_axis', True) return
def _set_axis_limits(self, which, lims, d, scale, reverse=False)
Private method for setting axis limits. Sets the axis limits on each axis for an individual plot. Args: which (str): The indicator of which part of the plots to adjust. This currently handles `x` and `y`. lims (len-2 list of floats): The limits for the axis. ...
2.629609
2.954589
0.890008
self._set_axis_limits('x', xlims, dx, xscale, reverse) return
def set_xlim(self, xlims, dx, xscale, reverse=False)
Set x limits for plot. This will set the limits for the x axis for the specific plot. Args: xlims (len-2 list of floats): The limits for the axis. dx (float): Amount to increment by between the limits. xscale (str): Scale of the axis. Either `log` or `lin`. ...
3.340441
4.703792
0.710159
self._set_axis_limits('y', xlims, dx, xscale, reverse) return
def set_ylim(self, xlims, dx, xscale, reverse=False)
Set y limits for plot. This will set the limits for the y axis for the specific plot. Args: ylims (len-2 list of floats): The limits for the axis. dy (float): Amount to increment by between the limits. yscale (str): Scale of the axis. Either `log` or `lin`. ...
3.45726
5.831851
0.592824
if 'size' in kwargs: if 'prop' not in kwargs: kwargs['prop'] = {'size': kwargs['size']} else: kwargs['prop']['size'] = kwargs['size'] del kwargs['size'] self.legend.add_legend = True self.legend.legend_labels = labels ...
def add_legend(self, labels=None, **kwargs)
Specify legend for a plot. Adds labels and basic legend specifications for specific plot. For the optional Args, refer to https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html for more information. # TODO: Add legend capabilities for Loss/Gain plots. This is possibl...
2.606921
2.860996
0.911194
if name is None and label is None and index is None: raise ValueError("Attempting to add a dataset without" + "supplying index or file information.") if index is None: trans_dict = DataImportContainer() if name is not None: ...
def add_dataset(self, name=None, label=None, x_column_label=None, y_column_label=None, index=None, control=False)
Add a dataset to a specific plot. This method adds a dataset to a plot. Its functional use is imperative to the plot generation. It handles adding new files as well as indexing to files that are added to other plots. All Args default to None. However, these are note the defaults ...
2.374227
2.289203
1.037141
self.figure.save_figure = True self.figure.output_path = output_path self.figure.savefig_kwargs = kwargs return
def savefig(self, output_path, **kwargs)
Save figure during generation. This method is used to save a completed figure during the main function run. It represents a call to ``matplotlib.pyplot.fig.savefig``. # TODO: Switch to kwargs for matplotlib.pyplot.savefig Args: output_path (str): Relative path to the WORKI...
4.956346
6.914257
0.71683
self.figure.figure_width = width self.figure.figure_height = height return
def set_fig_size(self, width, height=None)
Set the figure size in inches. Sets the figure size with a call to fig.set_size_inches. Default in code is 8 inches for each. Args: width (float): Dimensions for figure width in inches. height (float, optional): Dimensions for figure height in inches. Default is None.
4.947663
6.842483
0.72308
self.figure.spacing = space if 'subplots_adjust_kwargs' not in self.figure.__dict__: self.figure.subplots_adjust_kwargs = {} if space == 'wide': self.figure.subplots_adjust_kwargs['hspace'] = 0.3 self.figure.subplots_adjust_kwargs['wspace'] = 0.3 ...
def set_spacing(self, space)
Set the figure spacing. Sets whether in general there is space between subplots. If all axes are shared, this can be `tight`. Default in code is `wide`. The main difference is the tick labels extend to the ends if space==`wide`. If space==`tight`, the edge tick labels are cut off for c...
2.164652
2.077919
1.04174
prop_default = { 'bottom': 0.1, 'top': 0.85, 'right': 0.9, 'left': 0.12, 'hspace': 0.3, 'wspace': 0.3, } if 'subplots_adjust_kwargs' in self.figure.__dict__: for key, value in self.figure.subplots_adjus...
def subplots_adjust(self, **kwargs)
Adjust subplot spacing and dimensions. Adjust bottom, top, right, left, width in between plots, and height in between plots with a call to ``plt.subplots_adjust``. See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html for more information. Keyword Argum...
2.215376
2.43058
0.91146
prop_default = { 'x': 0.01, 'y': 0.51, 'fontsize': 20, 'rotation': 'vertical', 'va': 'center', } for prop, default in prop_default.items(): kwargs[prop] = kwargs.get(prop, default) self._set_fig_label('x',...
def set_fig_x_label(self, xlabel, **kwargs)
Set overall figure x. Set label for x axis on overall figure. This is not for a specific plot. It will place the label on the figure at the left with a call to ``fig.text``. Args: xlabel (str): xlabel for entire figure. Keyword Arguments: x/y (float, optional):...
3.007779
2.859968
1.051683
prop_default = { 'x': 0.45, 'y': 0.02, 'fontsize': 20, 'rotation': 'horizontal', 'ha': 'center', } for prop, default in prop_default.items(): kwargs[prop] = kwargs.get(prop, default) self._set_fig_label('y...
def set_fig_y_label(self, ylabel, **kwargs)
Set overall figure y. Set label for y axis on overall figure. This is not for a specific plot. It will place the label on the figure at the left with a call to ``fig.text``. Args: ylabel (str): ylabel for entire figure. Keyword Arguments: x/y (float, optional):...
2.935701
2.79532
1.05022
prop_default = { 'fontsize': 20, } for prop, default in prop_default.items(): kwargs[prop] = kwargs.get(prop, default) self.figure.fig_title = title self.figure.fig_title_kwargs = kwargs return
def set_fig_title(self, title, **kwargs)
Set overall figure title. Set title for overall figure. This is not for a specific plot. It will place the title at the top of the figure with a call to ``fig.suptitle``. Args: title (str): Figure title. Keywork Arguments: x/y (float, optional): The x/y locatio...
3.45741
4.25738
0.812098
prop_default = { 'cbar_label': None, 'cbar_ticks_fontsize': 15, 'cbar_label_fontsize': 20, 'cbar_axes': [], 'cbar_ticks': [], 'cbar_tick_labels': [], 'cbar_pos': 'use_default', 'cbar_label_pad': None, ...
def set_colorbar(self, plot_type, **kwargs)
Setup colorbar for specific type of plot. Specify a plot type to customize its corresponding colorbar in the figure. See the ColorbarContainer class attributes for more specific explanations. Args: plot_type (str): Type of plot to adjust. e.g. `Ratio` label (str, optio...
3.183172
3.269802
0.973506
if xlabel is not None: self.general.x_column_label = xlabel if ylabel is not None: self.general.y_column_label = ylabel if xlabel is None and ylabel is None: warnings.warn("is not specifying x or y lables even" + "though colu...
def set_all_file_column_labels(self, xlabel=None, ylabel=None)
Indicate general x,y column labels. This sets the general x and y column labels into data files for all plots. It can be overridden for specific plots. Args: xlabel/ylabel (str, optional): String indicating column label for x,y values into the data files. Default is...
4.831954
4.814994
1.003522
setattr(self.general, which + 'lims', lim) setattr(self.general, 'd' + which, d) setattr(self.general, which + 'scale', scale) if fontsize is not None: setattr(self.general, which + '_tick_label_fontsize', fontsize) return
def _set_all_lims(self, which, lim, d, scale, fontsize=None)
Set limits and ticks for an axis for whole figure. This will set axis limits and tick marks for the entire figure. It can be overridden in the SinglePlot class. Args: which (str): The indicator of which part of the plots to adjust. This currently handles `x` and `y`...
2.939409
2.879138
1.020933
self._set_all_lims('x', xlim, dx, xscale, fontsize) return
def set_all_xlims(self, xlim, dx, xscale, fontsize=None)
Set limits and ticks for x axis for whole figure. This will set x axis limits and tick marks for the entire figure. It can be overridden in the SinglePlot class. Args: xlim (len-2 list of floats): The limits for the axis. dx (float): Amount to increment by between the l...
3.425817
5.963494
0.574465
self._set_all_lims('y', ylim, dy, yscale, fontsize) return
def set_all_ylims(self, ylim, dy, yscale, fontsize=None)
Set limits and ticks for y axis for whole figure. This will set y axis limits and tick marks for the entire figure. It can be overridden in the SinglePlot class. Args: ylim (len-2 list of floats): The limits for the axis. dy (float): Amount to increment by between the l...
3.520278
6.294377
0.559274
if axis_to_reverse.lower() == 'x': self.general.reverse_x_axis = True if axis_to_reverse.lower() == 'y': self.general.reverse_y_axis = True if axis_to_reverse.lower() != 'x' or axis_to_reverse.lower() != 'y': raise ValueError('Axis for reversing needs...
def reverse_axis(self, axis_to_reverse)
Reverse an axis in all figure plots. This will reverse the tick marks on an axis for each plot in the figure. It can be overridden in SinglePlot class. Args: axis_to_reverse (str): Axis to reverse. Supports `x` and `y`. Raises: ValueError: The string representi...
2.406993
2.387093
1.008337
output_dict = {} output_dict['general'] = self._iterate_through_class(self.general.__dict__) output_dict['figure'] = self._iterate_through_class(self.figure.__dict__) if self.total_plots > 1: trans_dict = ({ str(i): self._iterate_through_c...
def return_dict(self)
Output dictionary for ``make_plot.py`` input. Iterates through the entire MainContainer class turning its contents into dictionary form. This dictionary becomes the input for ``make_plot.py``. If `print_input` attribute is True, the entire dictionary will be printed prior to returning ...
3.812616
3.475355
1.097044
output_dict = {} for key in class_dict: val = class_dict[key] try: val = val.__dict__ except AttributeError: pass if type(val) is dict: val = self._iterate_through_class(val) if type(va...
def _iterate_through_class(self, class_dict)
Recursive function for output dictionary creation. Function will check each value in a dictionary to see if it is a class, list, or dictionary object. The idea is to turn all class objects into dictionaries. If it is a class object it will pass its ``class.__dict__`` recursively through...
1.63031
1.677798
0.971696
# read in data = ascii.read(self.WORKING_DIRECTORY + '/' + self.file_name) # find number of distinct x and y points. num_x_pts = len(np.unique(data[self.x_column_label])) num_y_pts = len(np.unique(data[self.y_column_label])) # create 2D arrays of x,y,z ...
def txt_read_in(self)
Read in txt files. Method for reading in text or csv files. This uses ascii class from astropy.io for flexible input. It is slower than numpy, but has greater flexibility with less input.
2.242233
2.159382
1.038368
with h5py.File(self.WORKING_DIRECTORY + '/' + self.file_name) as f: # read in data = f['data'] # find number of distinct x and y points. num_x_pts = len(np.unique(data[self.x_column_label][:])) num_y_pts = len(np.unique(data[self.y_column_l...
def hdf5_read_in(self)
Method for reading in hdf5 files.
2.322183
2.285573
1.016018
# declare 1D arrays of both paramters if self.xscale != 'lin': self.xvals = np.logspace(np.log10(float(self.x_low)), np.log10(float(self.x_high)), self.num_x) else: self.xvals = np.linspa...
def set_parameters(self)
Setup all the parameters for the binaries to be evaluated. Grid values and store necessary parameters for input into the SNR function.
2.738242
2.717875
1.007494
if self.ecc: required_kwargs = {'dist_type': self.dist_type, 'initial_cond_type': self.initial_cond_type, 'ecc': True} input_args = [self.m1, self.m2, self.z_or_dist, self.initial_point, sel...
def run_snr(self)
Run the snr calculation. Takes results from ``self.set_parameters`` and other inputs and inputs these into the snr calculator.
3.535171
3.447164
1.02553
'''Record the payment event Official handler writes this information to TBK_EVN%Y%m%d file. ''' raise NotImplementedError("Logging Handler must implement event_payment")
def event_payment(self, date, time, pid, commerce_id, transaction_id, request_ip, token, webpay_server)
Record the payment event Official handler writes this information to TBK_EVN%Y%m%d file.
59.78373
5.480364
10.908714
'''Record the confirmation event. Official handler writes this information to TBK_EVN%Y%m%d file. ''' raise NotImplementedError("Logging Handler must implement event_confirmation")
def event_confirmation(self, date, time, pid, commerce_id, transaction_id, request_ip, order_id)
Record the confirmation event. Official handler writes this information to TBK_EVN%Y%m%d file.
50.633553
4.932531
10.265228
res = self.send_request('manager/stop', post=True) if res.status_code != 200: raise UnexpectedResponse( 'Attempted to stop manager. {res_code}: {res_text}'.format( res_code=res.status_code, res_text=res.text, )...
def stop(self)
If the manager is running, tell it to stop its process
5.619292
5.22931
1.074576
res = self.send_json_request('host/stop', data={'config': config_file}) if res.status_code != 200: raise UnexpectedResponse( 'Attempted to stop a JSHost. Response: {res_code}: {res_text}'.format( res_code=res.status_code, res_...
def stop_host(self, config_file)
Stops a managed host specified by `config_file`.
3.597583
3.519874
1.022077
if self and hasattr(self, 'proxies') and self.proxies is not None: response = requests.request('GET', url=PVWatts.PVWATTS_QUERY_URL, params=params, headers={'User-Agent': ...
def get_data(self, params={})
Make the request and return the deserialided JSON from the response :param params: Dictionary mapping (string) query parameters to values :type params: dict :return: JSON object with the data fetched from that URL as a JSON-format object. :rtype: (dict or array)
2.948053
3.013211
0.978376
if IRichInput.providedBy(input): richInput = unicode(input) symbolInput = unicode(input.symbol()) else: richInput = None symbolInput = unicode(input) action = LOG_FSM_TRANSITION( self.logger, fsm_identifier=self.id...
def receive(self, input)
Add logging of state transitions to the wrapped state machine. @see: L{IFiniteStateMachine.receive}
4.469768
4.365328
1.023925
prefix_len = len(self.prefix) for varname, value in os.environ.items(): if not varname.startswith(self.prefix): continue # Prepare values varname = varname[prefix_len:] value = value or app.config.get(varname) # Evalu...
def init_app(self, app)
Initialize Flask application.
2.758509
2.690231
1.02538
def smce_graph(X, metric='l2', sparsity_param=10, kmax=None, keep_ratio=0.95): '''Sparse graph construction from the SMCE paper. X : 2-dimensional array-like metric : str, optional sparsity_param : float, optional kmax : int, optional keep_ratio : float, optional When <1, keep edges up to (keep...
Sparse graph construction from the SMCE paper. X : 2-dimensional array-like metric : str, optional sparsity_param : float, optional kmax : int, optional keep_ratio : float, optional When <1, keep edges up to (keep_ratio * total weight) Returns a graph with asymmetric similarity weights. Ca...
null
null
null
def sparse_regularized_graph(X, positive=False, sparsity_param=None, kmax=None): '''Sparse Regularized Graph Construction, commonly known as an l1-graph. positive : bool, optional When True, computes the Sparse Probability Graph (SPG). sparsity_param : float, optional Controls sparsity cost in the ...
Sparse Regularized Graph Construction, commonly known as an l1-graph. positive : bool, optional When True, computes the Sparse Probability Graph (SPG). sparsity_param : float, optional Controls sparsity cost in the LASSO optimization. When None, uses cross-validation to find sparsity parameters. ...
null
null
null
if self.length < 100: raise Exception("Run this across 1 processor by setting num_processors kwarg to None.") if self.num_processors == -1: self.num_processors = mp.cpu_count() split_val = int(np.ceil(self.length/self.num_splits)) split_inds = [self.num_...
def prep_parallel(self, binary_args, other_args)
Prepare the parallel calculations Prepares the arguments to be run in parallel. It will divide up arrays according to num_splits. Args: binary_args (list): List of binary arguments for input into the SNR function. other_args (tuple of obj): tuple of other args for input...
3.366372
3.344401
1.00657
if self.timer: start_timer = time.time() # for testing # check = parallel_snr_func(*self.args[10]) # import pdb # pdb.set_trace() with mp.Pool(self.num_processors) as pool: print('start pool with {} processors: {} total processes.\n'.for...
def run_parallel(self, para_func)
Run parallel calulation This will run the parallel calculation on self.num_processors. Args: para_func (obj): Function object to be used in parallel. Returns: (dict): Dictionary with parallel results.
3.917133
3.977493
0.984825
def build_unparse(f): @wraps(f) def unparse(self, source, *a, **kw): node = parse_callable(source) return f(node, *a, **kw) # a dumb and lazy docstring replacement unparse.__doc__ = f.__doc__.replace( 'ast\n The AST ', 'sou...
def RawParserUnparserFactory(parser_name, parse_callable, *unparse_callables)
Produces a callable object that also has callable attributes that passes its first argument to the parent callable.
3.405183
3.240436
1.050841
parse_callable = import_module(PKGNAME + '.parsers.' + module_name).parse unparser_module = import_module(PKGNAME + '.unparsers.' + module_name) return RawParserUnparserFactory(module_name, parse_callable, *[ getattr(unparser_module, name) for name in unparser_names])
def ParserUnparserFactory(module_name, *unparser_names)
Produce a new parser/unparser object from the names provided.
4.100972
3.884688
1.055676
'''Downsamples all points together, then re-splits into original trajectories. trajectories : list of 2-d arrays, each representing a trajectory downsampler(X, *args, **kwargs) : callable that returns indices into X ''' X = np.vstack(trajectories) traj_lengths = list(map(len, trajectories)) inds = np.sor...
def downsample_trajectories(trajectories, downsampler, *args, **kwargs)
Downsamples all points together, then re-splits into original trajectories. trajectories : list of 2-d arrays, each representing a trajectory downsampler(X, *args, **kwargs) : callable that returns indices into X
3.93332
2.319464
1.695788
'''Selects a subset of `points` to preserve graph structure while minimizing the number of points used, by removing points within `close_distance`. Returns the downsampled indices.''' num_points = points.shape[0] indices = set(range(num_points)) selected = [] while indices: idx = indices.pop() nn_...
def epsilon_net(points, close_distance)
Selects a subset of `points` to preserve graph structure while minimizing the number of points used, by removing points within `close_distance`. Returns the downsampled indices.
5.360541
2.501253
2.143142
'''Uses Fuzzy C-Means to downsample `points`. m : aggregation parameter >1, larger implies smoother clusters Returns indices of downsampled points. ''' num_points = points.shape[0] if num_centers >= num_points: return np.arange(num_points) # randomly initialize cluster assignments matrix assn = np.r...
def fuzzy_c_means(points, num_centers, m=2., tol=1e-4, max_iter=100, verbose=False)
Uses Fuzzy C-Means to downsample `points`. m : aggregation parameter >1, larger implies smoother clusters Returns indices of downsampled points.
3.436575
2.644403
1.299565
if '/' not in url and ':' in url and url.rsplit(':')[-1].isdigit(): url = 'scgi://' + url url = urlparse.urlsplit(url, scheme="scgi", allow_fragments=False) # pylint: disable=redundant-keyword-arg try: transport = TRANSPORTS[url.scheme.lower()] except KeyError: if not any(...
def transport_from_url(url)
Create a transport for the given URL.
3.810565
3.777842
1.008662
"Wrap data in an SCGI request." prolog = "CONTENT_LENGTH\0%d\0SCGI\x001\0" % len(data) if headers: prolog += _encode_headers(headers) return _encode_netstring(prolog) + data
def _encode_payload(data, headers=None)
Wrap data in an SCGI request.
8.941624
6.320925
1.414607
"Get headers dict from header string." try: return dict(line.rstrip().split(": ", 1) for line in headers.splitlines() if line ) except (TypeError, ValueError) as exc: raise SCGIException("Error in SCGI headers %r (%s)" % (headers, exc,))
def _parse_headers(headers)
Get headers dict from header string.
5.540389
4.890387
1.132914
# Assume they care for standards and send us CRLF (not just LF) try: headers, payload = resp.split("\r\n\r\n", 1) except (TypeError, ValueError) as exc: raise SCGIException("No header delimiter in SCGI response of length %d (%s)" % (len(resp), exc,)) headers = _parse_headers(headers...
def _parse_response(resp)
Get xmlrpc response from scgi response
6.256322
5.763967
1.08542
xmlreq = xmlrpclib.dumps(params, methodname) xmlresp = SCGIRequest(url).send(xmlreq) if kw.get("deserialize", True): # This fixes a bug with the Python xmlrpclib module # (has no handler for <i8> in some versions) xmlresp = xmlresp.replace("<i8>", "<i4>").replace("</i8>", "</i4...
def scgi_request(url, methodname, *params, **kw)
Send a XMLRPC request over SCGI to the given URL. @param url: Endpoint URL. @param methodname: XMLRPC method name. @param params: Tuple of simple python objects. @keyword deserialize: Parse XML result? (default is True) @return: XMLRPC response, or the equivalent Python data.
4.834836
4.847836
0.997318
sock = socket.socket(*self.sock_args) try: sock.connect(self.sock_addr) except socket.error as exc: raise socket.error("Can't connect to %r (%s)" % (self.url.geturl(), exc)) try: # Send request sock.send(data) # Read ...
def send(self, data)
Open transport, send data, and yield response chunks.
2.656333
2.459877
1.079864
try: proc = subprocess.Popen(self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as exc: raise URLError("Calling %r failed (%s)!" % (' '.join(self.cmd), exc)) else: stdout, stderr = proc.communicate(data) ...
def send(self, data)
Open transport, send data, and yield response chunks.
2.853578
2.729654
1.045399
start = time.time() try: scgi_resp = ''.join(self.transport.send(_encode_payload(data))) finally: self.latency = time.time() - start resp, self.resp_headers = _parse_response(scgi_resp) return resp
def send(self, data)
Send data over scgi to URL and get response.
5.951215
4.64531
1.281123
''' Returns generator that iterates over frames in a traceback ''' frame = traceback while frame.tb_next: frame = frame.tb_next yield frame.tb_frame return
def _frames(traceback)
Returns generator that iterates over frames in a traceback
5.470098
3.963416
1.380147
''' Returns boolean whether traceback contains method from this instance ''' foundMethod = False for frame in self._frames(traceback): this = frame.f_locals.get('self') if this is self and frame.f_code.co_name == name: foundMethod = True break return foundMethod
def _methodInTraceback(self, name, traceback)
Returns boolean whether traceback contains method from this instance
5.084295
3.396866
1.496761
''' Add rollback step with optional arguments. If a rollback is triggered, each step is called in LIFO order. ''' self.steps.append((callback, args, kwargs))
def addStep(self, callback, *args, **kwargs)
Add rollback step with optional arguments. If a rollback is triggered, each step is called in LIFO order.
10.52972
2.511755
4.192176
''' Call each rollback step in LIFO order. ''' while self.steps: callback, args, kwargs = self.steps.pop() callback(*args, **kwargs)
def doRollback(self)
Call each rollback step in LIFO order.
6.89761
3.822841
1.804315
def neighbor_graph(X, metric='euclidean', k=None, epsilon=None, weighting='none', precomputed=False): '''Build a neighbor graph from pairwise distance information. X : two-dimensional array-like Shape must either be (num_pts, num_dims) or (num_pts, num_pts). k : int, maximum number...
Build a neighbor graph from pairwise distance information. X : two-dimensional array-like Shape must either be (num_pts, num_dims) or (num_pts, num_pts). k : int, maximum number of nearest neighbors epsilon : float, maximum distance to a neighbor metric : str, type of distance metric (see sklearn.m...
null
null
null
def nearest_neighbors(query_pts, target_pts=None, metric='euclidean', k=None, epsilon=None, return_dists=False, precomputed=False): '''Find nearest neighbors of query points from a matrix of target points. Returns a list of indices of neighboring points, one list pe...
Find nearest neighbors of query points from a matrix of target points. Returns a list of indices of neighboring points, one list per query. If no target_pts are specified, distances are calculated within query_pts. When return_dists is True, returns two lists: (distances, indices)
null
null
null
def _sparse_neighbor_graph(X, k, binary=False, metric='l2'): '''Construct a sparse adj matrix from a matrix of points (one per row). Non-zeros are unweighted/binary distance values, depending on the binary arg. Doesn't include self-edges.''' knn = NearestNeighbors(n_neighbors=k, metric=metric).fit(X) mod...
Construct a sparse adj matrix from a matrix of points (one per row). Non-zeros are unweighted/binary distance values, depending on the binary arg. Doesn't include self-edges.
null
null
null
'''a is (d,t), B is (k,d,t)''' # TODO: check case for t = d-1 if a.shape[1] == 1: return a.T.dot(B)[0,:,0] # find normals that maximize distance when projected x1 = np.einsum('abc,adc->abd', B, B).dot(a) - a # b.dot(b.T).dot(a) - a x2 = np.einsum('ab,cad->cbd', a.dot(a.T), B) - B # a.dot(a.T).dot(b)...
def _principal_angle(a, B)
a is (d,t), B is (k,d,t)
4.316128
4.041734
1.06789
limit = 15 if no_limit: limit = float('inf') with open_db(db, zip, encoding=encoding, case_sensitive=not case_insensitive) as dbf: for idx, row in enumerate(dbf, 1): click.secho('') for key, val in row._asdict().items(): click.secho(' %s: %s'...
def show(db, encoding, no_limit, zip, case_insensitive)
Show .dbf file contents (rows).
3.424582
3.438593
0.995925
with open_db(db, zip, case_sensitive=not case_insensitive) as dbf: click.secho('Rows count: %s' % (dbf.prolog.records_count)) click.secho('Fields:') for field in dbf.fields: click.secho(' %s: %s' % (field.type, field))
def describe(db, zip, case_insensitive)
Show .dbf file statistics.
4.460373
3.985655
1.119107
git(['clone', '--recursive', '-b', branch, repo, repo_dest])
def clone_repo(pkg, dest, repo, repo_dest, branch)
Clone the Playdoh repo into a custom path.
4.507569
5.115654
0.881133
vars = {'pkg': pkg} with dir_path(repo_dest): patch( % vars) git(['mv', 'project', pkg]) git(['commit', '-a', '-m', 'Renamed project module to %s' % pkg])
def init_pkg(pkg, repo_dest)
Initializes a custom named package module. This works by replacing all instances of 'project' with a custom module name.
10.918263
9.671057
1.128963
vars = {'pkg': pkg, 'db_user': db_user, 'db_name': db_name, 'db_password': db_password or '', 'db_host': db_host or '', 'db_port': db_port or '', 'hmac_date': datetime.now().strftime('%Y-%m-%d'), 'hmac_key': generate_key(32), ...
def create_settings(pkg, repo_dest, db_user, db_name, db_password, db_host, db_port)
Creates a local settings file out of the distributed template. This also fills in database settings and generates a secret key, etc.
3.263898
3.165471
1.031094
workon_home = os.environ.get('WORKON_HOME') venv_cmd = find_executable('virtualenv') python_bin = find_executable(python) if not python_bin: raise EnvironmentError('%s is not installed or not ' 'available on your $PATH' % python) if workon_home: # ...
def create_virtualenv(pkg, repo_dest, python)
Creates a virtualenv within which to install your new application.
3.669747
3.684046
0.996119
with dir_path(repo_dest): args = ['-r', 'requirements/compiled.txt'] if not verbose: args.insert(0, '-q') subprocess.check_call([os.path.join(venv, 'bin', 'pip'), 'install'] + args)
def install_reqs(venv, repo_dest)
Installs all compiled requirements that can't be shipped in vendor.
3.996126
3.622029
1.103284
for pt in os.environ.get('PATH', '').split(':'): candidate = os.path.join(pt, name) if os.path.exists(candidate): return candidate
def find_executable(name)
Finds the actual path to a named command. The first one on $PATH wins.
2.564459
3.335061
0.768939
old_dir = os.getcwd() os.chdir(dir) yield os.chdir(old_dir)
def dir_path(dir)
with dir_path(path) to change into a directory.
2.419539
2.459189
0.983877