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) ...
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...
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} =...
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 (de...
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} = \...
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, opt...
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...
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 obtaine...
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),) + (sl...
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` i...
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)...
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 ...
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), ...
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 indicatin...
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}`...
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=c...
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...
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}...
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...
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) ...
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...
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 --------...
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 = n...
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....
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 ...
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 :...
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 : ndar...
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 ...
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...
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 ...
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 ...
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 = n...
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, se...
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 (rh...
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']: ...
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 reco...
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...
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('...
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...
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: ...
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 co...
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...
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() ...
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 ...
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...
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...
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}}) ...
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) # ...
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 calli...
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 __in...
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...
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 Val...
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, 'AutoS...
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)...
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 creat...
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...
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...
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) ...
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() ...
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_invent...
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 a...
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 ...
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 ...
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...
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...
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+`...
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]['...
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 i...
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 ...
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 ...
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