code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Ensure axis specification is positive if axis < 0: axis = b.ndim + axis # Insert singleton axis into b bx = np.expand_dims(b, axis) # Calculate index of required singleton axis in a and insert it axshp = [1] * bx.ndim axshp[axis:axis + 2] = a.shape ax = a.reshape(axshp) # Calculate indexing expression required to remove singleton axis in # product idxexp = [slice(None)] * bx.ndim idxexp[axis + 1] = 0 # Compute and return product return np.sum(ax * bx, axis=axis+1, keepdims=True)[tuple(idxexp)]
def dot(a, b, axis=-2)
Compute the matrix product of `a` and the specified axes of `b`, with broadcasting over the remaining axes of `b`. This function is a generalisation of :func:`numpy.dot`, supporting sum product over an arbitrary axis instead of just over the last axis. If `a` and `b` are both 2D arrays, `dot` gives the same result as :func:`numpy.dot`. If `b` has more than 2 axes, the result is obtained as follows (where `a` has shape ``(M0, M1)`` and `b` has shape ``(N0, N1, ..., M1, Nn, ...)``): #. Reshape `a` to shape ``( 1, 1, ..., M0, M1, 1, ...)`` #. Reshape `b` to shape ``(N0, N1, ..., 1, M1, Nn, ...)`` #. Take the broadcast product and sum over the specified axis (the axis with dimension `M1` in this example) to give an array of shape ``(N0, N1, ..., M0, 1, Nn, ...)`` #. Remove the singleton axis created by the summation to give an array of shape ``(N0, N1, ..., M0, Nn, ...)`` Parameters ---------- a : array_like, 2D First component of product b : array_like, 2D or greater Second component of product axis : integer, optional (default -2) Axis of `b` over which sum is to be taken Returns ------- prod : ndarray Matrix product of `a` and specified axes of `b`, with broadcasting over the remaining axes of `b`
5.045208
4.113511
1.226497
r a = np.conj(ah) if c is None: c = solvedbi_sm_c(ah, a, rho, axis) if have_numexpr: cb = inner(c, b, axis=axis) return ne.evaluate('(b - (a * cb)) / rho') else: return (b - (a * inner(c, b, axis=axis))) / rho
def solvedbi_sm(ah, rho, b, c=None, axis=4)
r""" Solve a diagonal block linear system with a scaled identity term using the Sherman-Morrison equation. The solution is obtained by independently solving a set of linear systems of the form (see :cite:`wohlberg-2016-efficient`) .. math:: (\rho I + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} = \mathbf{b} \;\;. In this equation inner products and matrix products are taken along the specified axis of the corresponding multi-dimensional arrays; the solutions are independent over the other axes. Parameters ---------- ah : array_like Linear system component :math:`\mathbf{a}^H` rho : float Linear system parameter :math:`\rho` b : array_like Linear system component :math:`\mathbf{b}` c : array_like, optional (default None) Solution component :math:`\mathbf{c}` that may be pre-computed using :func:`solvedbi_sm_c` and cached for re-use. axis : int, optional (default 4) Axis along which to solve the linear system Returns ------- x : ndarray Linear system solution :math:`\mathbf{x}`
4.511488
4.442008
1.015642
r return ah / (inner(ah, a, axis=axis) + rho)
def solvedbi_sm_c(ah, a, rho, axis=4)
r""" Compute cached component used by :func:`solvedbi_sm`. Parameters ---------- ah : array_like Linear system component :math:`\mathbf{a}^H` a : array_like Linear system component :math:`\mathbf{a}` rho : float Linear system parameter :math:`\rho` axis : int, optional (default 4) Axis along which to solve the linear system Returns ------- c : ndarray Argument :math:`\mathbf{c}` used by :func:`solvedbi_sm`
19.065075
31.937714
0.596946
r a = np.conj(ah) if c is None: c = solvedbd_sm_c(ah, a, d, axis) if have_numexpr: cb = inner(c, b, axis=axis) return ne.evaluate('(b - (a * cb)) / d') else: return (b - (a * inner(c, b, axis=axis))) / d
def solvedbd_sm(ah, d, b, c=None, axis=4)
r""" Solve a diagonal block linear system with a diagonal term using the Sherman-Morrison equation. The solution is obtained by independently solving a set of linear systems of the form (see :cite:`wohlberg-2016-efficient`) .. math:: (\mathbf{d} + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} = \mathbf{b} \;\;. In this equation inner products and matrix products are taken along the specified axis of the corresponding multi-dimensional arrays; the solutions are independent over the other axes. Parameters ---------- ah : array_like Linear system component :math:`\mathbf{a}^H` d : array_like Linear system parameter :math:`\mathbf{d}` b : array_like Linear system component :math:`\mathbf{b}` c : array_like, optional (default None) Solution component :math:`\mathbf{c}` that may be pre-computed using :func:`solvedbd_sm_c` and cached for re-use. axis : int, optional (default 4) Axis along which to solve the linear system Returns ------- x : ndarray Linear system solution :math:`\mathbf{x}`
4.560352
4.355503
1.047032
r return (ah / d) / (inner(ah, (a / d), axis=axis) + 1.0)
def solvedbd_sm_c(ah, a, d, axis=4)
r""" Compute cached component used by :func:`solvedbd_sm`. Parameters ---------- ah : array_like Linear system component :math:`\mathbf{a}^H` a : array_like Linear system component :math:`\mathbf{a}` d : array_like Linear system parameter :math:`\mathbf{d}` axis : int, optional (default 4) Axis along which to solve the linear system Returns ------- c : ndarray Argument :math:`\mathbf{c}` used by :func:`solvedbd_sm`
13.377511
18.784956
0.71214
r if axisM < 0: axisM += ah.ndim if axisK < 0: axisK += ah.ndim K = ah.shape[axisK] a = np.conj(ah) gamma = np.zeros(a.shape, a.dtype) dltshp = list(a.shape) dltshp[axisM] = 1 delta = np.zeros(dltshp, a.dtype) slcnc = (slice(None),) * axisK alpha = np.take(a, [0], axisK) / rho beta = b / rho del b for k in range(0, K): slck = slcnc + (slice(k, k + 1),) gamma[slck] = alpha delta[slck] = 1.0 + inner(ah[slck], gamma[slck], axis=axisM) d = gamma[slck] * inner(ah[slck], beta, axis=axisM) beta[:] -= d / delta[slck] if k < K - 1: alpha[:] = np.take(a, [k + 1], axisK) / rho for l in range(0, k + 1): slcl = slcnc + (slice(l, l + 1),) d = gamma[slcl] * inner(ah[slcl], alpha, axis=axisM) alpha[:] -= d / delta[slcl] return beta
def solvemdbi_ism(ah, rho, b, axisM, axisK)
r""" Solve a multiple diagonal block linear system with a scaled identity term by iterated application of the Sherman-Morrison equation. The computation is performed in a way that avoids explictly constructing the inverse operator, leading to an :math:`O(K^2)` time cost. The solution is obtained by independently solving a set of linear systems of the form (see :cite:`wohlberg-2016-efficient`) .. math:: (\rho I + \mathbf{a}_0 \mathbf{a}_0^H + \mathbf{a}_1 \mathbf{a}_1^H + \; \ldots \; + \mathbf{a}_{K-1} \mathbf{a}_{K-1}^H) \; \mathbf{x} = \mathbf{b} where each :math:`\mathbf{a}_k` is an :math:`M`-vector. The sums, inner products, and matrix products in this equation are taken along the M and K axes of the corresponding multi-dimensional arrays; the solutions are independent over the other axes. Parameters ---------- ah : array_like Linear system component :math:`\mathbf{a}^H` rho : float Linear system parameter :math:`\rho` b : array_like Linear system component :math:`\mathbf{b}` axisM : int Axis in input corresponding to index m in linear system axisK : int Axis in input corresponding to index k in linear system Returns ------- x : ndarray Linear system solution :math:`\mathbf{x}`
2.717565
2.761887
0.983952
r axisM = dimN + 2 slcnc = (slice(None),) * axisK M = ah.shape[axisM] K = ah.shape[axisK] a = np.conj(ah) Ainv = np.ones(ah.shape[0:dimN] + (1,)*4) * \ np.reshape(np.eye(M, M) / rho, (1,)*(dimN + 2) + (M, M)) for k in range(0, K): slck = slcnc + (slice(k, k + 1),) + (slice(None), np.newaxis,) Aia = inner(Ainv, np.swapaxes(a[slck], dimN + 2, dimN + 3), axis=dimN + 3) ahAia = 1.0 + inner(ah[slck], Aia, axis=dimN + 2) ahAi = inner(ah[slck], Ainv, axis=dimN + 2) AiaahAi = Aia * ahAi Ainv = Ainv - AiaahAi / ahAia return np.sum(Ainv * np.swapaxes(b[(slice(None),) * b.ndim + (np.newaxis,)], dimN + 2, dimN + 3), dimN + 3)
def solvemdbi_rsm(ah, rho, b, axisK, dimN=2)
r""" Solve a multiple diagonal block linear system with a scaled identity term by repeated application of the Sherman-Morrison equation. The computation is performed by explictly constructing the inverse operator, leading to an :math:`O(K)` time cost and :math:`O(M^2)` memory cost, where :math:`M` is the dimension of the axis over which inner products are taken. The solution is obtained by independently solving a set of linear systems of the form (see :cite:`wohlberg-2016-efficient`) .. math:: (\rho I + \mathbf{a}_0 \mathbf{a}_0^H + \mathbf{a}_1 \mathbf{a}_1^H + \; \ldots \; + \mathbf{a}_{K-1} \mathbf{a}_{K-1}^H) \; \mathbf{x} = \mathbf{b} where each :math:`\mathbf{a}_k` is an :math:`M`-vector. The sums, inner products, and matrix products in this equation are taken along the M and K axes of the corresponding multi-dimensional arrays; the solutions are independent over the other axes. Parameters ---------- ah : array_like Linear system component :math:`\mathbf{a}^H` rho : float Linear system parameter :math:`\rho` b : array_like Linear system component :math:`\mathbf{b}` axisK : int Axis in input corresponding to index k in linear system dimN : int, optional (default 2) Number of spatial dimensions arranged as leading axes in input array. Axis M is taken to be at dimN+2. Returns ------- x : ndarray Linear system solution :math:`\mathbf{x}`
3.608816
3.525124
1.023742
r a = np.conj(ah) if isn is not None: isn = isn.ravel() Aop = lambda x: inner(ah, x, axis=axisM) AHop = lambda x: inner(a, x, axis=axisK) AHAop = lambda x: AHop(Aop(x)) vAHAoprI = lambda x: AHAop(x.reshape(b.shape)).ravel() + rho * x.ravel() lop = LinearOperator((b.size, b.size), matvec=vAHAoprI, dtype=b.dtype) vx, cgit = _cg_wrapper(lop, b.ravel(), isn, tol, mit) return vx.reshape(b.shape), cgit
def solvemdbi_cg(ah, rho, b, axisM, axisK, tol=1e-5, mit=1000, isn=None)
r""" Solve a multiple diagonal block linear system with a scaled identity term using Conjugate Gradient (CG) via :func:`scipy.sparse.linalg.cg`. The solution is obtained by independently solving a set of linear systems of the form (see :cite:`wohlberg-2016-efficient`) .. math:: (\rho I + \mathbf{a}_0 \mathbf{a}_0^H + \mathbf{a}_1 \mathbf{a}_1^H + \; \ldots \; + \mathbf{a}_{K-1} \mathbf{a}_{K-1}^H) \; \mathbf{x} = \mathbf{b} where each :math:`\mathbf{a}_k` is an :math:`M`-vector. The inner products and matrix products in this equation are taken along the M and K axes of the corresponding multi-dimensional arrays; the solutions are independent over the other axes. Parameters ---------- ah : array_like Linear system component :math:`\mathbf{a}^H` rho : float Parameter rho b : array_like Linear system component :math:`\mathbf{b}` axisM : int Axis in input corresponding to index m in linear system axisK : int Axis in input corresponding to index k in linear system tol : float CG tolerance mit : int CG maximum iterations isn : array_like CG initial solution Returns ------- x : ndarray Linear system solution :math:`\mathbf{x}` cgit : int Number of CG iterations
4.917366
4.449656
1.105112
r N, M = A.shape # If N < M it is cheaper to factorise A*A^T + rho*I and then use the # matrix inversion lemma to compute the inverse of A^T*A + rho*I if N >= M: lu, piv = linalg.lu_factor(A.T.dot(A) + rho * np.identity(M, dtype=A.dtype), check_finite=check_finite) else: lu, piv = linalg.lu_factor(A.dot(A.T) + rho * np.identity(N, dtype=A.dtype), check_finite=check_finite) return lu, piv
def lu_factor(A, rho, check_finite=True)
r""" Compute LU factorisation of either :math:`A^T A + \rho I` or :math:`A A^T + \rho I`, depending on which matrix is smaller. Parameters ---------- A : array_like Array :math:`A` rho : float Scalar :math:`\rho` check_finite : bool, optional (default False) Flag indicating whether the input array should be checked for Inf and NaN values Returns ------- lu : ndarray Matrix containing U in its upper triangle, and L in its lower triangle, as returned by :func:`scipy.linalg.lu_factor` piv : ndarray Pivot indices representing the permutation matrix P, as returned by :func:`scipy.linalg.lu_factor`
2.891607
2.764239
1.046077
r N, M = A.shape if N >= M: x = linalg.lu_solve((lu, piv), b, check_finite=check_finite) else: x = (b - A.T.dot(linalg.lu_solve((lu, piv), A.dot(b), 1, check_finite=check_finite))) / rho return x
def lu_solve_ATAI(A, rho, b, lu, piv, check_finite=True)
r""" Solve the linear system :math:`(A^T A + \rho I)\mathbf{x} = \mathbf{b}` or :math:`(A^T A + \rho I)X = B` using :func:`scipy.linalg.lu_solve`. Parameters ---------- A : array_like Matrix :math:`A` rho : float Scalar :math:`\rho` b : array_like Vector :math:`\mathbf{b}` or matrix :math:`B` lu : array_like Matrix containing U in its upper triangle, and L in its lower triangle, as returned by :func:`scipy.linalg.lu_factor` piv : array_like Pivot indices representing the permutation matrix P, as returned by :func:`scipy.linalg.lu_factor` check_finite : bool, optional (default False) Flag indicating whether the input array should be checked for Inf and NaN values Returns ------- x : ndarray Solution to the linear system
3.312725
3.492816
0.948439
r N, M = A.shape # If N < M it is cheaper to factorise A*A^T + rho*I and then use the # matrix inversion lemma to compute the inverse of A^T*A + rho*I if N >= M: c, lwr = linalg.cho_factor( A.T.dot(A) + rho * np.identity(M, dtype=A.dtype), lower=lower, check_finite=check_finite) else: c, lwr = linalg.cho_factor( A.dot(A.T) + rho * np.identity(N, dtype=A.dtype), lower=lower, check_finite=check_finite) return c, lwr
def cho_factor(A, rho, lower=False, check_finite=True)
r""" Compute Cholesky factorisation of either :math:`A^T A + \rho I` or :math:`A A^T + \rho I`, depending on which matrix is smaller. Parameters ---------- A : array_like Array :math:`A` rho : float Scalar :math:`\rho` lower : bool, optional (default False) Flag indicating whether lower or upper triangular factors are computed check_finite : bool, optional (default False) Flag indicating whether the input array should be checked for Inf and NaN values Returns ------- c : ndarray Matrix containing lower or upper triangular Cholesky factor, as returned by :func:`scipy.linalg.cho_factor` lwr : bool Flag indicating whether the factor is lower or upper triangular
2.967652
2.745861
1.080773
r N, M = A.shape if N >= M: x = linalg.cho_solve((c, lwr), b, check_finite=check_finite) else: x = (b - A.T.dot(linalg.cho_solve((c, lwr), A.dot(b), check_finite=check_finite))) / rho return x
def cho_solve_ATAI(A, rho, b, c, lwr, check_finite=True)
r""" Solve the linear system :math:`(A^T A + \rho I)\mathbf{x} = \mathbf{b}` or :math:`(A^T A + \rho I)X = B` using :func:`scipy.linalg.cho_solve`. Parameters ---------- A : array_like Matrix :math:`A` rho : float Scalar :math:`\rho` b : array_like Vector :math:`\mathbf{b}` or matrix :math:`B` c : array_like Matrix containing lower or upper triangular Cholesky factor, as returned by :func:`scipy.linalg.cho_factor` lwr : bool Flag indicating whether the factor is lower or upper triangular Returns ------- x : ndarray Solution to the linear system
3.211295
3.192982
1.005735
xpd = ((0, 0),)*ax + (pd,) + ((0, 0),)*(x.ndim-ax-1) return np.pad(x, xpd, 'constant')
def zpad(x, pd, ax)
Zero-pad array `x` with `pd = (leading, trailing)` zeros on axis `ax`. Parameters ---------- x : array_like Array to be padded pd : tuple Sequence of two ints (leading,trailing) specifying number of zeros for padding ax : int Axis to be padded Returns ------- xp : array_like Padded array
4.40975
4.905936
0.89886
slc = (slice(None),)*ax + (slice(-1, None),) xg = np.roll(x, -1, axis=ax) - x xg[slc] = 0.0 return xg
def Gax(x, ax)
Compute gradient of `x` along axis `ax`. Parameters ---------- x : array_like Input array ax : int Axis on which gradient is to be computed Returns ------- xg : ndarray Output array
4.137503
3.111021
1.32995
slc0 = (slice(None),) * ax xg = np.roll(x, 1, axis=ax) - x xg[slc0 + (slice(0, 1),)] = -x[slc0 + (slice(0, 1),)] xg[slc0 + (slice(-1, None),)] = x[slc0 + (slice(-2, -1),)] return xg
def GTax(x, ax)
Compute transpose of gradient of `x` along axis `ax`. Parameters ---------- x : array_like Input array ax : int Axis on which gradient transpose is to be computed Returns ------- xg : ndarray Output array
3.180163
2.698149
1.178646
r if dtype is None: dtype = np.float32 g = np.zeros([2 if k in axes else 1 for k in range(ndim)] + [len(axes),], dtype) for k in axes: g[(0,) * k + (slice(None),) + (0,) * (g.ndim - 2 - k) + (k,)] = \ np.array([1, -1]) Gf = rfftn(g, axshp, axes=axes) GHGf = np.sum(np.conj(Gf) * Gf, axis=-1).real return Gf, GHGf
def GradientFilters(ndim, axes, axshp, dtype=None)
r""" Construct a set of filters for computing gradients in the frequency domain. Parameters ---------- ndim : integer Total number of dimensions in array in which gradients are to be computed axes : tuple of integers Axes on which gradients are to be computed axshp : tuple of integers Shape of axes on which gradients are to be computed dtype : dtype Data type of output arrays Returns ------- Gf : ndarray Frequency domain gradient operators :math:`\hat{G}_i` GHGf : ndarray Sum of products :math:`\sum_i \hat{G}_i^H \hat{G}_i`
4.250098
3.572716
1.189599
# See https://stackoverflow.com/a/37977222 return np.divide(x, y, out=np.zeros_like(x), where=(y != 0))
def zdivide(x, y)
Return `x`/`y`, with 0 instead of NaN where `y` is 0. Parameters ---------- x : array_like Numerator y : array_like Denominator Returns ------- z : ndarray Quotient `x`/`y`
3.656089
4.316605
0.846983
r d = np.sqrt(np.sum((b - s)**2, axis=axes, keepdims=True)) p = zdivide(b - s, d) return np.asarray((d <= r) * b + (d > r) * (s + r*p), b.dtype)
def proj_l2ball(b, s, r, axes=None)
r""" Project :math:`\mathbf{b}` into the :math:`\ell_2` ball of radius :math:`r` about :math:`\mathbf{s}`, i.e. :math:`\{ \mathbf{x} : \|\mathbf{x} - \mathbf{s} \|_2 \leq r \}`. Note that ``proj_l2ball(b, s, r)`` is equivalent to :func:`.prox.proj_l2` ``(b - s, r) + s``. Parameters ---------- b : array_like Vector :math:`\mathbf{b}` to be projected s : array_like Centre of :math:`\ell_2` ball :math:`\mathbf{s}` r : float Radius of ball axes : sequence of ints, optional (default all axes) Axes over which to compute :math:`\ell_2` norms Returns ------- x : ndarray Projection of :math:`\mathbf{b}` into ball
5.355899
6.231267
0.85952
r dtype = np.float32 if u.dtype == np.float16 else u.dtype up = np.asarray(u, dtype=dtype) if fn is None: return up else: v = fn(up, *args, **kwargs) if isinstance(v, tuple): vp = tuple([np.asarray(vk, dtype=u.dtype) for vk in v]) else: vp = np.asarray(v, dtype=u.dtype) return vp
def promote16(u, fn=None, *args, **kwargs)
r""" Utility function for use with functions that do not support arrays of dtype ``np.float16``. This function has two distinct modes of operation. If called with only the `u` parameter specified, the returned value is either `u` itself if `u` is not of dtype ``np.float16``, or `u` promoted to ``np.float32`` dtype if it is. If the function parameter `fn` is specified then `u` is conditionally promoted as described above, passed as the first argument to function `fn`, and the returned values are converted back to dtype ``np.float16`` if `u` is of that dtype. Note that if parameter `fn` is specified, it may not be be specified as a keyword argument if it is followed by any non-keyword arguments. Parameters ---------- u : array_like Array to be promoted to np.float32 if it is of dtype ``np.float16`` fn : function or None, optional (default None) Function to be called with promoted `u` as first parameter and \*args and \*\*kwargs as additional parameters *args Variable length list of arguments for function `fn` **kwargs Keyword arguments for function `fn` Returns ------- up : ndarray Conditionally dtype-promoted version of `u` if `fn` is None, or value(s) returned by `fn`, converted to the same dtype as `u`, if `fn` is a function
2.785697
2.418876
1.151649
if u.ndim >= n: return u else: return u.reshape(u.shape + (1,)*(n-u.ndim))
def atleast_nd(n, u)
If the input array has fewer than n dimensions, append singleton dimensions so that it is n dimensional. Note that the interface differs substantially from that of :func:`numpy.atleast_3d` etc. Parameters ---------- n : int Minimum number of required dimensions u : array_like Input array Returns ------- v : ndarray Output array with at least n dimensions
3.144657
3.113307
1.010069
# Convert negative axis to positive if axis < 0: axis = u.ndim + axis # Construct axis selection slice slct0 = (slice(None),) * axis return [u[slct0 + (k,)] for k in range(u.shape[axis])]
def split(u, axis=0)
Split an array into a list of arrays on the specified axis. The length of the list is the shape of the array on the specified axis, and the corresponding axis is removed from each entry in the list. This function does not have the same behaviour as :func:`numpy.split`. Parameters ---------- u : array_like Input array axis : int, optional (default 0) Axis on which to split the input array Returns ------- v : list of ndarray List of arrays
4.818234
5.636601
0.854812
r, c = A[0].shape B = np.zeros((len(A) * r, len(A) * c), dtype=A[0].dtype) for k in range(len(A)): for l in range(len(A)): kl = np.mod(k + l, len(A)) B[r*kl:r*(kl + 1), c*k:c*(k + 1)] = A[l] return B
def blockcirculant(A)
Construct a block circulant matrix from a tuple of arrays. This is a block-matrix variant of :func:`scipy.linalg.circulant`. Parameters ---------- A : tuple of array_like Tuple of arrays corresponding to the first block column of the output block matrix Returns ------- B : ndarray Output array
2.547462
2.37328
1.073393
r xfs = xf.shape return (np.linalg.norm(xf)**2) / np.prod(np.array([xfs[k] for k in axis]))
def fl2norm2(xf, axis=(0, 1))
r""" Compute the squared :math:`\ell_2` norm in the DFT domain, taking into account the unnormalised DFT scaling, i.e. given the DFT of a multi-dimensional array computed via :func:`fftn`, return the squared :math:`\ell_2` norm of the original array. Parameters ---------- xf : array_like Input array axis : sequence of ints, optional (default (0,1)) Axes on which the input is in the frequency domain Returns ------- x : float :math:`\|\mathbf{x}\|_2^2` where the input array is the result of applying :func:`fftn` to the specified axes of multi-dimensional array :math:`\mathbf{x}`
6.920177
7.162596
0.966155
r scl = 1.0 / np.prod(np.array([xs[k] for k in axis])) slc0 = (slice(None),) * axis[-1] nrm0 = np.linalg.norm(xf[slc0 + (0,)]) idx1 = (xs[axis[-1]] + 1) // 2 nrm1 = np.linalg.norm(xf[slc0 + (slice(1, idx1),)]) if xs[axis[-1]] % 2 == 0: nrm2 = np.linalg.norm(xf[slc0 + (slice(-1, None),)]) else: nrm2 = 0.0 return scl*(nrm0**2 + 2.0*nrm1**2 + nrm2**2)
def rfl2norm2(xf, xs, axis=(0, 1))
r""" Compute the squared :math:`\ell_2` norm in the DFT domain, taking into account the unnormalised DFT scaling, i.e. given the DFT of a multi-dimensional array computed via :func:`rfftn`, return the squared :math:`\ell_2` norm of the original array. Parameters ---------- xf : array_like Input array xs : sequence of ints Shape of original array to which :func:`rfftn` was applied to obtain the input array axis : sequence of ints, optional (default (0,1)) Axes on which the input is in the frequency domain Returns ------- x : float :math:`\|\mathbf{x}\|_2^2` where the input array is the result of applying :func:`rfftn` to the specified axes of multi-dimensional array :math:`\mathbf{x}`
2.711129
2.660058
1.019199
r nrm = np.linalg.norm(b.ravel()) if nrm == 0.0: return 1.0 else: return np.linalg.norm((ax - b).ravel()) / nrm
def rrs(ax, b)
r""" Compute relative residual :math:`\|\mathbf{b} - A \mathbf{x}\|_2 / \|\mathbf{b}\|_2` of the solution to a linear equation :math:`A \mathbf{x} = \mathbf{b}`. Returns 1.0 if :math:`\mathbf{b} = 0`. Parameters ---------- ax : array_like Linear component :math:`A \mathbf{x}` of equation b : array_like Constant component :math:`\mathbf{b}` of equation Returns ------- x : float Relative residual
4.191793
3.465128
1.209708
if self.opt['Y0'] is None: return np.zeros(ushape, dtype=self.dtype) else: # If initial Y is non-zero, initial U is chosen so that # the relevant dual optimality criterion (see (3.10) in # boyd-2010-distributed) is satisfied. Yss = np.sqrt(np.sum(self.Y**2, axis=self.S.ndim, keepdims=True)) return (self.lmbda/self.rho)*sl.zdivide(self.Y, Yss)
def uinit(self, ushape)
Return initialiser for working variable U.
8.34551
7.805245
1.069218
r ngsit = 0 gsrrs = np.inf while gsrrs > self.opt['GSTol'] and ngsit < self.opt['MaxGSIter']: self.X = self.GaussSeidelStep(self.S, self.X, self.cnst_AT(self.Y-self.U), self.rho, self.lcw, self.Wdf2) gsrrs = sl.rrs( self.rho*self.cnst_AT(self.cnst_A(self.X)) + self.Wdf2*self.X, self.Wdf2*self.S + self.rho*self.cnst_AT(self.Y - self.U)) ngsit += 1 self.xs = (ngsit, gsrrs)
def xstep(self)
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}`.
7.138218
6.805196
1.048936
r self.Y = np.asarray(sp.prox_l2( self.AX + self.U, (self.lmbda/self.rho)*self.Wtvna, axis=self.saxes), dtype=self.dtype)
def ystep(self)
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.
19.687817
15.559288
1.265342
r dfd = 0.5*(np.linalg.norm(self.Wdf * (self.X - self.S))**2) reg = np.sum(self.Wtv * np.sqrt(np.sum(self.obfn_gvar()**2, axis=self.saxes))) obj = dfd + self.lmbda*reg return (obj, dfd, reg)
def eval_objfn(self)
r"""Compute components of objective function as well as total contribution to objective function. Data fidelity term is :math:`(1/2) \| \mathbf{x} - \mathbf{s} \|_2^2` and regularisation term is :math:`\| W_{\mathrm{tv}} \sqrt{(G_r \mathbf{x})^2 + (G_c \mathbf{x})^2}\|_1`.
8.130146
6.037546
1.346598
r return np.sum(np.concatenate( [sl.GTax(X[..., ax], ax)[..., np.newaxis] for ax in self.axes], axis=X.ndim-1), axis=X.ndim-1)
def cnst_AT(self, X)
r"""Compute :math:`A^T \mathbf{x}` where :math:`A \mathbf{x}` is a component of ADMM problem constraint. In this case :math:`A^T \mathbf{x} = (G_r^T \;\; G_c^T) \mathbf{x}`.
10.511413
10.867236
0.967257
r return np.zeros(self.S.shape + (len(self.axes),), self.dtype)
def cnst_c(self)
r"""Compute constant component :math:`\mathbf{c}` of ADMM problem constraint. In this case :math:`\mathbf{c} = \mathbf{0}`.
18.988905
14.925332
1.27226
sz = [1,] * self.S.ndim for ax in self.axes: sz[ax] = self.S.shape[ax] lcw = 2*len(self.axes)*np.ones(sz, dtype=self.dtype) for ax in self.axes: lcw[(slice(None),)*ax + ([0, -1],)] -= 1.0 return lcw
def LaplaceCentreWeight(self)
Centre weighting matrix for TV Laplacian.
4.663939
4.073911
1.144831
Xss = np.zeros_like(S, dtype=self.dtype) for ax in self.axes: Xss += sl.zpad(X[(slice(None),)*ax + (slice(0, -1),)], (1, 0), ax) Xss += sl.zpad(X[(slice(None),)*ax + (slice(1, None),)], (0, 1), ax) return (rho*(Xss + ATYU) + W2*S) / (W2 + rho*lcw)
def GaussSeidelStep(self, S, X, ATYU, rho, lcw, W2)
Gauss-Seidel step for linear system in TV problem.
4.048937
4.051074
0.999473
r b = self.AHSf + self.rho*np.sum( np.conj(self.Gf)*sl.rfftn(self.Y-self.U, axes=self.axes), axis=self.Y.ndim-1) self.Xf = b / (self.AHAf + self.rho*self.GHGf) self.X = sl.irfftn(self.Xf, self.axsz, axes=self.axes) if self.opt['LinSolveCheck']: ax = (self.AHAf + self.rho*self.GHGf)*self.Xf self.xrrs = sl.rrs(ax, b) else: self.xrrs = None
def xstep(self)
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}`.
7.283704
6.95195
1.047721
r Ef = self.Af * self.Xf - self.Sf dfd = sl.rfl2norm2(Ef, self.S.shape, axis=self.axes) / 2.0 reg = np.sum(self.Wtv * np.sqrt(np.sum(self.obfn_gvar()**2, axis=self.saxes))) obj = dfd + self.lmbda*reg return (obj, dfd, reg)
def eval_objfn(self)
r"""Compute components of objective function as well as total contribution to objective function. Data fidelity term is :math:`(1/2) \| H \mathbf{x} - \mathbf{s} \|_2^2` and regularisation term is :math:`\| W_{\mathrm{tv}} \sqrt{(G_r \mathbf{x})^2 + (G_c \mathbf{x})^2}\|_1`.
10.688695
8.389261
1.274093
# Open status display fmtstr, nsep = self.display_start() # Start solve timer self.timer.start(['solve', 'solve_wo_func', 'solve_wo_rsdl']) # Main optimisation iterations for self.k in range(self.k, self.k + self.opt['MaxMainIter']): # Update record of Y from previous iteration self.Yprev = self.Y.copy() # X update self.xstep() # Implement relaxation if RelaxParam != 1.0 self.relax_AX() # Y update self.ystep() # U update self.ustep() # Compute residuals and stopping thresholds self.timer.stop('solve_wo_rsdl') if self.opt['AutoRho', 'Enabled'] or not self.opt['FastSolve']: r, s, epri, edua = self.compute_residuals() self.timer.start('solve_wo_rsdl') # Compute and record other iteration statistics and # display iteration stats if Verbose option enabled self.timer.stop(['solve_wo_func', 'solve_wo_rsdl']) if not self.opt['FastSolve']: itst = self.iteration_stats(self.k, r, s, epri, edua) self.itstat.append(itst) self.display_status(fmtstr, itst) self.timer.start(['solve_wo_func', 'solve_wo_rsdl']) # Automatic rho adjustment self.timer.stop('solve_wo_rsdl') if self.opt['AutoRho', 'Enabled'] or not self.opt['FastSolve']: self.update_rho(self.k, r, s) self.timer.start('solve_wo_rsdl') # Call callback function if defined if self.opt['Callback'] is not None: if self.opt['Callback'](self): break # Stop if residual-based stopping tolerances reached if self.opt['AutoRho', 'Enabled'] or not self.opt['FastSolve']: if r < epri and s < edua: break # Increment iteration count self.k += 1 # Record solve time self.timer.stop(['solve', 'solve_wo_func', 'solve_wo_rsdl']) # Print final separator string if Verbose option enabled self.display_end(nsep) return self.getmin()
def solve(self)
Start (or re-start) optimisation. This method implements the framework for the iterations of an ADMM algorithm. There is sufficient flexibility in overriding the component methods that it calls that it is usually not necessary to override this method in derived clases. If option ``Verbose`` is ``True``, the progress of the optimisation is displayed at every iteration. At termination of this method, attribute :attr:`itstat` is a list of tuples representing statistics of each iteration, unless option ``FastSolve`` is ``True`` and option ``Verbose`` is ``False``. Attribute :attr:`timer` is an instance of :class:`.util.Timer` that provides the following labelled timers: ``init``: Time taken for object initialisation by :meth:`__init__` ``solve``: Total time taken by call(s) to :meth:`solve` ``solve_wo_func``: Total time taken by call(s) to :meth:`solve`, excluding time taken to compute functional value and related iteration statistics ``solve_wo_rsdl`` : Total time taken by call(s) to :meth:`solve`, excluding time taken to compute functional value and related iteration statistics as well as time take to compute residuals and implemented ``AutoRho`` mechanism
4.171473
3.362017
1.240765
warnings.warn("admm.ADMM.runtime attribute has been replaced by " "an upgraded timer class: please see the documentation " "for admm.ADMM.solve method and util.Timer class", PendingDeprecationWarning) return self.timer.elapsed('init') + self.timer.elapsed('solve')
def runtime(self)
Transitional property providing access to the new timer mechanism. This will be removed in the future.
11.985298
10.142421
1.1817
self.U += self.rsdl_r(self.AX, self.Y)
def ustep(self)
Dual variable update.
42.3433
24.865105
1.702921
if self.opt['AutoRho', 'StdResiduals']: r = np.linalg.norm(self.rsdl_r(self.AXnr, self.Y)) s = np.linalg.norm(self.rsdl_s(self.Yprev, self.Y)) epri = np.sqrt(self.Nc) * self.opt['AbsStopTol'] + \ self.rsdl_rn(self.AXnr, self.Y) * self.opt['RelStopTol'] edua = np.sqrt(self.Nx) * self.opt['AbsStopTol'] + \ self.rsdl_sn(self.U) * self.opt['RelStopTol'] else: rn = self.rsdl_rn(self.AXnr, self.Y) if rn == 0.0: rn = 1.0 sn = self.rsdl_sn(self.U) if sn == 0.0: sn = 1.0 r = np.linalg.norm(self.rsdl_r(self.AXnr, self.Y)) / rn s = np.linalg.norm(self.rsdl_s(self.Yprev, self.Y)) / sn epri = np.sqrt(self.Nc) * self.opt['AbsStopTol'] / rn + \ self.opt['RelStopTol'] edua = np.sqrt(self.Nx) * self.opt['AbsStopTol'] / sn + \ self.opt['RelStopTol'] return r, s, epri, edua
def compute_residuals(self)
Compute residuals and stopping thresholds.
2.527566
2.448122
1.032451
hdrmap = {'Itn': 'Iter'} hdrmap.update(cls.hdrval_objfun) hdrmap.update({'r': 'PrimalRsdl', 's': 'DualRsdl', u('ρ'): 'Rho'}) return hdrmap
def hdrval(cls)
Construct dictionary mapping display column title to IterationStats entries.
12.135178
10.390932
1.167862
tk = self.timer.elapsed(self.opt['IterTimer']) tpl = (k,) + self.eval_objfn() + (r, s, epri, edua, self.rho) + \ self.itstat_extra() + (tk,) return type(self).IterationStats(*tpl)
def iteration_stats(self, k, r, s, epri, edua)
Construct iteration stats record tuple.
10.845898
9.256726
1.171677
if self.opt['AutoRho', 'Enabled']: tau = self.rho_tau mu = self.rho_mu xi = self.rho_xi if k != 0 and np.mod(k + 1, self.opt['AutoRho', 'Period']) == 0: if self.opt['AutoRho', 'AutoScaling']: if s == 0.0 or r == 0.0: rhomlt = tau else: rhomlt = np.sqrt(r / (s * xi) if r > s * xi else (s * xi) / r) if rhomlt > tau: rhomlt = tau else: rhomlt = tau rsf = 1.0 if r > xi * mu * s: rsf = rhomlt elif s > (mu / xi) * r: rsf = 1.0 / rhomlt self.rho *= self.dtype.type(rsf) self.U /= rsf if rsf != 1.0: self.rhochange()
def update_rho(self, k, r, s)
Automatic rho adjustment.
4.101105
3.938606
1.041258
if self.opt['Verbose']: # If AutoRho option enabled rho is included in iteration status if self.opt['AutoRho', 'Enabled']: hdrtxt = type(self).hdrtxt() else: hdrtxt = type(self).hdrtxt()[0:-1] # Call utility function to construct status display formatting hdrstr, fmtstr, nsep = common.solve_status_str( hdrtxt, fwdth0=type(self).fwiter, fprec=type(self).fpothr) # Print header and separator strings if self.opt['StatusHeader']: print(hdrstr) print("-" * nsep) else: fmtstr, nsep = '', 0 return fmtstr, nsep
def display_start(self)
Set up status display if option selected. NB: this method assumes that the first entry is the iteration count and the last is the rho value.
11.446416
9.113526
1.255981
if self.opt['Verbose']: hdrtxt = type(self).hdrtxt() hdrval = type(self).hdrval() itdsp = tuple([getattr(itst, hdrval[col]) for col in hdrtxt]) if not self.opt['AutoRho', 'Enabled']: itdsp = itdsp[0:-1] print(fmtstr % itdsp)
def display_status(self, fmtstr, itst)
Display current iteration status as selection of fields from iteration stats tuple.
8.225282
7.019906
1.171708
# Avoid calling cnst_c() more than once in case it is expensive # (e.g. due to allocation of a large block of memory) if not hasattr(self, '_cnst_c'): self._cnst_c = self.cnst_c() return AX + self.cnst_B(Y) - self._cnst_c
def rsdl_r(self, AX, Y)
Compute primal residual vector. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden.
6.248271
4.110441
1.520098
# Avoid computing the norm of the value returned by cnst_c() # more than once if not hasattr(self, '_nrm_cnst_c'): self._nrm_cnst_c = np.linalg.norm(self.cnst_c()) return max((np.linalg.norm(AX), np.linalg.norm(self.cnst_B(Y)), self._nrm_cnst_c))
def rsdl_rn(self, AX, Y)
Compute primal residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden.
4.669312
3.473482
1.344274
return self.rho * np.linalg.norm(self.cnst_AT(U))
def rsdl_sn(self, U)
Compute dual residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden.
19.099251
7.039924
2.712991
if self.opt['ReturnVar'] == 'X': return self.var_x() elif self.opt['ReturnVar'] == 'Y0': return self.var_y0() elif self.opt['ReturnVar'] == 'Y1': return self.var_y1() else: raise ValueError(self.opt['ReturnVar'] + ' is not a valid value' 'for option ReturnVar')
def getmin(self)
Get minimiser after optimisation.
3.284064
2.885988
1.137934
r return Y[(slice(None),)*self.blkaxis + (slice(0, self.blkidx),)]
def block_sep0(self, Y)
r"""Separate variable into component corresponding to :math:`\mathbf{y}_0` in :math:`\mathbf{y}\;\;`.
21.566307
21.383089
1.008568
r return Y[(slice(None),)*self.blkaxis + (slice(self.blkidx, None),)]
def block_sep1(self, Y)
r"""Separate variable into component corresponding to :math:`\mathbf{y}_1` in :math:`\mathbf{y}\;\;`.
21.445894
21.124115
1.015233
r return np.concatenate((Y0, Y1), axis=self.blkaxis)
def block_cat(self, Y0, Y1)
r"""Concatenate components corresponding to :math:`\mathbf{y}_0` and :math:`\mathbf{y}_1` to form :math:`\mathbf{y}\;\;`.
13.925213
15.602424
0.892503
self.AXnr = self.cnst_A(self.X) if self.rlx == 1.0: self.AX = self.AXnr else: if not hasattr(self, '_cnst_c0'): self._cnst_c0 = self.cnst_c0() if not hasattr(self, '_cnst_c1'): self._cnst_c1 = self.cnst_c1() alpha = self.rlx self.AX = alpha*self.AXnr + (1 - alpha)*self.block_cat( self.var_y0() + self._cnst_c0, self.var_y1() + self._cnst_c1)
def relax_AX(self)
Implement relaxation if option ``RelaxParam`` != 1.0.
3.432185
3.256296
1.054015
return self.var_y0() if self.opt['AuxVarObj'] else \ self.cnst_A0(self.X) - self.cnst_c0()
def obfn_g0var(self)
Variable to be evaluated in computing :meth:`ADMMTwoBlockCnstrnt.obfn_g0`, depending on the ``AuxVarObj`` option value.
19.50518
9.153038
2.131006
return self.var_y1() if self.opt['AuxVarObj'] else \ self.cnst_A1(self.X) - self.cnst_c1()
def obfn_g1var(self)
Variable to be evaluated in computing :meth:`ADMMTwoBlockCnstrnt.obfn_g1`, depending on the ``AuxVarObj`` option value.
19.827831
8.97306
2.209707
r return self.obfn_g0(self.obfn_g0var()) + \ self.obfn_g1(self.obfn_g1var())
def obfn_g(self, Y)
r"""Compute :math:`g(\mathbf{y}) = g_0(\mathbf{y}_0) + g_1(\mathbf{y}_1)` component of ADMM objective function.
6.574169
5.586282
1.176842
fval = self.obfn_f(self.obfn_fvar()) g0val = self.obfn_g0(self.obfn_g0var()) g1val = self.obfn_g1(self.obfn_g1var()) obj = fval + g0val + g1val return (obj, fval, g0val, g1val)
def eval_objfn(self)
Compute components of objective function as well as total contribution to objective function.
2.89551
2.6038
1.112033
r return self.block_cat(self.cnst_A0(X), self.cnst_A1(X))
def cnst_A(self, X)
r"""Compute :math:`A \mathbf{x}` component of ADMM problem constraint.
9.749379
8.281299
1.177277
r return self.cnst_A0T(self.block_sep0(Y)) + \ self.cnst_A1T(self.block_sep1(Y))
def cnst_AT(self, Y)
r"""Compute :math:`A^T \mathbf{y}` where .. math:: A^T \mathbf{y} = \left( \begin{array}{cc} A_0^T & A_1^T \end{array} \right) \left( \begin{array}{c} \mathbf{y}_0 \\ \mathbf{y}_1 \end{array} \right) = A_0^T \mathbf{y}_0 + A_1^T \mathbf{y}_1 \;\;.
8.280594
6.190954
1.337531
if not hasattr(self, '_cnst_c0'): self._cnst_c0 = self.cnst_c0() if not hasattr(self, '_cnst_c1'): self._cnst_c1 = self.cnst_c1() return AX - self.block_cat(self.var_y0() + self._cnst_c0, self.var_y1() + self._cnst_c1)
def rsdl_r(self, AX, Y)
Compute primal residual vector. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_c0` and :meth:`cnst_c1` are not overridden.
3.342377
2.496702
1.338717
return self.rho * self.cnst_AT(Yprev - Y)
def rsdl_s(self, Yprev, Y)
Compute dual residual vector. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden.
27.06551
9.005884
3.005314
if not hasattr(self, '_cnst_nrm_c'): self._cnst_nrm_c = np.sqrt(np.linalg.norm(self.cnst_c0())**2 + np.linalg.norm(self.cnst_c1())**2) return max((np.linalg.norm(AX), np.linalg.norm(Y), self._cnst_nrm_c))
def rsdl_rn(self, AX, Y)
Compute primal residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden.
3.33026
2.926719
1.137882
r rho = self.Nb * self.rho mAXU = np.mean(self.AX + self.U, axis=-1) self.Y[:] = self.prox_g(mAXU, rho)
def ystep(self)
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.
19.320677
16.494474
1.171342
self.AXnr = self.X if self.rlx == 1.0: self.AX = self.X else: alpha = self.rlx self.AX = alpha*self.X + (1 - alpha)*self.Y[..., np.newaxis]
def relax_AX(self)
Implement relaxation if option ``RelaxParam`` != 1.0.
5.406523
4.707885
1.148397
fval = self.obfn_f() gval = self.obfn_g(self.obfn_gvar()) obj = fval + gval return (obj, fval, gval)
def eval_objfn(self)
Compute components of objective function as well as total contribution to objective function.
5.121115
4.329742
1.182776
r return self.X[..., i] if self.opt['fEvalX'] else self.Y
def obfn_fvar(self, i)
r"""Variable to be evaluated in computing :math:`f_i(\cdot)`, depending on the ``fEvalX`` option value.
49.952328
15.824932
3.156559
r return self.Y if self.opt['gEvalY'] else np.mean(self.X, axis=-1)
def obfn_gvar(self)
r"""Variable to be evaluated in computing :math:`g(\cdot)`, depending on the ``gEvalY`` option value.
31.251888
13.245347
2.359462
r obf = 0.0 for i in range(self.Nb): obf += self.obfn_fi(self.obfn_fvar(i), i) return obf
def obfn_f(self)
r"""Compute :math:`f(\mathbf{x}) = \sum_i f(\mathbf{x}_i)` component of ADMM objective function.
6.745583
6.715572
1.004469
# Since s = rho A^T B (y^(k+1) - y^(k)) and B = -(I I I ...)^T, # the correct calculation here would involve replicating (Yprev - Y) # on the axis on which the blocks of X are stacked. Since this would # require allocating additional memory, and since it is only the norm # of s that is required, instead of replicating the vector it is # scaled to have the same l2 norm as the replicated vector return np.sqrt(self.Nb) * self.rho * (Yprev - Y)
def rsdl_s(self, Yprev, Y)
Compute dual residual vector.
14.021079
13.70647
1.022953
# The primal residual normalisation term is # max( ||A x^(k)||_2, ||B y^(k)||_2 ) and B = -(I I I ...)^T. # The scaling by sqrt(Nb) of the l2 norm of Y accounts for the # block replication introduced by multiplication by B return max((np.linalg.norm(AX), np.sqrt(self.Nb) * np.linalg.norm(Y)))
def rsdl_rn(self, AX, Y)
Compute primal residual normalisation term.
14.777172
11.831332
1.248986
r return prox_l2(prox_l1(v, alpha), beta, axis)
def prox_l1l2(v, alpha, beta, axis=None)
r"""Compute the proximal operator of the :math:`\ell_1` plus :math:`\ell_2` norm (compound shrinkage/soft thresholding) :cite:`wohlberg-2012-local` :cite:`chartrand-2013-nonconvex` .. math:: \mathrm{prox}_{f}(\mathbf{v}) = \mathcal{S}_{1,2,\alpha,\beta}(\mathbf{v}) = \mathcal{S}_{2,\beta}(\mathcal{S}_{1,\alpha}(\mathbf{v})) where :math:`f(\mathbf{x}) = \alpha \|\mathbf{x}\|_1 + \beta \|\mathbf{x}\|_2`. Parameters ---------- v : array_like Input array :math:`\mathbf{v}` alpha : float or array_like Parameter :math:`\alpha` beta : float or array_like Parameter :math:`\beta` axis : None or int or tuple of ints, optional (default None) Axes of `v` over which to compute the :math:`\ell_2` norm. If `None`, an entire multi-dimensional array is treated as a vector. If axes are specified, then distinct norm values are computed over the indices of the remaining axes of input array `v`, which is equivalent to the proximal operator of the sum over these values (i.e. an :math:`\ell_{2,1}` norm). Returns ------- x : ndarray Output array
9.253881
14.921535
0.62017
clsmod = {'admm': admm_cbpdn.ConvBPDNMaskDcpl, 'fista': fista_cbpdn.ConvBPDNMask} if label in clsmod: return clsmod[label] else: raise ValueError('Unknown ConvBPDNMask solver method %s' % label)
def cbpdnmsk_class_label_lookup(label)
Get a ConvBPDNMask class from a label string.
5.713667
4.602045
1.24155
dflt = copy.deepcopy(cbpdnmsk_class_label_lookup(method).Options.defaults) if method == 'admm': dflt.update({'MaxMainIter': 1, 'AutoRho': {'Period': 10, 'AutoScaling': False, 'RsdlRatio': 10.0, 'Scaling': 2.0, 'RsdlTarget': 1.0}}) else: dflt.update({'MaxMainIter': 1, 'BackTrack': {'gamma_u': 1.2, 'MaxIter': 50}}) return dflt
def ConvBPDNMaskOptionsDefaults(method='admm')
Get defaults dict for the ConvBPDNMask class specified by the ``method`` parameter.
5.447215
5.388561
1.010885
# Assign base class depending on method selection argument base = cbpdnmsk_class_label_lookup(method).Options # Nested class with dynamically determined inheritance class ConvBPDNMaskOptions(base): def __init__(self, opt): super(ConvBPDNMaskOptions, self).__init__(opt) # Allow pickling of objects of type ConvBPDNOptions _fix_dynamic_class_lookup(ConvBPDNMaskOptions, method) # Return object of the nested class type return ConvBPDNMaskOptions(opt)
def ConvBPDNMaskOptions(opt=None, method='admm')
A wrapper function that dynamically defines a class derived from the Options class associated with one of the implementations of the Convolutional BPDN problem, and returns an object instantiated with the provided parameters. The wrapper is designed to allow the appropriate object to be created by calling this function using the same syntax as would be used if it were a class. The specific implementation is selected by use of an additional keyword argument 'method'. Valid values are as specified in the documentation for :func:`ConvBPDN`.
8.293381
7.671194
1.081107
# Extract method selection argument or set default method = kwargs.pop('method', 'admm') # Assign base class depending on method selection argument base = cbpdnmsk_class_label_lookup(method) # Nested class with dynamically determined inheritance class ConvBPDNMask(base): def __init__(self, *args, **kwargs): super(ConvBPDNMask, self).__init__(*args, **kwargs) # Allow pickling of objects of type ConvBPDNMask _fix_dynamic_class_lookup(ConvBPDNMask, method) # Return object of the nested class type return ConvBPDNMask(*args, **kwargs)
def ConvBPDNMask(*args, **kwargs)
A wrapper function that dynamically defines a class derived from one of the implementations of the Convolutional Constrained MOD problems, and returns an object instantiated with the provided parameters. The wrapper is designed to allow the appropriate object to be created by calling this function using the same syntax as would be used if it were a class. The specific implementation is selected by use of an additional keyword argument 'method'. Valid values are: - ``'admm'`` : Use the implementation defined in :class:`.admm.cbpdn.ConvBPDNMaskDcpl`. - ``'fista'`` : Use the implementation defined in :class:`.fista.cbpdn.ConvBPDNMask`. The default value is ``'admm'``.
6.331108
5.387259
1.1752
clsmod = {'ism': admm_ccmod.ConvCnstrMODMaskDcpl_IterSM, 'cg': admm_ccmod.ConvCnstrMODMaskDcpl_CG, 'cns': admm_ccmod.ConvCnstrMODMaskDcpl_Consensus, 'fista': fista_ccmod.ConvCnstrMODMask} if label in clsmod: return clsmod[label] else: raise ValueError('Unknown ConvCnstrMODMask solver method %s' % label)
def ccmodmsk_class_label_lookup(label)
Get a ConvCnstrMODMask class from a label string.
5.711216
4.951214
1.153498
dflt = copy.deepcopy(ccmodmsk_class_label_lookup(method).Options.defaults) if method == 'fista': dflt.update({'MaxMainIter': 1, 'BackTrack': {'gamma_u': 1.2, 'MaxIter': 50}}) else: dflt.update({'MaxMainIter': 1, 'AutoRho': {'Period': 10, 'AutoScaling': False, 'RsdlRatio': 10.0, 'Scaling': 2.0, 'RsdlTarget': 1.0}}) return dflt
def ConvCnstrMODMaskOptionsDefaults(method='fista')
Get defaults dict for the ConvCnstrMODMask class specified by the ``method`` parameter.
5.611339
5.457842
1.028124
# Assign base class depending on method selection argument base = ccmodmsk_class_label_lookup(method).Options # Nested class with dynamically determined inheritance class ConvCnstrMODMaskOptions(base): def __init__(self, opt): super(ConvCnstrMODMaskOptions, self).__init__(opt) # Allow pickling of objects of type ConvCnstrMODMaskOptions _fix_dynamic_class_lookup(ConvCnstrMODMaskOptions, method) # Return object of the nested class type return ConvCnstrMODMaskOptions(opt)
def ConvCnstrMODMaskOptions(opt=None, method='fista')
A wrapper function that dynamically defines a class derived from the Options class associated with one of the implementations of the Convolutional Constrained MOD problem, and returns an object instantiated with the provided parameters. The wrapper is designed to allow the appropriate object to be created by calling this function using the same syntax as would be used if it were a class. The specific implementation is selected by use of an additional keyword argument 'method'. Valid values are as specified in the documentation for :func:`ConvCnstrMODMask`.
6.743622
6.31529
1.067825
# Extract method selection argument or set default method = kwargs.pop('method', 'fista') # Assign base class depending on method selection argument base = ccmodmsk_class_label_lookup(method) # Nested class with dynamically determined inheritance class ConvCnstrMODMask(base): def __init__(self, *args, **kwargs): super(ConvCnstrMODMask, self).__init__(*args, **kwargs) # Allow pickling of objects of type ConvCnstrMODMask _fix_dynamic_class_lookup(ConvCnstrMODMask, method) # Return object of the nested class type return ConvCnstrMODMask(*args, **kwargs)
def ConvCnstrMODMask(*args, **kwargs)
A wrapper function that dynamically defines a class derived from one of the implementations of the Convolutional Constrained MOD problems, and returns an object instantiated with the provided parameters. The wrapper is designed to allow the appropriate object to be created by calling this function using the same syntax as would be used if it were a class. The specific implementation is selected by use of an additional keyword argument 'method'. Valid values are: - ``'ism'`` : Use the implementation defined in :class:`.ConvCnstrMODMaskDcpl_IterSM`. This method works well for a small number of training images, but is very slow for larger training sets. - ``'cg'`` : Use the implementation defined in :class:`.ConvCnstrMODMaskDcpl_CG`. This method is slower than ``'ism'`` for small training sets, but has better run time scaling as the training set grows. - ``'cns'`` : Use the implementation defined in :class:`.ConvCnstrMODMaskDcpl_Consensus`. This method is a good choice for large training sets. - ``'fista'`` : Use the implementation defined in :class:`.fista.ccmod.ConvCnstrMODMask`. This method is the best choice for large training sets. The default value is ``'fista'``.
5.785129
5.102219
1.133846
if D is None: D = self.getdict(crop=False) if X is None: X = self.getcoef() Df = sl.rfftn(D, self.xstep.cri.Nv, self.xstep.cri.axisN) Xf = sl.rfftn(X, self.xstep.cri.Nv, self.xstep.cri.axisN) DXf = sl.inner(Df, Xf, axis=self.xstep.cri.axisM) return sl.irfftn(DXf, self.xstep.cri.Nv, self.xstep.cri.axisN)
def reconstruct(self, D=None, X=None)
Reconstruct representation.
2.789108
2.706702
1.030445
if self.opt['AccurateDFid']: DX = self.reconstruct() S = self.xstep.S dfd = (np.linalg.norm(self.xstep.W * (DX - S))**2) / 2.0 if self.xmethod == 'fista': X = self.xstep.getcoef() else: X = self.xstep.var_y1() rl1 = np.sum(np.abs(X)) return dict(DFid=dfd, RegL1=rl1, ObjFun=dfd + self.xstep.lmbda * rl1) else: return None
def evaluate(self)
Evaluate functional value of previous iteration.
7.754741
7.013851
1.105632
if dropext: pth = os.path.splitext(pth)[0] parts = os.path.split(pth) if parts[0] == '': return parts[1:] elif len(parts[0]) == 1: return parts else: return pathsplit(parts[0], dropext=False) + parts[1:]
def pathsplit(pth, dropext=True)
Split a path into a tuple of all of its components.
2.268484
2.088471
1.086194
return not os.path.exists(dstpth) or \ os.stat(srcpth).st_mtime > os.stat(dstpth).st_mtime
def update_required(srcpth, dstpth)
If the file at `dstpth` is generated from the file at `srcpth`, determine whether an update is required. Returns True if `dstpth` does not exist, or if `srcpth` has been more recently modified than `dstpth`.
2.749337
2.686317
1.023459
# See https://stackoverflow.com/a/30981554 class MockConfig(object): intersphinx_timeout = None tls_verify = False class MockApp(object): srcdir = '' config = MockConfig() def warn(self, msg): warnings.warn(msg) return intersphinx.fetch_inventory(MockApp(), '', uri)
def fetch_intersphinx_inventory(uri)
Fetch and read an intersphinx inventory file at a specified uri, which can either be a url (e.g. http://...) or a local file system filename.
4.728014
4.822243
0.98046
with open(pth, 'rb') as fo: env = pickle.load(fo) return env
def read_sphinx_environment(pth)
Read the sphinx environment.pickle file at path `pth`.
4.496999
3.200447
1.405116
pthidx = {} pthlst = [] with open(rstpth) as fd: lines = fd.readlines() for i, l in enumerate(lines): if i > 0: if re.match(r'^ \w+', l) is not None and \ re.match(r'^\w+', lines[i - 1]) is not None: # List of subdirectories in order of appearance in index.rst pthlst.append(lines[i - 1][:-1]) # Dict mapping subdirectory name to description pthidx[lines[i - 1][:-1]] = l[2:-1] return pthlst, pthidx
def parse_rst_index(rstpth)
Parse the top-level RST index file, at `rstpth`, for the example python scripts. Returns a list of subdirectories in order of appearance in the index file, and a dict mapping subdirectory name to a description.
3.310428
2.792147
1.185621
# Remove header comment str = re.sub(r'^(#[^#\n]+\n){5}\n*', r'', str) # Insert notebook plotting configuration function str = re.sub(r'from sporco import plot', r'from sporco import plot' '\nplot.config_notebook_plotting()', str, flags=re.MULTILINE) # Remove final input statement and preceding comment str = re.sub(r'\n*# Wait for enter on keyboard.*\ninput().*\n*', r'', str, flags=re.MULTILINE) return str
def preprocess_script_string(str)
Process python script represented as string `str` in preparation for conversion to a notebook. This processing includes removal of the header comment, modification of the plotting configuration, and replacement of certain sphinx cross-references with appropriate links to online docs.
7.132503
6.235024
1.143941
nb = py2jn.py_string_to_notebook(str) py2jn.write_notebook(nb, pth)
def script_string_to_notebook(str, pth)
Convert a python script represented as string `str` to a notebook with filename `pth`.
5.198588
5.013117
1.036997
# Read entire text of example script with open(spth) as f: stxt = f.read() # Process script text stxt = preprocess_script_string(stxt) # If the notebook file exists and has been executed, try to # update markdown cells without deleting output cells if os.path.exists(npth) and notebook_executed(npth): # Read current notebook file nbold = nbformat.read(npth, as_version=4) # Construct updated notebook nbnew = script_string_to_notebook_object(stxt) if cr is not None: notebook_substitute_ref_with_url(nbnew, cr) # If the code cells of the two notebooks match, try to # update markdown cells without deleting output cells if same_notebook_code(nbnew, nbold): try: replace_markdown_cells(nbnew, nbold) except Exception: script_string_to_notebook_with_links(stxt, npth, cr) else: with open(npth, 'wt') as f: nbformat.write(nbold, f) else: # Write changed text to output notebook file script_string_to_notebook_with_links(stxt, npth, cr) else: # Write changed text to output notebook file script_string_to_notebook_with_links(stxt, npth, cr)
def script_to_notebook(spth, npth, cr)
Convert the script at `spth` to a notebook at `npth`. Parameter `cr` is a CrossReferenceLookup object.
3.514211
3.559506
0.987275
if cr is None: script_string_to_notebook(str, pth) else: ntbk = script_string_to_notebook_object(str) notebook_substitute_ref_with_url(ntbk, cr) with open(pth, 'wt') as f: nbformat.write(ntbk, f)
def script_string_to_notebook_with_links(str, pth, cr=None)
Convert a python script represented as string `str` to a notebook with filename `pth` and replace sphinx cross-references with links to online docs. Parameter `cr` is a CrossReferenceLookup object.
3.488066
3.283697
1.062238
# Read infile into a string with open(infile, 'r') as fin: rststr = fin.read() # Convert string from rst to markdown mdfmt = 'markdown_github+tex_math_dollars+fenced_code_attributes' mdstr = pypandoc.convert_text(rststr, mdfmt, format='rst', extra_args=['--atx-headers']) # In links, replace .py extensions with .ipynb mdstr = re.sub(r'\(([^\)]+).py\)', r'(\1.ipynb)', mdstr) # Enclose the markdown within triple quotes and convert from # python to notebook mdstr = '' nb = py2jn.py_string_to_notebook(mdstr) py2jn.tools.write_notebook(nb, outfile, nbver=4)
def rst_to_notebook(infile, outfile)
Convert an rst file to a notebook file.
5.148562
5.187156
0.99256
# Read infile into a string with open(infile, 'r') as fin: str = fin.read() # Enclose the markdown within triple quotes and convert from # python to notebook str = '' nb = py2jn.py_string_to_notebook(str) py2jn.tools.write_notebook(nb, outfile, nbver=4)
def markdown_to_notebook(infile, outfile)
Convert a markdown file to a notebook file.
7.926074
8.246153
0.961184
# Read infile into a list of lines with open(infile, 'r') as fin: rst = fin.readlines() # Inspect outfile path components to determine whether outfile # is in the root of the examples directory or in a subdirectory # thererof ps = pathsplit(outfile)[-3:] if ps[-2] == 'examples': ps = ps[-2:] idx = 'index' else: idx = '' # Output string starts with a cross-reference anchor constructed from # the file name and path out = '.. _' + '_'.join(ps) + ':\n\n' # Iterate over lines from infile it = iter(rst) for line in it: if line[0:12] == '.. toc-start': # Line has start of toc marker # Initialise current toc array and iterate over lines until # end of toc marker encountered toc = [] for line in it: if line == '\n': # Drop newline lines continue elif line[0:10] == '.. toc-end': # End of toc marker # Add toctree section to output string out += '.. toctree::\n :maxdepth: 1\n\n' for c in toc: out += ' %s <%s>\n' % c break else: # Still within toc section # Extract link text and target url and append to # toc array m = re.search(r'`(.*?)\s*<(.*?)(?:.py)?>`', line) if m: if idx == '': toc.append((m.group(1), m.group(2))) else: toc.append((m.group(1), os.path.join(m.group(2), idx))) else: # Not within toc section out += line with open(outfile, 'w') as fout: fout.write(out)
def rst_to_docs_rst(infile, outfile)
Convert an rst file to a sphinx docs rst file.
4.41179
4.403063
1.001982
# Convert notebook to RST text in string rex = RSTExporter() rsttxt = rex.from_filename(ntbkpth)[0] # Clean up trailing whitespace rsttxt = re.sub(r'\n ', r'', rsttxt, re.M | re.S) pthidx = {} pthlst = [] lines = rsttxt.split('\n') for l in lines: m = re.match(r'^-\s+`([^<]+)\s+<([^>]+).ipynb>`__', l) if m: # List of subdirectories in order of appearance in index.rst pthlst.append(m.group(2)) # Dict mapping subdirectory name to description pthidx[m.group(2)] = m.group(1) return pthlst, pthidx
def parse_notebook_index(ntbkpth)
Parse the top-level notebook index file at `ntbkpth`. Returns a list of subdirectories in order of appearance in the index file, and a dict mapping subdirectory name to a description.
4.742922
4.24518
1.117249
# Insert title text txt = '\n\n' return txt
def construct_notebook_index(title, pthlst, pthidx)
Construct a string containing a markdown format index for the list of paths in `pthlst`. The title for the index is in `title`, and `pthidx` is a dict giving label text for each path.
26.759819
30.780321
0.869381
nb = nbformat.read(pth, as_version=4) for n in range(len(nb['cells'])): if nb['cells'][n].cell_type == 'code' and \ nb['cells'][n].execution_count is None: return False return True
def notebook_executed(pth)
Determine whether the notebook at `pth` has been executed.
2.458794
2.184072
1.125785
# Notebooks do not match of the number of cells differ if len(nb1['cells']) != len(nb2['cells']): return False # Iterate over cells in nb1 for n in range(len(nb1['cells'])): # Notebooks do not match if corresponding cells have different # types if nb1['cells'][n]['cell_type'] != nb2['cells'][n]['cell_type']: return False # Notebooks do not match if source of corresponding code cells # differ if nb1['cells'][n]['cell_type'] == 'code' and \ nb1['cells'][n]['source'] != nb2['cells'][n]['source']: return False return True
def same_notebook_code(nb1, nb2)
Return true of the code cells of notebook objects `nb1` and `nb2` are the same.
2.407307
2.424102
0.993072
ep = ExecutePreprocessor(timeout=timeout, kernel_name=kernel) nb = nbformat.read(npth, as_version=4) t0 = timer() ep.preprocess(nb, {'metadata': {'path': dpth}}) t1 = timer() with open(npth, 'wt') as f: nbformat.write(nb, f) return t1 - t0
def execute_notebook(npth, dpth, timeout=1200, kernel='python3')
Execute the notebook at `npth` using `dpth` as the execution directory. The execution timeout and kernel are `timeout` and `kernel` respectively.
2.062433
2.114272
0.975481
# It is an error to attempt markdown replacement if src and dst # have different numbers of cells if len(src['cells']) != len(dst['cells']): raise ValueError('notebooks do not have the same number of cells') # Iterate over cells in src for n in range(len(src['cells'])): # It is an error to attempt markdown replacement if any # corresponding pair of cells have different type if src['cells'][n]['cell_type'] != dst['cells'][n]['cell_type']: raise ValueError('cell number %d of different type in src and dst') # If current src cell is a markdown cell, copy the src cell to # the dst cell if src['cells'][n]['cell_type'] == 'markdown': dst['cells'][n]['source'] = src['cells'][n]['source']
def replace_markdown_cells(src, dst)
Overwrite markdown cells in notebook object `dst` with corresponding cells in notebook object `src`.
3.238187
3.089492
1.048129
# Iterate over cells in notebook for n in range(len(ntbk['cells'])): # Only process cells of type 'markdown' if ntbk['cells'][n]['cell_type'] == 'markdown': # Get text of markdown cell txt = ntbk['cells'][n]['source'] # Replace links to online docs with sphinx cross-references txt = cr.substitute_ref_with_url(txt) # Replace current cell text with processed text ntbk['cells'][n]['source'] = txt
def notebook_substitute_ref_with_url(ntbk, cr)
In markdown cells of notebook object `ntbk`, replace sphinx cross-references with links to online docs. Parameter `cr` is a CrossReferenceLookup object.
3.046232
2.382402
1.278639
# Iterate over cells in notebook for n in range(len(ntbk['cells'])): # Only process cells of type 'markdown' if ntbk['cells'][n]['cell_type'] == 'markdown': # Get text of markdown cell txt = ntbk['cells'][n]['source'] # Replace links to online docs with sphinx cross-references txt = cr.substitute_url_with_ref(txt) # Replace current cell text with processed text ntbk['cells'][n]['source'] = txt
def preprocess_notebook(ntbk, cr)
Process notebook object `ntbk` in preparation for conversion to an rst document. This processing replaces links to online docs with corresponding sphinx cross-references within the local docs. Parameter `cr` is a CrossReferenceLookup object.
3.306772
2.600254
1.271711