code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if plot: pylab.clf() self.hist() self.plot_pdf(Nbest=Nbest, lw=lw) pylab.grid(True) Nbest = min(Nbest, len(self.distributions)) try: names = self.df_errors.sort_values( by="sumsquare_error").index[0:Nbest] ...
def summary(self, Nbest=5, lw=2, plot=True)
Plots the distribution of the data and Nbest distribution
3.599942
3.617224
0.995222
class InterruptableThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result = default self.exc_info = (None, None, None) def run(self): try: self.result = func(a...
def _timed_run(self, func, distribution, args=(), kwargs={}, default=None)
This function will spawn a thread and run the given function using the args, kwargs and return the given default value if the timeout is exceeded. http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call
2.723419
2.643816
1.030109
r return np.sum(np.dot(G.A, G.A), axis=1) / (np.sum(G.A, axis=1) + 1.)
def compute_avg_adj_deg(G)
r""" Compute the average adjacency degree for each node. The average adjacency degree is the average of the degrees of a node and its neighbors. Parameters ---------- G: Graph Graph on which the statistic is extracted
4.452445
5.703854
0.780603
r tig = compute_tig(g, **kwargs) return np.linalg.norm(tig, axis=1, ord=2)
def compute_norm_tig(g, **kwargs)
r""" Compute the :math:`\ell_2` norm of the Tig. See :func:`compute_tig`. Parameters ---------- g: Filter The filter or filter bank. kwargs: dict Additional parameters to be passed to the :func:`pygsp.filters.Filter.filter` method.
5.201986
5.579448
0.932348
r if not atom: def atom(x): return np.exp(-M * (x / G.lmax)**2) scale = np.linspace(0, G.lmax, M) spectr = np.empty((G.N, M)) for shift_idx in range(M): shift_filter = filters.Filter(G, lambda x: atom(x - scale[shift_idx])) tig = compute_norm_tig(shift_filter, ...
def compute_spectrogram(G, atom=None, M=100, **kwargs)
r""" Compute the norm of the Tig for all nodes with a kernel shifted along the spectral axis. Parameters ---------- G : Graph Graph on which to compute the spectrogram. atom : func Kernel to use in the spectrogram (default = exp(-M*(x/lmax)²)). M : int (optional) Num...
4.959955
3.410822
1.454182
r x = np.asanyarray(x) # Avoid to copy data as with np.array([g(x) for g in self._kernels]). y = np.empty([self.Nf] + list(x.shape)) for i, kernel in enumerate(self._kernels): y[i] = kernel(x) return y
def evaluate(self, x)
r"""Evaluate the kernels at given frequencies. Parameters ---------- x : array_like Graph frequencies at which to evaluate the filter. Returns ------- y : ndarray Frequency response of the filters. Shape ``(g.Nf, len(x))``. Examples ...
5.852732
6.990191
0.837278
r if s.ndim == 3 and s.shape[-1] != 1: raise ValueError('Last dimension (#features) should be ' '1, got {}.'.format(s.shape)) return self.filter(s, method, order)
def analyze(self, s, method='chebyshev', order=30)
r"""Convenience alias to :meth:`filter`.
6.03383
5.193557
1.161791
r if s.shape[-1] != self.Nf: raise ValueError('Last dimension (#features) should be the number ' 'of filters Nf = {}, got {}.'.format(self.Nf, s.shape)) return self.filter(s, method, order)
def synthesize(self, s, method='chebyshev', order=30)
r"""Convenience wrapper around :meth:`filter`. Will be an alias to `adjoint().filter()` in the future.
7.416657
6.423833
1.154553
r s = np.zeros(self.G.N) s[i] = 1 return np.sqrt(self.G.N) * self.filter(s, **kwargs)
def localize(self, i, **kwargs)
r"""Localize the kernels at a node (to visualize them). That is particularly useful to visualize a filter in the vertex domain. A kernel is localized on vertex :math:`v_i` by filtering a Kronecker delta :math:`\delta_i` as .. math:: (g(L) \delta_i)(j) = g(L)(i,j), \t...
6.63866
8.991295
0.738343
r if self.G.N > 2000: _logger.warning('Creating a big matrix. ' 'You should prefer the filter method.') # Filter one delta per vertex. s = np.identity(self.G.N) return self.filter(s, **kwargs).T.reshape(-1, self.G.N)
def compute_frame(self, **kwargs)
r"""Compute the associated frame. A filter bank defines a frame, which is a generalization of a basis to sets of vectors that may be linearly dependent. See `Wikipedia <https://en.wikipedia.org/wiki/Frame_(linear_algebra)>`_. The frame of a filter bank is the union of the frames of its...
11.266474
12.114826
0.929974
r def kernel(x, *args, **kwargs): y = self.evaluate(x) np.power(y, 2, out=y) y = np.sum(y, axis=0) if frame_bound is None: bound = y.max() elif y.max() > frame_bound: raise ValueError('The chosen bound is not ...
def complement(self, frame_bound=None)
r"""Return the filter that makes the frame tight. The complementary filter is designed such that the union of a filter bank and its complementary filter forms a tight frame. Parameters ---------- frame_bound : float or None The desired frame bound :math:`A = B` of t...
5.028481
4.25148
1.18276
r from pygsp.plotting import _plot_filter return _plot_filter(self, n=n, eigenvalues=eigenvalues, sum=sum, title=title, ax=ax, **kwargs)
def plot(self, n=500, eigenvalues=None, sum=None, title=None, ax=None, **kwargs)
r"""Docstring overloaded at import time.
3.658793
3.421882
1.069234
return super(Gabor, self).filter(s, method='exact')
def filter(self, s, method='exact', order=None)
TODO: indirection will be removed when poly filtering is merged.
13.624628
9.546903
1.427125
r if self._D is None: self.logger.warning('The differential operator G.D is not ' 'available, we need to compute it. Explicitly ' 'call G.compute_differential_operator() ' 'once beforehand to supp...
def D(self)
r"""Differential operator (for gradient and divergence). Is computed by :func:`compute_differential_operator`.
7.39989
6.803161
1.087713
r x = self._check_signal(x) return self.D.T.dot(x)
def grad(self, x)
r"""Compute the gradient of a signal defined on the vertices. The gradient :math:`y` of a signal :math:`x` is defined as .. math:: y = \nabla_\mathcal{G} x = D^\top x, where :math:`D` is the differential operator :attr:`D`. The value of the gradient on the edge :math:`e_k = (v_i, v_j...
13.311055
20.817278
0.639423
r y = np.asanyarray(y) if y.shape[0] != self.Ne: raise ValueError('First dimension must be the number of edges ' 'G.Ne = {}, got {}.'.format(self.Ne, y.shape)) return self.D.dot(y)
def div(self, y)
r"""Compute the divergence of a signal defined on the edges. The divergence :math:`z` of a signal :math:`y` is defined as .. math:: z = \operatorname{div}_\mathcal{G} y = D y, where :math:`D` is the differential operator :attr:`D`. The value of the divergence on the vertex :math:`v_i...
6.571594
9.101349
0.722046
r if n_eigenvectors is None: n_eigenvectors = self.n_vertices if (self._U is not None and n_eigenvectors <= len(self._e)): return assert self.L.shape == (self.n_vertices, self.n_vertices) if self.n_vertices**2 * n_eigenvectors > 3000**3: self...
def compute_fourier_basis(self, n_eigenvectors=None)
r"""Compute the (partial) Fourier basis of the graph (cached). The result is cached and accessible by the :attr:`U`, :attr:`e`, :attr:`lmax`, and :attr:`coherence` properties. Parameters ---------- n_eigenvectors : int or `None` Number of eigenvectors to compute. If...
4.670615
4.479486
1.042668
r s = self._check_signal(s) U = np.conjugate(self.U) # True Hermitian. (Although U is often real.) return np.tensordot(U, s, ([0], [0]))
def gft(self, s)
r"""Compute the graph Fourier transform. The graph Fourier transform of a signal :math:`s` is defined as .. math:: \hat{s} = U^* s, where :math:`U` is the Fourier basis attr:`U` and :math:`U^*` denotes the conjugate transpose or Hermitian transpose of :math:`U`. Parameters ...
10.411597
13.932919
0.747266
r s_hat = self._check_signal(s_hat) return np.tensordot(self.U, s_hat, ([1], [0]))
def igft(self, s_hat)
r"""Compute the inverse graph Fourier transform. The inverse graph Fourier transform of a Fourier domain signal :math:`\hat{s}` is defined as .. math:: s = U \hat{s}, where :math:`U` is the Fourier basis :attr:`U`. Parameters ---------- s_hat : array_like ...
5.601054
8.731914
0.641446
r G = f.G i = kwargs.pop('i', 0) if not N: N = m + 1 a_arange = [0, G.lmax] a1 = (a_arange[1] - a_arange[0]) / 2 a2 = (a_arange[1] + a_arange[0]) / 2 c = np.zeros(m + 1) tmpN = np.arange(N) num = np.cos(np.pi * (tmpN + 0.5) / N) for o in range(m + 1): c[o]...
def compute_cheby_coeff(f, m=30, N=None, *args, **kwargs)
r""" Compute Chebyshev coefficients for a Filterbank. Parameters ---------- f : Filter Filterbank with at least 1 filter m : int Maximum order of Chebyshev coeff to compute (default = 30) N : int Grid order used to compute quadrature (default = m + 1) ...
3.776926
3.759774
1.004562
r # Handle if we do not have a list of filters but only a simple filter in cheby_coeff. if not isinstance(c, np.ndarray): c = np.array(c) c = np.atleast_2d(c) Nscales, M = c.shape if M < 2: raise TypeError("The coefficients have an invalid shape") # thanks to that, we can ...
def cheby_op(G, c, signal, **kwargs)
r""" Chebyshev polynomial of graph Laplacian applied to vector. Parameters ---------- G : Graph c : ndarray or list of ndarrays Chebyshev coefficients for a Filter or a Filterbank signal : ndarray Signal to filter Returns ------- r : ndarray Result of the fi...
3.87077
3.811658
1.015508
r if not (isinstance(bounds, (list, np.ndarray)) and len(bounds) == 2): raise ValueError('Bounds of wrong shape.') bounds = np.array(bounds) m = int(kwargs.pop('order', 30) + 1) try: Nv = np.shape(signal)[1] r = np.zeros((G.N, Nv)) except IndexError: r = np.zer...
def cheby_rect(G, bounds, signal, **kwargs)
r""" Fast filtering using Chebyshev polynomial for a perfect rectangle filter. Parameters ---------- G : Graph bounds : array_like The bounds of the pass-band filter signal : array_like Signal to filter order : int (optional) Order of the Chebyshev polynomial (defaul...
3.526621
3.520016
1.001877
r # Parameters check if delta_lambda[0] > filter_bounds[0] or delta_lambda[1] < filter_bounds[1]: _logger.error("Bounds of the filter are out of the lambda values") raise() elif delta_lambda[0] > delta_lambda[1]: _logger.error("lambda_min is greater than lambda_max") rais...
def compute_jackson_cheby_coeff(filter_bounds, delta_lambda, m)
r""" To compute the m+1 coefficients of the polynomial approximation of an ideal band-pass between a and b, between a range of values defined by lambda_min and lambda_max. Parameters ---------- filter_bounds : list [a, b] delta_lambda : list [lambda_min, lambda_max] m : int ...
2.823387
2.735137
1.032266
r G = f.G Nf = len(f.g) # To have the right shape for the output array depending on the signal dim try: Nv = np.shape(s)[1] is2d = True c = np.zeros((G.N*Nf, Nv)) except IndexError: Nv = 1 is2d = False c = np.zeros((G.N*Nf)) tmpN = np.arange(...
def lanczos_op(f, s, order=30)
r""" Perform the lanczos approximation of the signal s. Parameters ---------- f: Filter s : ndarray Signal to approximate. order : int Degree of the lanczos approximation. (default = 30) Returns ------- L : ndarray lanczos approximation of s
3.469782
3.558622
0.975035
r try: N, M = np.shape(x) except ValueError: N = np.shape(x)[0] M = 1 x = x[:, np.newaxis] # normalization q = np.divide(x, np.kron(np.ones((N, 1)), np.linalg.norm(x, axis=0))) # initialization hiv = np.arange(0, order*M, order) V = np.zeros((N, M*order)...
def lanczos(A, order, x)
r""" TODO short description Parameters ---------- A: ndarray Returns -------
2.592021
2.616961
0.99047
r # Test the input parameters if isinstance(M, graphs.Graph): if not M.lap_type == 'combinatorial': raise NotImplementedError L = M.L else: L = M N = np.shape(L)[0] if not 1./np.sqrt(N) <= epsilon < 1: raise ValueError('GRAPH_SPARSIFY: Epsilon out of...
def graph_sparsify(M, epsilon, maxiter=10)
r"""Sparsify a graph (with Spielman-Srivastava). Parameters ---------- M : Graph or sparse matrix Graph structure or a Laplacian matrix epsilon : int Sparsification parameter Returns ------- Mnew : Graph or sparse matrix New graph structure or sparse matrix Not...
4.325468
4.140566
1.044656
r L_reg = G.L + reg_eps * sparse.eye(G.N) K_reg = getattr(G.mr, 'K_reg', kron_reduction(L_reg, keep_inds)) green_kernel = getattr(G.mr, 'green_kernel', filters.Filter(G, lambda x: 1. / (reg_eps + x))) alpha = K_reg.dot(f_subsampled) try: Nv = np.shape(f_subsa...
def interpolate(G, f_subsampled, keep_inds, order=100, reg_eps=0.005, **kwargs)
r"""Interpolate a graph signal. Parameters ---------- G : Graph f_subsampled : ndarray A graph signal on the graph G. keep_inds : ndarray List of indices on which the signal is sampled. order : int Degree of the Chebyshev approximation (default = 100). reg_eps : floa...
4.717455
4.907137
0.961346
r if isinstance(G, graphs.Graph): if G.lap_type != 'combinatorial': msg = 'Unknown reduction for {} Laplacian.'.format(G.lap_type) raise NotImplementedError(msg) if G.is_directed(): msg = 'This method only work for undirected graphs.' rai...
def kron_reduction(G, ind)
r"""Compute the Kron reduction. This function perform the Kron reduction of the weight matrix in the graph *G*, with boundary nodes labeled by *ind*. This function will create a new graph with a weight matrix Wnew that contain only boundary nodes and is computed as the Schur complement of the original ...
3.360586
3.370421
0.997082
r if np.shape(f)[0] != Gs[0].N: raise ValueError("PYRAMID ANALYSIS: The signal to analyze should have the same dimension as the first graph.") levels = len(Gs) - 1 # check if the type of filters is right. h_filters = kwargs.pop('h_filters', lambda x: 1. / (2*x+1)) if not isinstance(h_...
def pyramid_analysis(Gs, f, **kwargs)
r"""Compute the graph pyramid transform coefficients. Parameters ---------- Gs : list of graphs A multiresolution sequence of graph structures. f : ndarray Graph signal to analyze. h_filters : list A list of filter that will be used for the analysis and sythesis operator. ...
4.447117
3.797167
1.171167
r least_squares = bool(kwargs.pop('least_squares', False)) def_ul = Gs[0].N > 3000 or Gs[0]._e is None or Gs[0]._U is None use_landweber = bool(kwargs.pop('use_landweber', def_ul)) reg_eps = float(kwargs.get('reg_eps', 0.005)) if least_squares and 'h_filters' not in kwargs: ValueError('...
def pyramid_synthesis(Gs, cap, pe, order=30, **kwargs)
r"""Synthesize a signal from its pyramid coefficients. Parameters ---------- Gs : Array of Graphs A multiresolution sequence of graph structures. cap : ndarray Coarsest approximation of the original signal. pe : ndarray Prediction error at each level. use_exact : bool ...
4.956628
3.930243
1.261151
if not hasattr(self, '_coefficients'): # Graph Fourier transform -> modulation -> inverse GFT. c = self.G.igft(self._kernels.evaluate(self.G.e).squeeze()) c = np.sqrt(self.G.n_vertices) * self.G.U * c[:, np.newaxis] self._coefficients = self.G.gft(c) ...
def evaluate(self, x)
TODO: will become _evaluate once polynomial filtering is merged.
5.251229
5.026245
1.044762
if self._modulation_first: return super(Modulation, self).filter(s, method='exact') else: # The dot product with each modulated kernel is equivalent to the # GFT, as for the localization and the IGFT. y = np.empty((self.G.n_vertices, self.G.n_vert...
def filter(self, s, method='exact', order=None)
TODO: indirection will be removed when poly filtering is merged. TODO: with _filter and shape handled in Filter.filter, synthesis will work.
6.761902
6.428928
1.051793
r # Preserve documentation of plot. @functools.wraps(plot) def inner(obj, **kwargs): # Create a figure and an axis if none were passed. if kwargs['ax'] is None: _, plt, _ = _import_plt() fig = plt.figure() global _plt_figures _plt_figure...
def _plt_handle_figure(plot)
r"""Handle the common work (creating an axis if not given, setting the title) of all matplotlib plot commands.
3.904582
3.91142
0.998252
r # Windows can be closed by releasing all references to them so they can be # garbage collected. May not be necessary to call close(). global _qtg_windows for window in _qtg_windows: window.close() _qtg_windows = [] global _qtg_widgets for widget in _qtg_widgets: widge...
def close_all()
r"""Close all opened windows.
4.932296
4.481461
1.1006
r _, plt, _ = _import_plt() plt.show(*args, **kwargs)
def show(*args, **kwargs)
r"""Show created figures, alias to ``plt.show()``. By default, showing plots does not block the prompt. Calling this function will block execution.
13.584561
10.459726
1.298749
r _, plt, _ = _import_plt() plt.close(*args, **kwargs)
def close(*args, **kwargs)
r"""Close last created figure, alias to ``plt.close()``.
14.962062
10.103118
1.480935
r if eigenvalues is None: eigenvalues = (filters.G._e is not None) if sum is None: sum = filters.n_filters > 1 if title is None: title = repr(filters) return _plt_plot_filter(filters, n=n, eigenvalues=eigenvalues, sum=sum, title=title, ax=ax, *...
def _plot_filter(filters, n, eigenvalues, sum, title, ax, **kwargs)
r"""Plot the spectral response of a filter bank. Parameters ---------- n : int Number of points where the filters are evaluated. eigenvalues : boolean Whether to show the eigenvalues of the graph Laplacian. The eigenvalues should have been computed with :meth:`~pygsp.gra...
3.879429
4.419518
0.877795
r from pygsp import features qtg, _, _ = _import_qtg() if not hasattr(G, 'spectr'): features.compute_spectrogram(G) M = G.spectr.shape[1] spectr = G.spectr[node_idx, :] if node_idx is not None else G.spectr spectr = np.ravel(spectr) min_spec, max_spec = spectr.min(), spectr.ma...
def _plot_spectrogram(G, node_idx)
r"""Plot the graph's spectrogram. Parameters ---------- node_idx : ndarray Order to sort the nodes in the spectrogram. By default, does not reorder the nodes. Notes ----- This function is only implemented for the pyqtgraph backend at the moment. Examples -------- >...
3.60162
3.487439
1.032741
r y[M == False] = 0 Y = _to_logits(y.astype(np.int)) return regression_tikhonov(G, Y, M, tau)
def classification_tikhonov(G, y, M, tau=0)
r"""Solve a classification problem on graph via Tikhonov minimization. The function first transforms :math:`y` in logits :math:`Y`, then solves .. math:: \operatorname*{arg min}_X \| M X - Y \|_2^2 + \tau \ tr(X^T L X) if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_X tr(X^T L X) \ \text{...
7.748217
15.387325
0.503545
r if tau > 0: y[M == False] = 0 if sparse.issparse(G.L): def Op(x): return (M * x.T).T + tau * (G.L.dot(x)) LinearOp = sparse.linalg.LinearOperator([G.N, G.N], Op) if y.ndim > 1: sol = np.empty(shape=y.shape) ...
def regression_tikhonov(G, y, M, tau=0)
r"""Solve a regression problem on graph via Tikhonov minimization. The function solves .. math:: \operatorname*{arg min}_x \| M x - y \|_2^2 + \tau \ x^T L x if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_x x^T L x \ \text{ s. t. } \ y = M x otherwise. Parameters ----------...
3.567299
3.655585
0.975849
r signal = self._check_signal(signal) self.signals[name] = signal
def set_signal(self, signal, name)
r"""Attach a signal to the graph. Attached signals can be accessed (and modified or deleted) through the :attr:`signals` dictionary. Parameters ---------- signal : array_like A sequence that assigns a value to each vertex. The value of the signal at vert...
6.943024
15.965492
0.434877
r adjacency = self.W[vertices, :][:, vertices] try: coords = self.coords[vertices] except AttributeError: coords = None graph = Graph(adjacency, self.lap_type, coords, self.plotting) for name, signal in self.signals.items(): graph.set_s...
def subgraph(self, vertices)
r"""Create a subgraph from a list of vertices. Parameters ---------- vertices : list Vertices to keep. Either a list of indices or an indicator function. Returns ------- subgraph : :class:`Graph` Subgraph. Examples --...
5.753093
6.388507
0.900538
r if self._connected is not None: return self._connected adjacencies = [self.W] if self.is_directed(): adjacencies.append(self.W.T) for adjacency in adjacencies: visited = np.zeros(self.n_vertices, dtype=np.bool) stack = set([0]) ...
def is_connected(self)
r"""Check if the graph is connected (cached). A graph is connected if and only if there exists a (directed) path between any two vertices. Returns ------- connected : bool True if the graph is connected, False otherwise. Notes ----- For und...
2.485103
2.674634
0.929138
r if self._directed is None: self._directed = (self.W != self.W.T).nnz != 0 return self._directed
def is_directed(self)
r"""Check if the graph has directed edges (cached). In this framework, we consider that a graph is directed if and only if its weight matrix is not symmetric. Returns ------- directed : bool True if the graph is directed, False otherwise. Examples -...
5.715477
6.441412
0.887302
r if self.A.shape[0] != self.A.shape[1]: self.logger.error('Inconsistent shape to extract components. ' 'Square matrix required.') return None if self.is_directed(): raise NotImplementedError('Directed graphs not supported yet.')...
def extract_components(self)
r"""Split the graph into connected components. See :func:`is_connected` for the method used to determine connectedness. Returns ------- graphs : list A list of graph structures. Each having its own node list and weight matrix. If the graph is directed, a...
4.315772
4.375573
0.986333
r s = np.asanyarray(s) if s.shape[0] != self.n_vertices: raise ValueError('First dimension must be the number of vertices ' 'G.N = {}, got {}.'.format(self.N, s.shape)) return s
def _check_signal(self, s)
r"""Check if signal is valid.
6.040164
6.024555
1.002591
r x = self._check_signal(x) return x.T.dot(self.L.dot(x))
def dirichlet_energy(self, x)
r"""Compute the Dirichlet energy of a signal defined on the vertices. The Dirichlet energy of a signal :math:`x` is defined as .. math:: x^\top L x = \| \nabla_\mathcal{G} x \|_2^2 = \frac12 \sum_{i,j} W[i, j] (x[j] - x[i])^2 for the combinatorial Laplacian, and ...
10.045087
14.230047
0.705907
r if self._A is None: self._A = self.W > 0 return self._A
def A(self)
r"""Graph adjacency matrix (the binary version of W). The adjacency matrix defines which edges exist on the graph. It is represented as an N-by-N matrix of booleans. :math:`A_{i,j}` is True if :math:`W_{i,j} > 0`.
8.976963
7.824647
1.147267
r if self._d is None: if not self.is_directed(): # Shortcut for undirected graphs. self._d = self.W.getnnz(axis=1) # axis=1 faster for CSR (https://stackoverflow.com/a/16391764) else: degree_in = self.W.getnnz(axis=0...
def d(self)
r"""The degree (number of neighbors) of vertices. For undirected graphs, the degree of a vertex is the number of vertices it is connected to. For directed graphs, the degree is the average of the in and out degrees, where the in degree is the number of incoming edges, and the ou...
4.153697
3.877913
1.071117
r if self._dw is None: if not self.is_directed(): # Shortcut for undirected graphs. self._dw = np.ravel(self.W.sum(axis=0)) else: degree_in = np.ravel(self.W.sum(axis=0)) degree_out = np.ravel(self.W.sum(axis=1)) ...
def dw(self)
r"""The weighted degree of vertices. For undirected graphs, the weighted degree of the vertex :math:`v_i` is defined as .. math:: d[i] = \sum_j W[j, i] = \sum_j W[i, j], where :math:`W` is the weighted adjacency matrix :attr:`W`. For directed graphs, the weighted degree of th...
2.810119
2.710153
1.036886
r if self._lmax is None: self.logger.warning('The largest eigenvalue G.lmax is not ' 'available, we need to estimate it. ' 'Explicitly call G.estimate_lmax() or ' 'G.compute_fourier_basis() ' ...
def lmax(self)
r"""Largest eigenvalue of the graph Laplacian. Can be exactly computed by :func:`compute_fourier_basis` or approximated by :func:`estimate_lmax`.
7.479468
5.717588
1.308151
r if method == self._lmax_method: return self._lmax_method = method if method == 'lanczos': try: # We need to cast the matrix L to a supported type. # TODO: not good for memory. Cast earlier? lmax = sparse.linalg.ei...
def estimate_lmax(self, method='lanczos')
r"""Estimate the Laplacian's largest eigenvalue (cached). The result is cached and accessible by the :attr:`lmax` property. Exact value given by the eigendecomposition of the Laplacian, see :func:`compute_fourier_basis`. That estimation is much faster than the eigendecomposition. ...
4.169281
3.896341
1.07005
r if self.lap_type == 'normalized': return 2 # Equal iff the graph is bipartite. elif self.lap_type == 'combinatorial': bounds = [] # Equal for full graphs. bounds += [self.n_vertices * np.max(self.W)] # Gershgorin circle theorem. Equ...
def _get_upper_bound(self)
r"""Return an upper bound on the eigenvalues of the Laplacian.
6.374532
5.743394
1.109889
r if self.is_directed(): W = self.W.tocoo() else: W = sparse.triu(self.W, format='coo') sources = W.row targets = W.col weights = W.data assert self.n_edges == sources.size == targets.size == weights.size return sources, targets,...
def get_edge_list(self)
r"""Return an edge list, an alternative representation of the graph. Each edge :math:`e_k = (v_i, v_j) \in \mathcal{E}` from :math:`v_i` to :math:`v_j` is associated with the weight :math:`W[i, j]`. For each edge :math:`e_k`, the method returns :math:`(i, j, W[i, j])` as `(sources[k], t...
3.826515
4.143363
0.923529
r from pygsp.plotting import _plot_graph return _plot_graph(self, vertex_color=vertex_color, vertex_size=vertex_size, highlight=highlight, edges=edges, indices=indices, colorbar=colorbar, edge_color=edge_color, edge...
def plot(self, vertex_color=None, vertex_size=None, highlight=[], edges=None, edge_color=None, edge_width=None, indices=False, colorbar=True, limits=None, ax=None, title=None, backend=None)
r"""Docstring overloaded at import time.
2.136193
2.111421
1.011732
r from pygsp.plotting import _plot_spectrogram _plot_spectrogram(self, node_idx=node_idx)
def plot_spectrogram(self, node_idx=None)
r"""Docstring overloaded at import time.
4.842373
5.253648
0.921716
r if A is None: def A(x): return x if At is None: def At(x): return x tight = 0 l1_nu = 2 * G.lmax * nu if use_matrix: def l1_a(x): return G.Diff * A(x) def l1_at(x): return G.Diff * At(D.T * x) else: ...
def prox_tv(x, gamma, G, A=None, At=None, nu=1, tol=10e-4, maxit=200, use_matrix=True)
r""" Total Variation proximal operator for graphs. This function computes the TV proximal operator for graphs. The TV norm is the one norm of the gradient. The gradient is defined in the function :meth:`pygsp.graphs.Graph.grad`. This function requires the PyUNLocBoX to be executed. This functi...
4.414818
4.060869
1.087161
r warn = False msg = 'The given matrix' # check symmetry if np.abs(self.A - self.A.T).sum() > 0: warn = True msg = '{} is not symmetric,'.format(msg) # check parallel edged if self.A.max(axis=None) > 1: warn = True ...
def is_regular(self)
r""" Troubleshoot a given regular graph.
4.044256
3.682601
1.098206
r for name in list(self.signals.keys()): if self.signals[name].ndim == 2: for i, signal_1d in enumerate(self.signals[name].T): self.signals[name + '_' + str(i)] = signal_1d del self.signals[name]
def _break_signals(self)
r"""Break N-dimensional signals into N 1D signals.
3.581225
2.871929
1.246975
r joined = dict() for name in self.signals: name_base = name.rsplit('_', 1)[0] names = joined.get(name_base, list()) names.append(name) joined[name_base] = names for name_base, names in joined.items(): if len(names) > 1: ...
def _join_signals(self)
r"""Join N 1D signals into one N-dimensional signal.
3.367244
3.19688
1.053291
r nx = _import_networkx() def convert(number): # NetworkX accepts arbitrary python objects as attributes, but: # * the GEXF writer does not accept any NumPy types (on signals), # * the GraphML writer does not accept NumPy ints. if issubclass(numbe...
def to_networkx(self)
r"""Export the graph to NetworkX. Edge weights are stored as an edge attribute, under the name "weight". Signals are stored as node attributes, under their name in the :attr:`signals` dictionary. `N`-dimensional signals are broken into `N` 1-dimensional signals. They wi...
4.432641
4.893656
0.905793
r # See gt.value_types() for the list of accepted types. # See the definition of _type_alias() for a list of aliases. # Mapping from https://docs.scipy.org/doc/numpy/user/basics.types.html. convert = { np.bool_: 'bool', np.int8: 'int8_t', np.i...
def to_graphtool(self)
r"""Export the graph to graph-tool. Edge weights are stored as an edge property map, under the name "weight". Signals are stored as vertex property maps, under their name in the :attr:`signals` dictionary. `N`-dimensional signals are broken into `N` 1-dimensional signals. ...
2.695962
2.558387
1.053774
r nx = _import_networkx() from .graph import Graph adjacency = nx.to_scipy_sparse_matrix(graph, weight=weight) graph_pg = Graph(adjacency) for i, node in enumerate(graph.nodes()): for name in graph.nodes[node].keys(): try: ...
def from_networkx(cls, graph, weight='weight')
r"""Import a graph from NetworkX. Edge weights are retrieved as an edge attribute, under the name specified by the ``weight`` parameter. Signals are retrieved from node attributes, and stored in the :attr:`signals` dictionary under the attribute name. `N`-dimensional signals th...
3.838067
4.206926
0.912321
r gt = _import_graphtool() import graph_tool.spectral from .graph import Graph weight = graph.edge_properties.get(weight, None) adjacency = gt.spectral.adjacency(graph, weight=weight) graph_pg = Graph(adjacency.T) for name, signal in graph.vertex_propert...
def from_graphtool(cls, graph, weight='weight')
r"""Import a graph from graph-tool. Edge weights are retrieved as an edge property, under the name specified by the ``weight`` parameter. Signals are retrieved from node properties, and stored in the :attr:`signals` dictionary under the property name. `N`-dimensional signals th...
6.107215
6.60002
0.925333
r if fmt is None: fmt = os.path.splitext(path)[1][1:] if fmt not in ['graphml', 'gml', 'gexf']: raise ValueError('Unsupported format {}.'.format(fmt)) def load_networkx(path, fmt): nx = _import_networkx() load = getattr(nx, 'read_' + fmt)...
def load(cls, path, fmt=None, backend=None)
r"""Load a graph from a file. Edge weights are retrieved as an edge attribute named "weight". Signals are retrieved from node attributes, and stored in the :attr:`signals` dictionary under the attribute name. `N`-dimensional signals that were broken during export are joined. P...
1.992083
1.868206
1.066308
r data = pkgutil.get_data('pygsp', 'data/' + path + '.mat') data = io.BytesIO(data) return scipy.io.loadmat(data)
def loadmat(path)
r""" Load a matlab data file. Parameters ---------- path : string Path to the mat file from the data folder, without the .mat extension. Returns ------- data : dict dictionary with variable names as keys, and loaded matrices as values. Examples -------- ...
4.08848
6.701628
0.610073
r try: x.shape[1] except IndexError: x = x.reshape(1, x.shape[0]) if y is None: y = x else: try: y.shape[1] except IndexError: y = y.reshape(1, y.shape[0]) rx, cx = x.shape ry, cy = y.shape # Size verification if rx ...
def distanz(x, y=None)
r""" Calculate the distance between two colon vectors. Parameters ---------- x : ndarray First colon vector y : ndarray Second colon vector Returns ------- d : ndarray Distance between x and y Examples -------- >>> from pygsp import utils >>> x ...
2.528706
2.813174
0.89888
r if sparse.issparse(G): L = G.tocsc() else: if G.lap_type != 'combinatorial': raise ValueError('Need a combinatorial Laplacian.') L = G.L.tocsc() try: pseudo = sparse.linalg.inv(L) except RuntimeError: pseudo = sparse.lil_matrix(np.linalg.pinv(...
def resistance_distance(G)
r""" Compute the resistance distances of a graph. Parameters ---------- G : Graph or sparse matrix Graph structure or Laplacian matrix (L) Returns ------- rd : sparse matrix distance matrix References ---------- :cite:`klein1993resistance`
3.856943
3.596397
1.072446
r if W.shape[0] != W.shape[1]: raise ValueError('Matrix must be square.') if method == 'average': return (W + W.T) / 2 elif method == 'maximum': if sparse.issparse(W): bigger = (W.T > W) return W - W.multiply(bigger) + W.T.multiply(bigger) else: ...
def symmetrize(W, method='average')
r""" Symmetrize a square matrix. Parameters ---------- W : array_like Square matrix to be symmetrized method : string * 'average' : symmetrize by averaging with the transpose. Most useful when transforming a directed graph to an undirected one. * 'maximum' : symmet...
2.873098
2.807107
1.023508
r N = x.shape[1] y = x - np.kron(np.ones((1, N)), np.mean(x, axis=1)[:, np.newaxis]) c = np.amax(y) r = y / c return r
def rescale_center(x)
r""" Rescale and center data, e.g. embedding coordinates. Parameters ---------- x : ndarray Data to be rescaled. Returns ------- r : ndarray Rescaled data. Examples -------- >>> from pygsp import utils >>> x = np.array([[1, 6], [2, 5], [3, 4]]) >>> util...
4.472158
5.349227
0.836038
r scale_min = t1 / lmax scale_max = t2 / lmin return np.exp(np.linspace(np.log(scale_max), np.log(scale_min), Nscales))
def compute_log_scales(lmin, lmax, Nscales, t1=1, t2=2)
r""" Compute logarithm scales for wavelets. Parameters ---------- lmin : float Smallest non-zero eigenvalue. lmax : float Largest eigenvalue, i.e. :py:attr:`pygsp.graphs.Graph.lmax`. Nscales : int Number of scales. Returns ------- scales : ndarray Li...
3.157362
5.087738
0.620583
for name in names: module = importlib.import_module(src + '.' + name) setattr(sys.modules[dst], name, module)
def import_modules(names, src, dst)
Import modules in package.
2.068207
2.286816
0.904404
for name in names: module = importlib.import_module('pygsp.' + src + '.' + name.lower()) setattr(sys.modules['pygsp.' + dst], name, getattr(module, name))
def import_classes(names, src, dst)
Import classes in package from their implementation modules.
2.733793
2.890965
0.945634
for name in names: module = importlib.import_module('pygsp.' + src) setattr(sys.modules['pygsp.' + dst], name, getattr(module, name))
def import_functions(names, src, dst)
Import functions in package from their implementation modules.
3.080429
3.167238
0.972591
if isinstance(result, dict): if result.get('status') == 'failed': raise ActionFailed(retcode=result.get('retcode')) return result.get('data')
def _handle_api_result(result: Optional[Dict[str, Any]]) -> Any
Retrieve 'data' field from the API result object. :param result: API result that received from HTTP API :return: the 'data' field in result object :raise ActionFailed: the 'status' field is 'failed'
4.353683
3.159768
1.377849
idx = 0 while idx < len(self): if idx > 0 and \ self[idx - 1].type == 'text' and self[idx].type == 'text': self[idx - 1].data['text'] += self[idx].data['text'] del self[idx] else: idx += 1
def reduce(self) -> None
Remove redundant segments. Since this class is implemented based on list, this method may require O(n) time.
2.857631
2.634682
1.084621
if reduce: self.reduce() result = '' for seg in self: if seg.type == 'text': result += ' ' + seg.data['text'] if result: result = result[1:] return result
def extract_plain_text(self, reduce: bool = False) -> str
Extract text segments from the message, joined by single space. :param reduce: reduce the message before extracting :return: the joined string
4.573221
3.97392
1.150808
from django.utils.encoding import force_text from django.core.mail import EmailMultiAlternatives from mailer.models import make_message priority = get_priority(priority) # need to do this in case subject used lazy version of ugettext subject = force_text(subject) message = force_text(...
def send_html_mail(subject, message, message_html, from_email, recipient_list, priority=None, fail_silently=False, auth_user=None, auth_password=None, headers={})
Function to queue HTML e-mails
2.822615
2.774627
1.017295
to = filter_recipient_list(to) bcc = filter_recipient_list(bcc) core_msg = EmailMessage( subject=subject, body=body, from_email=from_email, to=to, bcc=bcc, attachments=attachments, headers=headers ) db_msg = Message(priority=priority) ...
def make_message(subject="", body="", from_email=None, to=None, bcc=None, attachments=None, headers=None, priority=None)
Creates a simple message for the email parameters supplied. The 'to' and 'bcc' lists are filtered using DontSendEntry. If needed, the 'email' attribute can be set to any instance of EmailMessage if e-mails with attachments etc. need to be supported. Call 'save()' on the result when it is ready to be s...
2.417308
2.58059
0.936727
queryset = self.filter(to_address__iexact=address) return queryset.exists()
def has_address(self, address)
is the given address on the don't send list?
6.402432
5.020135
1.275351
return self.create( message_data=message.message_data, message_id=get_message_id(message.email), when_added=message.when_added, priority=message.priority, # @@@ other fields from Message result=result_code, log_message=...
def log(self, message, result_code, log_message="")
create a log entry for an attempt to send the given message and record the given result and (optionally) a log message
5.847821
5.585184
1.047024
while True: hp_qs = Message.objects.high_priority().using('default') mp_qs = Message.objects.medium_priority().using('default') lp_qs = Message.objects.low_priority().using('default') while hp_qs.count() or mp_qs.count(): while hp_qs.count(): for mes...
def prioritize()
Yield the messages in the queue in the order they should be sent.
2.748701
2.494098
1.102082
# The actual backend to use for sending, defaulting to the Django default. # To make testing easier this is not stored at module level. EMAIL_BACKEND = getattr( settings, "MAILER_EMAIL_BACKEND", "django.core.mail.backends.smtp.EmailBackend" ) acquired, lock = acquire_lo...
def send_all()
Send all eligible messages in the queue.
4.658339
4.58437
1.016135
while True: while not Message.objects.all(): logging.debug("sleeping for %s seconds before checking queue again" % EMPTY_QUEUE_SLEEP) time.sleep(EMPTY_QUEUE_SLEEP) send_all()
def send_loop()
Loop indefinitely, checking queue at intervals of EMPTY_QUEUE_SLEEP and sending messages if any are on queue.
5.999557
3.806597
1.576094
if isinstance(name, str): components = name.split('.') mod = __import__('.'.join(components[0:-1]), globals(), locals(), [components[-1]] ) return getattr(mod, components[-1]) else: return name
def import_name(name)
import module given by str or pass the module if it is not str
2.078004
1.901169
1.093014
if request.user.is_authenticated: try: return { 'ACCOUNT_EXPIRED': request.user.userplan.is_expired(), 'ACCOUNT_NOT_ACTIVE': ( not request.user.userplan.is_active() and not request.user.userplan.is_expired()), 'EXPIRE_IN_DAYS'...
def account_status(request)
Set following ``RequestContext`` variables: * ``ACCOUNT_EXPIRED = boolean``, account was expired state, * ``ACCOUNT_NOT_ACTIVE = boolean``, set when account is not expired, but it is over quotas so it is not active * ``EXPIRE_IN_DAYS = integer``, number of days to...
3.430434
2.18326
1.571244
for plan in queryset: plan_copy = deepcopy(plan) plan_copy.id = None plan_copy.available = False plan_copy.default = False plan_copy.created = None plan_copy.save(force_insert=True) for pricing in plan.planpricing_set.all(): pricing.id = None...
def copy_plan(modeladmin, request, queryset)
Admin command for duplicating plans preserving quotas and pricings.
1.980598
1.778664
1.113531
# Retrieve all quotas that are used by any ``Plan`` in ``plan_list`` quota_list = Quota.objects.all().filter(planquota__plan__in=plan_list).distinct() # Create random access dict that for every ``Plan`` map ``Quota`` -> ``PlanQuota`` plan_quotas_dic = {} for plan in pl...
def get_plan_table(self, plan_list)
This method return a list in following order: [ ( Quota1, [ Plan1Quota1, Plan2Quota1, ... , PlanNQuota1] ), ( Quota2, [ Plan1Quota2, Plan2Quota2, ... , PlanNQuota2] ), ... ( QuotaM, [ Plan1QuotaM, Plan2QuotaM, ... , PlanNQuotaM] ), ] This can be v...
4.558063
3.500732
1.302031
order = Order(pk=-1) order.amount = amount order.currency = self.get_currency() country = getattr(billing_info, 'country', None) if not country is None: country = country.code tax_number = getattr(billing_info, 'tax_number', None) # Calculati...
def recalculate(self, amount, billing_info)
Calculates and return pre-filled Order
4.890622
4.750306
1.029538
self.plan_pricing = get_object_or_404(PlanPricing.objects.all().select_related('plan', 'pricing'), Q(pk=self.kwargs['pk']) & Q(plan__available=True) & ( Q(plan__customized=self.request.user) | Q( ...
def get_all_context(self)
Retrieves Plan and Pricing for current order creation
4.748603
4.063541
1.168587
if created: Invoice.create(instance, Invoice.INVOICE_TYPES['PROFORMA'])
def create_proforma_invoice(sender, instance, created, **kwargs)
For every Order if there are defined billing_data creates invoice proforma, which is an order confirmation document
5.988439
7.334734
0.816449
if plan is None: # if plan is not given, the default is to use current plan of the user plan = user.userplan.plan quota_dict = plan.get_quota_dict() validators = getattr(settings, 'PLANS_VALIDATORS', {}) validators = import_name(validators) errors = { 'required_to_activa...
def plan_validation(user, plan=None, on_activation=False)
Validates validator that represents quotas in a given system :param user: :param plan: :return:
3.147885
3.148485
0.99981
if quota_dict is None: quota_dict = get_user_quota(user) return quota_dict.get(self.code, self.default_quota_value)
def get_quota_value(self, user, quota_dict=None)
Returns quota value for a given user
2.960237
2.796767
1.05845
send_emails = getattr(settings, 'SEND_PLANS_EMAILS', True) if not send_emails: return site_name = getattr(settings, 'SITE_NAME', 'Please define settings.SITE_NAME') domain = getattr(settings, 'SITE_URL', None) if domain is None: try: Site = apps.get_model('sites',...
def send_template_email(recipients, title_template, body_template, context, language)
Sends e-mail using templating system
2.227509
2.187829
1.018137
return_value = {} user_language.send(sender=user, user=user, return_value=return_value) return return_value.get('language')
def get_user_language(user)
Simple helper that will fire django signal in order to get User language possibly given by other part of application. :param user: :return: string or None
4.204709
4.332342
0.970539
plan_pricings = plan.planpricing_set.order_by('-pricing__period').select_related('pricing') selected_pricing = None for plan_pricing in plan_pricings: selected_pricing = plan_pricing if plan_pricing.pricing.period <= period: break if sel...
def _calculate_day_cost(self, plan, period)
Finds most fitted plan pricing for a given period, and calculate day cost
3.203084
2.986169
1.07264
if period is None or period < 1: return None plan_old_day_cost = self._calculate_day_cost(plan_old, period) plan_new_day_cost = self._calculate_day_cost(plan_new, period) if plan_new_day_cost <= plan_old_day_cost: return self._calculate_final_price(peri...
def get_change_price(self, plan_old, plan_new, period)
Calculates total price of plan change. Returns None if no payment is required.
2.195526
2.054993
1.068386
@wraps(operator) def wrapper(self, other): if not isinstance(other, (VersionInfo, dict)): return NotImplemented return operator(self, other) return wrapper
def comparator(operator)
Wrap a VersionInfo binary op method in a type-check
3.751859
2.672415
1.403921
assert type(alpha) == float and type(beta) == float self.alpha = alpha self.beta = beta
def set_priors(self, alpha, beta)
Override default values for Dirichlet hyperparameters. alpha: hyperparameter for distribution of topics within documents. beta: hyperparameter for distribution of tokens within topics.
3.249166
2.849347
1.14032
assert sampled_topics.dtype == np.int and \ len(sampled_topics.shape) <= 2 if len(sampled_topics.shape) == 1: self.sampled_topics = \ sampled_topics.reshape(1, sampled_topics.shape[0]) else: self.sampled_topics = sampled_topics ...
def set_sampled_topics(self, sampled_topics)
Allocate sampled topics to the documents rather than estimate them. Automatically generate term-topic and document-topic matrices.
2.641459
2.432705
1.085811