code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Extended filename used for output images extfnm = fnm + '_files' # Directory into which output images are written extpth = os.path.join(pth, extfnm) # Make output image directory if it doesn't exist mkdir(extpth) # Iterate over output images in resources dict for r in res['outputs'].keys(): # New name for current output image rnew = re.sub('output', fnm, r) # Partial path for current output image rpth = os.path.join(extfnm, rnew) # In RST text, replace old output name with the new one txt = re.sub('\.\. image:: ' + r, '.. image:: ' + rpth, txt, re.M) # Full path of the current output image fullrpth = os.path.join(pth, rpth) # Write the current output image to disk with open(fullrpth, 'wb') as fo: fo.write(res['outputs'][r]) # Remove trailing whitespace in RST text txt = re.sub(r'[ \t]+$', '', txt, flags=re.M) # Write RST text to disk with open(os.path.join(pth, fnm + '.rst'), 'wt') as fo: fo.write(txt)
def write_notebook_rst(txt, res, fnm, pth)
Write the converted notebook text `txt` and resources `res` to filename `fnm` in directory `pth`.
3.327784
3.316674
1.00335
# Read the notebook file ntbk = nbformat.read(npth, nbformat.NO_CONVERT) # Convert notebook object to rstpth notebook_object_to_rst(ntbk, rpth, rdir, cr)
def notebook_to_rst(npth, rpth, rdir, cr=None)
Convert notebook at `npth` to rst document at `rpth`, in directory `rdir`. Parameter `cr` is a CrossReferenceLookup object.
4.28669
4.469654
0.959065
# Parent directory of file rpth rdir = os.path.dirname(rpth) # File basename rb = os.path.basename(os.path.splitext(rpth)[0]) # Pre-process notebook prior to conversion to rst if cr is not None: preprocess_notebook(ntbk, cr) # Convert notebook to rst rex = RSTExporter() rsttxt, rstres = rex.from_notebook_node(ntbk) # Replace `` with ` in sphinx cross-references rsttxt = re.sub(r':([^:]+):``(.*?)``', r':\1:`\2`', rsttxt) # Insert a cross-reference target at top of file reflbl = '.. _examples_' + os.path.basename(rdir) + '_' + \ rb.replace('-', '_') + ':\n' rsttxt = reflbl + rsttxt # Write the converted rst to disk write_notebook_rst(rsttxt, rstres, rb, rdir)
def notebook_object_to_rst(ntbk, rpth, cr=None)
Convert notebook object `ntbk` to rst document at `rpth`, in directory `rdir`. Parameter `cr` is a CrossReferenceLookup object.
4.182382
4.127025
1.013413
# Read entire text of script at spth with open(spth) as f: stxt = f.read() # Process script text stxt = preprocess_script_string(stxt) # Convert script text to notebook object nbs = script_string_to_notebook_object(stxt) # Read notebook file npth nbn = nbformat.read(npth, as_version=4) # Overwrite markdown cells in nbn with those from nbs try: replace_markdown_cells(nbs, nbn) except ValueError: raise ValueError('mismatch between source script %s and notebook %s' % (spth, npth)) # Convert notebook object to rst notebook_object_to_rst(nbn, rpth)
def script_and_notebook_to_rst(spth, npth, rpth)
Convert a script and the corresponding executed notebook to rst. The script is converted to notebook format *without* replacement of sphinx cross-references with links to online docs, and the resulting markdown cells are inserted into the executed notebook, which is then converted to rst.
3.795858
3.728009
1.0182
# Ensure that output directory exists mkdir(rpth) # Iterate over index files for fp in glob(os.path.join(spth, '*.rst')) + \ glob(os.path.join(spth, '*', '*.rst')): # Index basename b = os.path.basename(fp) # Index dirname dn = os.path.dirname(fp) # Name of subdirectory of examples directory containing current index sd = os.path.split(dn) # Set d to the name of the subdirectory of the root directory if dn == spth: # fp is the root directory index file d = '' else: # fp is a subdirectory index file d = sd[-1] # Path to corresponding subdirectory in docs directory fd = os.path.join(rpth, d) # Ensure notebook subdirectory exists mkdir(fd) # Filename of index file to be constructed fn = os.path.join(fd, b) # Process current index file if corresponding notebook file # doesn't exist, or is older than index file if update_required(fp, fn): print('Converting %s ' % os.path.join(d, b), end='\r') # Convert script index to docs index rst_to_docs_rst(fp, fn) # Iterate over example scripts for fp in sorted(glob(os.path.join(spth, '*', '*.py'))): # Name of subdirectory of examples directory containing current script d = os.path.split(os.path.dirname(fp))[1] # Script basename b = os.path.splitext(os.path.basename(fp))[0] # Path to corresponding notebook fn = os.path.join(npth, d, b + '.ipynb') # Path to corresponding sphinx doc file fr = os.path.join(rpth, d, b + '.rst') # Only proceed if script and notebook exist if os.path.exists(fp) and os.path.exists(fn): # Convert notebook to rst if notebook is newer than rst # file or if rst file doesn't exist if update_required(fn, fr): fnb = os.path.join(d, b + '.ipynb') print('Processing %s ' % fnb, end='\r') script_and_notebook_to_rst(fp, fn, fr) else: print('WARNING: script %s or notebook %s not found' % (fp, fn))
def make_example_scripts_docs(spth, npth, rpth)
Generate rst docs from example scripts. Arguments `spth`, `npth`, and `rpth` are the top-level scripts directory, the top-level notebooks directory, and the top-level output directory within the docs respectively.
3.176129
3.157211
1.005992
# An initial '.' indicates a partial name if name[0] == '.': # Find matches for the partial name in the string # containing all full names for this role ptrn = r'(?<= )[^,]*' + name + r'(?=,)' ml = re.findall(ptrn, self.rolnam[role]) # Handle cases depending on the number of returned matches, # raising an error if exactly one match is not found if len(ml) == 0: raise KeyError('name matching %s not found' % name, 'name', len(ml)) elif len(ml) > 1: raise KeyError('multiple names matching %s found' % name, 'name', len(ml)) else: return ml[0] else: # The absence of an initial '.' indicates a full # name. Return the name if it is present in the inventory, # otherwise raise an error try: dom = IntersphinxInventory.roledomain[role] except KeyError: raise KeyError('role %s not found' % role, 'role', 0) if name in self.inv[dom]: return name else: raise KeyError('name %s not found' % name, 'name', 0)
def get_full_name(self, role, name)
If ``name`` is already the full name of an object, return ``name``. Otherwise, if ``name`` is a partial object name, look up the full name and return it.
4.388003
4.367621
1.004667
# Expand partial names to full names name = self.get_full_name(role, name) # Look up domain corresponding to role dom = IntersphinxInventory.roledomain[role] # Get the inventory entry tuple corresponding to the name # of the referenced type itpl = self.inv[dom][name] # Get the required path postfix from the inventory entry # tuple path = itpl[2] # Construct link url, appending the base url or note # depending on the addbase flag return self.baseurl + path if self.addbase else path
def get_docs_url(self, role, name)
Get a url for the online docs corresponding to a sphinx cross reference :role:`name`.
11.182654
10.650919
1.049924
n = len(self.baseurl) return url[0:n] == self.baseurl
def matching_base_url(self, url)
Return True if the initial part of `url` matches the base url passed to the initialiser of this object, and False otherwise.
7.895651
4.918129
1.605417
# Raise an exception if the initial part of url does not match # the base url for this object n = len(self.baseurl) if url[0:n] != self.baseurl: raise KeyError('base of url %s does not match base url %s' % (url, self.baseurl)) # The reverse lookup key is either the full url or the postfix # to the base url, depending on flag addbase if self.addbase: pstfx = url[n:] else: pstfx = url # Look up the cross-reference role and referenced object # name via the postfix to the base url role, name = self.revinv[pstfx] # If the label string is provided and is shorter than the name # string we have lookup up, assume it is a partial name for # the same object: append a '.' at the front and use it as the # object name in the cross-reference if label is not None and len(label) < len(name): name = '.' + label # Construct cross-reference ref = ':%s:`%s`' % (role, name) return ref
def get_sphinx_ref(self, url, label=None)
Get an internal sphinx cross reference corresponding to `url` into the online docs, associated with a link with label `label` (if not None).
6.29922
6.282485
1.002664
# Initialise dicts revinv = {} rolnam = {} # Iterate over domain keys in inventory dict for d in inv: # Since keys seem to be duplicated, ignore those not # starting with 'py:' if d[0:3] == 'py:' and d in IntersphinxInventory.domainrole: # Get role corresponding to current domain r = IntersphinxInventory.domainrole[d] # Initialise role-specific name lookup string rolnam[r] = '' # Iterate over all type names for current domain for n in inv[d]: # Get the url postfix string for the current # domain and type name p = inv[d][n][2] # Allow lookup of role and object name tuple from # url postfix revinv[p] = (r, n) # Append object name to a string for this role, # allowing regex searching for partial names rolnam[r] += ' ' + n + ',' return revinv, rolnam
def inventory_maps(inv)
Construct dicts facilitating information lookup in an inventory dict. A reversed dict allows lookup of a tuple specifying the sphinx cross-reference role and the name of the referenced type from the intersphinx inventory url postfix string. A role-specific name lookup string allows the set of all names corresponding to a specific role to be searched via regex.
8.273963
5.19421
1.592921
if role == 'cite': # If the cross-reference is a citation, make sure that # the cite key is in the sphinx environment bibtex cache. # If it is, construct the url from the cite key, otherwise # raise an exception if name not in self.env.bibtex_cache.get_all_cited_keys(): raise KeyError('cite key %s not found' % name, 'cite', 0) url = self.baseurl + 'zreferences.html#' + name elif role == 'ref': try: reftpl = self.env.domaindata['std']['labels'][name] except Exception: raise KeyError('ref label %s not found' % name, 'ref', 0) url = self.baseurl + reftpl[0] + '.html#' + reftpl[1] else: # If the cross-reference is not a citation, try to look it # up in each of the IntersphinxInventory objects in our list url = None for ii in self.invlst: try: url = ii.get_docs_url(role, name) except KeyError as ex: # Re-raise the exception if multiple matches found, # otherwise ignore it if ex.args[1] == 'role' or ex.args[2] > 1: raise ex else: # If an exception was not raised, the lookup must # have succeeded: break from the loop to terminate # further searching break if url is None: raise KeyError('name %s not found' % name, 'name', 0) return url
def get_docs_url(self, role, name)
Get the online docs url for sphinx cross-reference :role:`name`.
4.617155
4.379669
1.054225
if role == 'cite': # Get the string used as the citation label in the text try: cstr = self.env.bibtex_cache.get_label_from_key(name) except Exception: raise KeyError('cite key %s not found' % name, 'cite', 0) # The link label is the citation label (number) enclosed # in square brackets return '[%s]' % cstr elif role == 'ref': try: reftpl = self.env.domaindata['std']['labels'][name] except Exception: raise KeyError('ref label %s not found' % name, 'ref', 0) return reftpl[2] else: # Use the object name as a label, omiting any initial '.' if name[0] == '.': return name[1:] else: return name
def get_docs_label(self, role, name)
Get an appropriate label to use in a link to the online docs.
5.039724
4.921941
1.02393
# A url is assumed to correspond to a citation if it contains # 'zreferences.html#' if 'zreferences.html#' in url: key = url.partition('zreferences.html#')[2] ref = ':cite:`%s`' % key else: # If the url does not correspond to a citation, try to look it # up in each of the IntersphinxInventory objects in our list ref = None # Iterate over IntersphinxInventory objects in our list for ii in self.invlst: # If the baseurl for the current IntersphinxInventory # object matches the url, try to look up the reference # from the url and terminate the loop of the look up # succeeds if ii.matching_base_url(url): ref = ii.get_sphinx_ref(url, label) break if ref is None: raise KeyError('no match found for url %s' % url) return ref
def get_sphinx_ref(self, url, label=None)
Get an internal sphinx cross reference corresponding to `url` into the online docs, associated with a link with label `label` (if not None).
5.598146
5.571361
1.004808
# Find sphinx cross-references mi = re.finditer(r':([^:]+):`([^`]+)`', txt) if mi: # Iterate over match objects in iterator returned by re.finditer for mo in mi: # Initialize link label and url for substitution lbl = None url = None # Get components of current match: full matching text, the # role label in the reference, and the name of the # referenced type mtxt = mo.group(0) role = mo.group(1) name = mo.group(2) # If role is 'ref', the name component is in the form # label <name> if role == 'ref': ma = re.match(r'\s*([^\s<]+)\s*<([^>]+)+>', name) if ma: name = ma.group(2) lbl = ma.group(1) # Try to look up the current cross-reference. Issue a # warning if the lookup fails, and do the substitution # if it succeeds. try: url = self.get_docs_url(role, name) if role != 'ref': lbl = self.get_docs_label(role, name) except KeyError as ex: if len(ex.args) == 1 or ex.args[1] != 'role': print('Warning: %s' % ex.args[0]) else: # If the cross-reference lookup was successful, replace # it with an appropriate link to the online docs rtxt = '[%s](%s)' % (lbl, url) txt = re.sub(mtxt, rtxt, txt, flags=re.M) return txt
def substitute_ref_with_url(self, txt)
In the string `txt`, replace sphinx references with corresponding links to online docs.
3.98022
3.763788
1.057504
# Find links mi = re.finditer(r'\[([^\]]+|\[[^\]]+\])\]\(([^\)]+)\)', txt) if mi: # Iterate over match objects in iterator returned by # re.finditer for mo in mi: # Get components of current match: full matching text, # the link label, and the postfix to the base url in the # link url mtxt = mo.group(0) lbl = mo.group(1) url = mo.group(2) # Try to look up the current link url. Issue a warning if # the lookup fails, and do the substitution if it succeeds. try: ref = self.get_sphinx_ref(url, lbl) except KeyError as ex: print('Warning: %s' % ex.args[0]) else: txt = re.sub(re.escape(mtxt), ref, txt) return txt
def substitute_url_with_ref(self, txt)
In the string `txt`, replace links to online docs with corresponding sphinx cross-references.
4.647452
4.390683
1.058481
# Extract method selection argument or set default if 'method' in kwargs: method = kwargs['method'] del kwargs['method'] else: method = 'cns' # Assign base class depending on method selection argument if method == 'ism': base = ConvCnstrMOD_IterSM elif method == 'cg': base = ConvCnstrMOD_CG elif method == 'cns': base = ConvCnstrMOD_Consensus else: raise ValueError('Unknown ConvCnstrMOD solver method %s' % method) # Nested class with dynamically determined inheritance class ConvCnstrMOD(base): def __init__(self, *args, **kwargs): super(ConvCnstrMOD, self).__init__(*args, **kwargs) # Allow pickling of objects of type ConvCnstrMOD _fix_dynamic_class_lookup(ConvCnstrMOD, method) # Return object of the nested class type return ConvCnstrMOD(*args, **kwargs)
def ConvCnstrMOD(*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:`.ConvCnstrMOD_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:`.ConvCnstrMOD_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:`.ConvCnstrMOD_Consensus`. This method is the best choice for large training sets. The default value is ``'cns'``.
3.844175
2.80593
1.370018
# Assign base class depending on method selection argument if method == 'ism': base = ConvCnstrMOD_IterSM.Options elif method == 'cg': base = ConvCnstrMOD_CG.Options elif method == 'cns': base = ConvCnstrMOD_Consensus.Options else: raise ValueError('Unknown ConvCnstrMOD solver method %s' % method) # Nested class with dynamically determined inheritance class ConvCnstrMODOptions(base): def __init__(self, opt): super(ConvCnstrMODOptions, self).__init__(opt) # Allow pickling of objects of type ConvCnstrMODOptions _fix_dynamic_class_lookup(ConvCnstrMODOptions, method) # Return object of the nested class type return ConvCnstrMODOptions(opt)
def ConvCnstrMODOptions(opt=None, method='cns')
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:`ConvCnstrMOD`.
4.286292
4.048053
1.058853
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. return self.Y
def uinit(self, ushape)
Return initialiser for working variable U
9.347448
8.536878
1.094949
D = self.Y if crop: D = cr.bcrop(D, self.cri.dsz, self.cri.dimN) return D
def getdict(self, crop=True)
Get final dictionary. If ``crop`` is ``True``, apply :func:`.cnvrep.bcrop` to returned array.
14.269937
12.435812
1.147487
r self.Y = self.Pcn(self.AX + self.U)
def ystep(self)
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.
72.078835
48.815643
1.476552
return self.Xf if self.opt['fEvalX'] else \ sl.rfftn(self.Y, None, self.cri.axisN)
def obfn_fvarf(self)
Variable to be evaluated in computing data fidelity term, depending on 'fEvalX' option value.
23.949556
12.820977
1.867998
dfd = self.obfn_dfd() cns = self.obfn_cns() return (dfd, cns)
def eval_objfn(self)
Compute components of objective function as well as total contribution to objective function.
10.39892
7.81406
1.330796
r return np.linalg.norm((self.Pcn(self.obfn_gvar()) - self.obfn_gvar()))
def obfn_cns(self)
r"""Compute constraint violation measure :math:`\| P(\mathbf{y}) - \mathbf{y}\|_2`.
16.607697
10.950132
1.516666
if D is None: Df = self.Xf else: Df = sl.rfftn(D, None, self.cri.axisN) Sf = np.sum(self.Zf * Df, axis=self.cri.axisM) return sl.irfftn(Sf, self.cri.Nv, self.cri.axisN)
def reconstruct(self, D=None)
Reconstruct representation.
3.721742
3.610311
1.030865
r self.cgit = None self.YU[:] = self.Y - self.U b = self.ZSf + self.rho*sl.rfftn(self.YU, None, self.cri.axisN) self.Xf[:], cgit = sl.solvemdbi_cg(self.Zf, self.rho, b, self.cri.axisM, self.cri.axisK, self.opt['CG', 'StopTol'], self.opt['CG', 'MaxIter'], self.Xf) self.cgit = cgit self.X = sl.irfftn(self.Xf, self.cri.Nv, self.cri.axisN) self.xstep_check(b)
def xstep(self)
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}`.
8.578735
7.131407
1.202951
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. return np.repeat(self.Y[..., np.newaxis], self.Nb, axis=-1)/self.rho
def uinit(self, ushape)
Return initialiser for working variable U.
8.846716
8.071373
1.096061
r # This test reflects empirical evidence that two slightly # different implementations are faster for single or # multi-channel data. This kludge is intended to be temporary. if self.cri.Cd > 1: for i in range(self.Nb): self.xistep(i) else: self.YU[:] = self.Y[..., np.newaxis] - self.U b = np.swapaxes(self.ZSf[..., np.newaxis], self.cri.axisK, -1) \ + self.rho*sl.rfftn(self.YU, None, self.cri.axisN) for i in range(self.Nb): self.Xf[..., i] = sl.solvedbi_sm( self.Zf[..., [i], :], self.rho, b[..., i], axis=self.cri.axisM) self.X = sl.irfftn(self.Xf, self.cri.Nv, self.cri.axisN) if self.opt['LinSolveCheck']: ZSfs = np.sum(self.ZSf, axis=self.cri.axisK, keepdims=True) YU = np.sum(self.Y[..., np.newaxis] - self.U, axis=-1) b = ZSfs + self.rho*sl.rfftn(YU, None, self.cri.axisN) Xf = self.swapaxes(self.Xf) Zop = lambda x: sl.inner(self.Zf, x, axis=self.cri.axisM) ZHop = lambda x: np.conj(self.Zf) * x ax = np.sum(ZHop(Zop(Xf)) + self.rho*Xf, axis=self.cri.axisK, keepdims=True) self.xrrs = sl.rrs(ax, b) else: self.xrrs = None
def xstep(self)
r"""Minimise Augmented Lagrangian with respect to block vector :math:`\mathbf{x} = \left( \begin{array}{ccc} \mathbf{x}_0^T & \mathbf{x}_1^T & \ldots \end{array} \right)^T\;`.
4.98174
4.794158
1.039127
r self.YU[:] = self.Y - self.U[..., i] b = np.take(self.ZSf, [i], axis=self.cri.axisK) + \ self.rho*sl.rfftn(self.YU, None, self.cri.axisN) self.Xf[..., i] = sl.solvedbi_sm(np.take( self.Zf, [i], axis=self.cri.axisK), self.rho, b, axis=self.cri.axisM) self.X[..., i] = sl.irfftn(self.Xf[..., i], self.cri.Nv, self.cri.axisN)
def xistep(self, i)
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}` component :math:`\mathbf{x}_i`.
6.631153
6.316051
1.049889
r Y = self.obfn_gvar() return np.linalg.norm((self.Pcn(Y) - Y))
def obfn_cns(self)
r"""Compute constraint violation measure :math:`\| P(\mathbf{y}) - \mathbf{y}\|_2`.
22.186373
16.525465
1.342557
# If the dictionary has a single channel but the input (and # therefore also the coefficient map array) has multiple # channels, the channel index and multiple image index have # the same behaviour in the dictionary update equation: the # simplest way to handle this is to just reshape so that the # channels also appear on the multiple image index. if self.cri.Cd == 1 and self.cri.C > 1: Z = Z.reshape(self.cri.Nv + (1,) + (self.cri.Cx * self.cri.K,) + (self.cri.M,)) self.Z = np.asarray(Z, dtype=self.dtype) self.Zf = sl.rfftn(self.Z, self.cri.Nv, self.cri.axisN)
def setcoef(self, Z)
Set coefficient array.
8.908943
8.448788
1.054464
# Compute X D - S Ryf = self.eval_Rf(self.Yf) gradf = sl.inner(np.conj(self.Zf), Ryf, axis=self.cri.axisK) # Multiple channel signal, single channel dictionary if self.cri.C > 1 and self.cri.Cd == 1: gradf = np.sum(gradf, axis=self.cri.axisC, keepdims=True) return gradf
def eval_grad(self)
Compute gradient in Fourier domain.
8.620804
7.638571
1.128589
diff = self.Xf - self.Yfprv return sl.rfl2norm2(diff, self.X.shape, axis=self.cri.axisN)
def rsdl(self)
Compute fixed point residual in Fourier domain.
33.370571
18.908241
1.764869
r Ef = self.eval_Rf(self.Xf) return sl.rfl2norm2(Ef, self.S.shape, axis=self.cri.axisN) / 2.0
def obfn_dfd(self)
r"""Compute data fidelity term :math:`(1/2) \| \sum_m \mathbf{d}_m * \mathbf{x}_m - \mathbf{s} \|_2^2`.
25.578798
21.841705
1.171099
r return np.linalg.norm((self.Pcn(self.X) - self.X))
def obfn_cns(self)
r"""Compute constraint violation measure :math:`\| P(\mathbf{y}) - \mathbf{y}\|_2`.
20.5343
13.969906
1.469895
r if Xf is None: Xf = self.Xf Rf = self.eval_Rf(Xf) return 0.5 * np.linalg.norm(Rf.flatten(), 2)**2
def obfn_f(self, Xf=None)
r"""Compute data fidelity term :math:`(1/2) \| \sum_m \mathbf{d}_m * \mathbf{x}_m - \mathbf{s} \|_2^2`. This is used for backtracking. Since the backtracking is computed in the DFT, it is important to preserve the DFT scaling.
5.155694
5.134714
1.004086
r Ef = self.eval_Rf(self.Xf) E = sl.irfftn(Ef, self.cri.Nv, self.cri.axisN) return (np.linalg.norm(self.W * E)**2) / 2.0
def obfn_dfd(self)
r"""Compute data fidelity term :math:`(1/2) \sum_k \| W (\sum_m \mathbf{d}_m * \mathbf{x}_{k,m} - \mathbf{s}_k) \|_2^2`
11.29002
10.965078
1.029634
r if Xf is None: Xf = self.Xf Rf = self.eval_Rf(Xf) R = sl.irfftn(Rf, self.cri.Nv, self.cri.axisN) WRf = sl.rfftn(self.W * R, self.cri.Nv, self.cri.axisN) return 0.5 * np.linalg.norm(WRf.flatten(), 2)**2
def obfn_f(self, Xf=None)
r"""Compute data fidelity term :math:`(1/2) \sum_k \| W (\sum_m \mathbf{d}_m * \mathbf{x}_{k,m} - \mathbf{s}_k) \|_2^2`. This is used for backtracking. Since the backtracking is computed in the DFT, it is important to preserve the DFT scaling.
4.466607
4.165499
1.072286
clsmod = {'admm': admm_cbpdn.ConvBPDN, 'fista': fista_cbpdn.ConvBPDN} if label in clsmod: return clsmod[label] else: raise ValueError('Unknown ConvBPDN solver method %s' % label)
def cbpdn_class_label_lookup(label)
Get a CBPDN class from a label string.
4.692989
4.366402
1.074796
dflt = copy.deepcopy(cbpdn_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 ConvBPDNOptionsDefaults(method='admm')
Get defaults dict for the ConvBPDN class specified by the ``method`` parameter.
5.04611
4.964925
1.016352
# Assign base class depending on method selection argument base = cbpdn_class_label_lookup(method).Options # Nested class with dynamically determined inheritance class ConvBPDNOptions(base): def __init__(self, opt): super(ConvBPDNOptions, self).__init__(opt) # Allow pickling of objects of type ConvBPDNOptions _fix_dynamic_class_lookup(ConvBPDNOptions, method) # Return object of the nested class type return ConvBPDNOptions(opt)
def ConvBPDNOptions(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`.
7.792745
6.993777
1.11424
# Extract method selection argument or set default method = kwargs.pop('method', 'admm') # Assign base class depending on method selection argument base = cbpdn_class_label_lookup(method) # Nested class with dynamically determined inheritance class ConvBPDN(base): def __init__(self, *args, **kwargs): super(ConvBPDN, self).__init__(*args, **kwargs) # Allow pickling of objects of type ConvBPDN _fix_dynamic_class_lookup(ConvBPDN, method) # Return object of the nested class type return ConvBPDN(*args, **kwargs)
def ConvBPDN(*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.ConvBPDN`. - ``'fista'`` : Use the implementation defined in :class:`.fista.cbpdn.ConvBPDN`. The default value is ``'admm'``.
5.938691
5.218736
1.137956
clsmod = {'ism': admm_ccmod.ConvCnstrMOD_IterSM, 'cg': admm_ccmod.ConvCnstrMOD_CG, 'cns': admm_ccmod.ConvCnstrMOD_Consensus, 'fista': fista_ccmod.ConvCnstrMOD} if label in clsmod: return clsmod[label] else: raise ValueError('Unknown ConvCnstrMOD solver method %s' % label)
def ccmod_class_label_lookup(label)
Get a CCMOD class from a label string.
5.044937
5.372272
0.93907
dflt = copy.deepcopy(ccmod_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 ConvCnstrMODOptionsDefaults(method='fista')
Get defaults dict for the ConvCnstrMOD class specified by the ``method`` parameter.
5.393535
5.10053
1.057446
# Assign base class depending on method selection argument base = ccmod_class_label_lookup(method).Options # Nested class with dynamically determined inheritance class ConvCnstrMODOptions(base): def __init__(self, opt): super(ConvCnstrMODOptions, self).__init__(opt) # Allow pickling of objects of type ConvCnstrMODOptions _fix_dynamic_class_lookup(ConvCnstrMODOptions, method) # Return object of the nested class type return ConvCnstrMODOptions(opt)
def ConvCnstrMODOptions(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:`ConvCnstrMOD`.
6.609409
6.12456
1.079165
# Extract method selection argument or set default method = kwargs.pop('method', 'fista') # Assign base class depending on method selection argument base = ccmod_class_label_lookup(method) # Nested class with dynamically determined inheritance class ConvCnstrMOD(base): def __init__(self, *args, **kwargs): super(ConvCnstrMOD, self).__init__(*args, **kwargs) # Allow pickling of objects of type ConvCnstrMOD _fix_dynamic_class_lookup(ConvCnstrMOD, method) # Return object of the nested class type return ConvCnstrMOD(*args, **kwargs)
def ConvCnstrMOD(*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:`.ConvCnstrMOD_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:`.ConvCnstrMOD_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:`.ConvCnstrMOD_Consensus`. This method is a good choice for large training sets. - ``'fista'`` : Use the implementation defined in :class:`.fista.ccmod.ConvCnstrMOD`. This method is the best choice for large training sets. The default value is ``'fista'``.
5.706865
5.095749
1.119927
if self.opt['AccurateDFid']: if self.dmethod == 'fista': D = self.dstep.getdict(crop=False) else: D = self.dstep.var_y() if self.xmethod == 'fista': X = self.xstep.getcoef() else: X = self.xstep.var_y() Df = sl.rfftn(D, self.xstep.cri.Nv, self.xstep.cri.axisN) Xf = sl.rfftn(X, self.xstep.cri.Nv, self.xstep.cri.axisN) Sf = self.xstep.Sf Ef = sl.inner(Df, Xf, axis=self.xstep.cri.axisM) - Sf dfd = sl.rfl2norm2(Ef, self.xstep.S.shape, axis=self.xstep.cri.axisN) / 2.0 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.
4.466753
4.215888
1.059505
if self.opt['AccurateDFid']: D = self.dstep.var_y() X = self.xstep.var_y() S = self.xstep.S dfd = 0.5*np.linalg.norm((D.dot(X) - S))**2 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.305434
6.369809
1.146884
return not os.path.exists(pth1) or not os.path.exists(pth2) or \ os.stat(pth1).st_mtime > os.stat(pth2).st_mtime
def is_newer_than(pth1, pth2)
Return true if either file pth1 or file pth2 don't exist, or if pth1 has been modified more recently than pth2
2.534363
2.315168
1.094678
sz = int(np.product(shape)) csz = sz * np.dtype(dtype).itemsize raw = mp.RawArray('c', csz) return np.frombuffer(raw, dtype=dtype, count=sz).reshape(shape)
def mpraw_as_np(shape, dtype)
Construct a numpy array of the specified shape and dtype for which the underlying storage is a multiprocessing RawArray in shared memory. Parameters ---------- shape : tuple Shape of numpy array dtype : data-type Data type of array Returns ------- arr : ndarray Numpy array
3.46387
3.730947
0.928416
return np.ascontiguousarray(np.swapaxes(x[np.newaxis, ...], 0, axis+1))
def swap_axis_to_0(x, axis)
Insert a new singleton axis at position 0 and swap it with the specified axis. The resulting array has an additional dimension, with ``axis`` + 1 (which was ``axis`` before the insertion of the new axis) of ``x`` at position 0, and a singleton axis at position ``axis`` + 1. Parameters ---------- x : ndarray Input array axis : int Index of axis in ``x`` to swap to axis index 0. Returns ------- arr : ndarray Output array
4.615553
7.016592
0.657806
globals()[mpv] = mpraw_as_np(npv.shape, npv.dtype) globals()[mpv][:] = npv
def init_mpraw(mpv, npv)
Set a global variable as a multiprocessing RawArray in shared memory with a numpy array wrapper and initialise its value. Parameters ---------- mpv : string Name of global variable to set npv : ndarray Numpy array to use as initialiser for global variable value
5.73545
5.529434
1.037258
global mp_DSf # Set working dictionary for cbpdn step and compute DFT of dictionary # D and of D^T S mp_Df[:] = sl.rfftn(mp_D_Y, mp_cri.Nv, mp_cri.axisN) if mp_cri.Cd == 1: mp_DSf[:] = np.conj(mp_Df) * mp_Sf else: mp_DSf[:] = sl.inner(np.conj(mp_Df[np.newaxis, ...]), mp_Sf, axis=mp_cri.axisC+1)
def cbpdn_setdict()
Set the dictionary for the cbpdn stage. There are no parameters or return values because all inputs and outputs are from and to global variables.
8.878844
8.866396
1.001404
YU = mp_Z_Y[k] - mp_Z_U[k] b = mp_DSf[k] + mp_xrho * sl.rfftn(YU, None, mp_cri.axisN) if mp_cri.Cd == 1: Xf = sl.solvedbi_sm(mp_Df, mp_xrho, b, axis=mp_cri.axisM) else: Xf = sl.solvemdbi_ism(mp_Df, mp_xrho, b, mp_cri.axisM, mp_cri.axisC) mp_Z_X[k] = sl.irfftn(Xf, mp_cri.Nv, mp_cri.axisN)
def cbpdn_xstep(k)
Do the X step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
5.904515
5.868493
1.006138
mp_Z_X[k] = mp_xrlx * mp_Z_X[k] + (1 - mp_xrlx) * mp_Z_Y[k]
def cbpdn_relax(k)
Do relaxation for the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
7.49721
7.376577
1.016353
AXU = mp_Z_X[k] + mp_Z_U[k] mp_Z_Y[k] = sp.prox_l1(AXU, (mp_lmbda/mp_xrho))
def cbpdn_ystep(k)
Do the Y step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
13.108836
11.797667
1.111138
# Set working coefficient maps for ccmod step and compute DFT of # coefficient maps Z and Z^T S mp_Zf[k] = sl.rfftn(mp_Z_Y[k], mp_cri.Nv, mp_cri.axisN) mp_ZSf[k] = np.conj(mp_Zf[k]) * mp_Sf[k]
def ccmod_setcoef(k)
Set the coefficient maps for the ccmod stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
13.060806
12.280555
1.063536
YU = mp_D_Y - mp_D_U[k] b = mp_ZSf[k] + mp_drho * sl.rfftn(YU, None, mp_cri.axisN) Xf = sl.solvedbi_sm(mp_Zf[k], mp_drho, b, axis=mp_cri.axisM) mp_D_X[k] = sl.irfftn(Xf, mp_cri.Nv, mp_cri.axisN)
def ccmod_xstep(k)
Do the X step of the ccmod stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
8.761149
8.650258
1.012819
mAXU = np.mean(mp_D_X + mp_D_U, axis=0) mp_D_Y[:] = mp_dprox(mAXU)
def ccmod_ystep()
Do the Y step of the ccmod stage. There are no parameters or return values because all inputs and outputs are from and to global variables.
16.151426
14.369185
1.124032
cbpdn_xstep(k) if mp_xrlx != 1.0: cbpdn_relax(k) cbpdn_ystep(k) cbpdn_ustep(k) ccmod_setcoef(k) ccmod_xstep(k) if mp_drlx != 1.0: ccmod_relax(k)
def step_group(k)
Do a single iteration over cbpdn and ccmod steps that can be performed independently for each slice `k` of the input data set.
6.401753
5.005707
1.278891
YU0 = mp_Z_Y0[k] + mp_S[k] - mp_Z_U0[k] YU1 = mp_Z_Y1[k] - mp_Z_U1[k] if mp_cri.Cd == 1: b = np.conj(mp_Df) * sl.rfftn(YU0, None, mp_cri.axisN) + \ sl.rfftn(YU1, None, mp_cri.axisN) Xf = sl.solvedbi_sm(mp_Df, 1.0, b, axis=mp_cri.axisM) else: b = sl.inner(np.conj(mp_Df), sl.rfftn(YU0, None, mp_cri.axisN), axis=mp_cri.axisC) + \ sl.rfftn(YU1, None, mp_cri.axisN) Xf = sl.solvemdbi_ism(mp_Df, 1.0, b, mp_cri.axisM, mp_cri.axisC) mp_Z_X[k] = sl.irfftn(Xf, mp_cri.Nv, mp_cri.axisN) mp_DX[k] = sl.irfftn(sl.inner(mp_Df, Xf), mp_cri.Nv, mp_cri.axisN)
def cbpdnmd_xstep(k)
Do the X step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
3.324509
3.271733
1.016131
mp_Z_X[k] = mp_xrlx * mp_Z_X[k] + (1 - mp_xrlx) * mp_Z_Y1[k] mp_DX[k] = mp_xrlx * mp_DX[k] + (1 - mp_xrlx) * (mp_Z_Y0[k] + mp_S[k])
def cbpdnmd_relax(k)
Do relaxation for the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
4.202227
4.150481
1.012467
if mp_W.shape[0] > 1: W = mp_W[k] else: W = mp_W AXU0 = mp_DX[k] - mp_S[k] + mp_Z_U0[k] AXU1 = mp_Z_X[k] + mp_Z_U1[k] mp_Z_Y0[k] = mp_xrho*AXU0 / (W**2 + mp_xrho) mp_Z_Y1[k] = sp.prox_l1(AXU1, (mp_lmbda/mp_xrho))
def cbpdnmd_ystep(k)
Do the Y step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
4.984846
5.002069
0.996557
mp_Z_U0[k] += mp_DX[k] - mp_Z_Y0[k] - mp_S[k] mp_Z_U1[k] += mp_Z_X[k] - mp_Z_Y1[k]
def cbpdnmd_ustep(k)
Do the U step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
5.516077
5.345995
1.031815
# Set working coefficient maps for ccmod step and compute DFT of # coefficient maps Z mp_Zf[k] = sl.rfftn(mp_Z_Y1[k], mp_cri.Nv, mp_cri.axisN)
def ccmodmd_setcoef(k)
Set the coefficient maps for the ccmod stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
27.22682
24.516476
1.110552
YU0 = mp_D_Y0 - mp_D_U0[k] YU1 = mp_D_Y1[k] + mp_S[k] - mp_D_U1[k] b = sl.rfftn(YU0, None, mp_cri.axisN) + \ np.conj(mp_Zf[k]) * sl.rfftn(YU1, None, mp_cri.axisN) Xf = sl.solvedbi_sm(mp_Zf[k], 1.0, b, axis=mp_cri.axisM) mp_D_X[k] = sl.irfftn(Xf, mp_cri.Nv, mp_cri.axisN) mp_DX[k] = sl.irfftn(sl.inner(Xf, mp_Zf[k]), mp_cri.Nv, mp_cri.axisN)
def ccmodmd_xstep(k)
Do the X step of the ccmod stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
4.273917
4.201213
1.017305
mp_D_X[k] = mp_drlx * mp_D_X[k] + (1 - mp_drlx) * mp_D_Y0 mp_DX[k] = mp_drlx * mp_DX[k] + (1 - mp_drlx) * (mp_D_Y1[k] + mp_S[k])
def ccmodmd_relax(k)
Do relaxation for the ccmod stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
4.116242
4.072294
1.010792
mAXU = np.mean(mp_D_X + mp_D_U0, axis=0) mp_D_Y0[:] = mp_dprox(mAXU) AXU1 = mp_DX - mp_S + mp_D_U1 mp_D_Y1[:] = mp_drho*AXU1 / (mp_W**2 + mp_drho)
def ccmodmd_ystep()
Do the Y step of the ccmod stage. There are no parameters or return values because all inputs and outputs are from and to global variables.
10.880256
9.987291
1.08941
cbpdnmd_xstep(k) if mp_xrlx != 1.0: cbpdnmd_relax(k) cbpdnmd_ystep(k) cbpdnmd_ustep(k) ccmodmd_setcoef(k) ccmodmd_xstep(k) if mp_drlx != 1.0: ccmodmd_relax(k)
def md_step_group(k)
Do a single iteration over cbpdn and ccmod steps that can be performed independently for each slice `k` of the input data set.
6.150316
5.120872
1.201029
# If the nproc parameter of __init__ is zero, just iterate # over the K consensus instances instead of using # multiprocessing to do the computations in parallel. This is # useful for debugging and timing comparisons. if self.nproc == 0: for k in range(self.xstep.cri.K): step_group(k) else: self.pool.map(step_group, range(self.xstep.cri.K)) ccmod_ystep() ccmod_ustep() cbpdn_setdict()
def step(self)
Do a single iteration over all cbpdn and ccmod steps. Those that are not coupled on the K axis are performed in parallel.
11.461105
7.917269
1.447608
# Construct tuple of status display column titles and set status # display strings hdrtxt = ['Itn', 'Fnc', 'DFid', u('Regℓ1')] hdrstr, fmtstr, nsep = common.solve_status_str( hdrtxt, fwdth0=type(self).fwiter, fprec=type(self).fpothr) # Print header and separator strings if self.opt['Verbose']: if self.opt['StatusHeader']: print(hdrstr) print("-" * nsep) # Reset timer self.timer.start(['solve', 'solve_wo_eval']) # Create process pool if self.nproc > 0: self.pool = mp.Pool(processes=self.nproc) for self.j in range(self.j, self.j + self.opt['MaxMainIter']): # Perform a set of update steps self.step() # Evaluate functional self.timer.stop('solve_wo_eval') fnev = self.evaluate() self.timer.start('solve_wo_eval') # Record iteration stats tk = self.timer.elapsed('solve') itst = self.IterationStats(*((self.j,) + fnev + (tk,))) self.itstat.append(itst) # Display iteration stats if Verbose option enabled if self.opt['Verbose']: print(fmtstr % itst[:-1]) # Call callback function if defined if self.opt['Callback'] is not None: if self.opt['Callback'](self): break # Clean up process pool if self.nproc > 0: self.pool.close() self.pool.join() # Increment iteration count self.j += 1 # Record solve time self.timer.stop(['solve', 'solve_wo_eval']) # Print final separator string if Verbose option enabled if self.opt['Verbose'] and self.opt['StatusHeader']: print("-" * nsep) # Return final dictionary return self.getdict()
def solve(self)
Start (or re-start) optimisation. This method implements the framework for the alternation between `X` and `D` updates in a dictionary learning algorithm. 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. 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
5.215775
4.518962
1.154198
global mp_Z_Y return np.swapaxes(mp_Z_Y, 0, self.xstep.cri.axisK+1)[0]
def getcoef(self)
Get final coefficient map array.
30.981756
24.452286
1.267029
X = mp_Z_Y Xf = mp_Zf Df = mp_Df Sf = mp_Sf Ef = sl.inner(Df[np.newaxis, ...], Xf, axis=self.xstep.cri.axisM+1) - Sf Ef = np.swapaxes(Ef, 0, self.xstep.cri.axisK+1)[0] dfd = sl.rfl2norm2(Ef, self.xstep.S.shape, axis=self.xstep.cri.axisN)/2.0 rl1 = np.sum(np.abs(X)) obj = dfd + self.xstep.lmbda*rl1 return (obj, dfd, rl1)
def evaluate(self)
Evaluate functional value of previous iteration.
7.2521
6.858596
1.057374
# If the nproc parameter of __init__ is zero, just iterate # over the K consensus instances instead of using # multiprocessing to do the computations in parallel. This is # useful for debugging and timing comparisons. if self.nproc == 0: for k in range(self.xstep.cri.K): md_step_group(k) else: self.pool.map(md_step_group, range(self.xstep.cri.K)) ccmodmd_ystep() ccmodmd_ustep() cbpdnmd_setdict()
def step(self)
Do a single iteration over all cbpdn and ccmod steps. Those that are not coupled on the K axis are performed in parallel.
12.190627
8.724504
1.397286
global mp_D_Y0 D = mp_D_Y0 if crop: D = cr.bcrop(D, self.dstep.cri.dsz, self.dstep.cri.dimN) return D
def getdict(self, crop=True)
Get final dictionary. If ``crop`` is ``True``, apply :func:`.cnvrep.bcrop` to returned array.
16.059628
12.853119
1.249473
global mp_Z_Y1 return np.swapaxes(mp_Z_Y1, 0, self.xstep.cri.axisK+1)[0]
def getcoef(self)
Get final coefficient map array.
29.463621
23.799263
1.238006
if self.opt['AccurateDFid']: DX = self.reconstruct() W = self.dstep.W S = self.dstep.S else: W = mp_W S = mp_S Xf = mp_Zf Df = mp_Df DX = sl.irfftn(sl.inner( Df[np.newaxis, ...], Xf, axis=self.xstep.cri.axisM+1), self.xstep.cri.Nv, np.array(self.xstep.cri.axisN) + 1) dfd = (np.linalg.norm(W * (DX - S))**2) / 2.0 rl1 = np.sum(np.abs(self.getcoef())) obj = dfd + self.xstep.lmbda*rl1 return (obj, dfd, rl1)
def evaluate(self)
Evaluate functional value of previous iteration.
8.116821
7.466968
1.08703
if self.opt['AutoRho', 'Enabled']: tau = self.rho_tau mu = self.rho_mu xi = self.rho_xi if k != 0 and cp.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 = cp.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 *= float(rsf) self.U /= rsf if rsf != 1.0: self.rhochange()
def _update_rho(self, k, r, s)
Patched version of :func:`sporco.admm.admm.ADMM.update_rho`.
4.428314
4.151277
1.066735
self.D = np.asarray(D, dtype=self.dtype)
def setdict(self, D)
Set dictionary array.
7.052281
4.696606
1.50157
# Compute D^T(D Y - S) return self.D.T.dot(self.D.dot(self.Y) - self.S)
def eval_grad(self)
Compute gradient in spatial domain for variable Y.
6.762136
5.570749
1.213865
return np.asarray(sp.prox_l1(V, (self.lmbda / self.L) * self.wl1), dtype=self.dtype)
def eval_proxop(self, V)
Compute proximal operator of :math:`g`.
9.144237
8.256569
1.10751
return np.linalg.norm((self.X - self.Yprv).ravel())
def rsdl(self)
Compute fixed point residual.
23.807873
11.803642
2.016994
dfd = self.obfn_f() reg = self.obfn_reg() obj = dfd + reg[0] return (obj, dfd) + reg[1:]
def eval_objfn(self)
Compute components of objective function as well as total contribution to objective function.
7.992234
6.703826
1.19219
r if X is None: X = self.X return 0.5 * np.linalg.norm((self.D.dot(X) - self.S).ravel())**2
def obfn_f(self, X=None)
r"""Compute data fidelity term :math:`(1/2) \| D \mathbf{x} - \mathbf{s} \|_2^2`.
5.135604
3.706573
1.38554
if X is None: X = self.X return self.D.dot(self.X)
def reconstruct(self, X=None)
Reconstruct representation.
4.728995
4.186249
1.12965
if D is not None: self.D = np.asarray(D, dtype=self.dtype) self.Df = sl.rfftn(self.D, self.cri.Nv, self.cri.axisN)
def setdict(self, D=None)
Set dictionary array.
4.981694
4.857226
1.025625
# Compute D X - S Ryf = self.eval_Rf(self.Yf) # Compute D^H Ryf gradf = np.conj(self.Df) * Ryf # Multiple channel signal, multiple channel dictionary if self.cri.Cd > 1: gradf = np.sum(gradf, axis=self.cri.axisC, keepdims=True) return gradf
def eval_grad(self)
Compute gradient in Fourier domain.
11.308169
9.464366
1.194815
return sl.inner(self.Df, Vf, axis=self.cri.axisM) - self.Sf
def eval_Rf(self, Vf)
Evaluate smooth term in Vf.
24.099583
20.431479
1.179532
return sp.prox_l1(V, (self.lmbda / self.L) * self.wl1)
def eval_proxop(self, V)
Compute proximal operator of :math:`g`.
12.882721
11.722901
1.098936
dfd = self.obfn_dfd() reg = self.obfn_reg() obj = dfd + reg[0] return (obj, dfd) + reg[1:]
def eval_objfn(self)
Compute components of objective function as well as total contribution to objective function.
7.674099
6.096067
1.258861
if X is None: X = self.X Xf = sl.rfftn(X, None, self.cri.axisN) Sf = np.sum(self.Df * Xf, axis=self.cri.axisM) return sl.irfftn(Sf, self.cri.Nv, self.cri.axisN)
def reconstruct(self, X=None)
Reconstruct representation.
3.678732
3.496037
1.052258
# Compute D X - S self.Ryf[:] = self.eval_Rf(self.Yf) # Map to spatial domain to multiply by mask Ry = sl.irfftn(self.Ryf, self.cri.Nv, self.cri.axisN) # Multiply by mask self.WRy[:] = (self.W**2) * Ry # Map back to frequency domain WRyf = sl.rfftn(self.WRy, self.cri.Nv, self.cri.axisN) gradf = np.conj(self.Df) * WRyf # Multiple channel signal, multiple channel dictionary if self.cri.Cd > 1: gradf = np.sum(gradf, axis=self.cri.axisC, keepdims=True) return gradf
def eval_grad(self)
Compute gradient in Fourier domain.
6.267098
5.748644
1.090187
return D.reshape(D.shape[0:dimN] + (Cd,) + (1,) + (M,))
def stdformD(D, Cd, M, dimN=2)
Reshape dictionary array (`D` in :mod:`.admm.cbpdn` module, `X` in :mod:`.admm.ccmod` module) to internal standard form. Parameters ---------- D : array_like Dictionary array Cd : int Size of dictionary channel index M : int Number of filters in dictionary dimN : int, optional (default 2) Number of problem spatial indices Returns ------- Dr : ndarray Reshaped dictionary array
6.362753
7.093311
0.897007
r # Number of dimensions in input array `S` sdim = cri.dimN + cri.dimC + cri.dimK if W.ndim < sdim: if W.size == 1: # Weight array is a scalar shpW = (1,) * (cri.dimN + 3) else: # Invalid weight array shape raise ValueError('weight array must be scalar or have at least ' 'the same number of dimensions as input array') elif W.ndim == sdim: # Weight array has the same number of dimensions as the input array shpW = W.shape + (1,) * (3 - cri.dimC - cri.dimK) else: # Weight array has more dimensions than the input array if W.ndim == cri.dimN + 3: # Weight array is already of the appropriate shape shpW = W.shape else: # Assume that the final axis in the input array is the filter # index shpW = W.shape[0:-1] + (1,) * (2 - cri.dimC - cri.dimK) + \ W.shape[-1:] return shpW
def l1Wshape(W, cri)
r"""Get appropriate internal shape (see :class:`CSC_ConvRepIndexing`) for an :math:`\ell_1` norm weight array `W`, as in option ``L1Weight`` in :class:`.admm.cbpdn.ConvBPDN.Options` and related options classes. The external shape of `W` depends on the external shape of input data array `S` and the size of the final axis (i.e. the number of filters) in dictionary array `D`. The internal shape of the weight array `W` is required to be compatible for multiplication with the internal sparse representation array `X`. The simplest criterion for ensuring that the external `W` is compatible with `S` is to ensure that `W` has shape ``S.shape + D.shape[-1:]``, except that non-singleton dimensions may be replaced with singleton dimensions. If `W` has a single additional axis that is neither a spatial axis nor a filter axis, it is assigned as a channel or multi-signal axis depending on the corresponding assignement in `S`. Parameters ---------- W : array_like Weight array cri : :class:`CSC_ConvRepIndexing` object Object specifying convolutional representation dimensions Returns ------- shp : tuple Appropriate internal weight array shape
3.388158
3.039612
1.114668
# Number of axes in W available for C and/or K axes ckdim = W.ndim - cri.dimN if ckdim >= 2: # Both C and K axes are present in W shpW = W.shape + (1,) if ckdim == 2 else W.shape elif ckdim == 1: # Exactly one of C or K axes is present in W if cri.C == 1 and cri.K > 1: # Input S has a single channel and multiple signals shpW = W.shape[0:cri.dimN] + (1, W.shape[cri.dimN]) + (1,) elif cri.C > 1 and cri.K == 1: # Input S has multiple channels and a single signal shpW = W.shape[0:cri.dimN] + (W.shape[cri.dimN], 1) + (1,) else: # Input S has multiple channels and signals: resolve ambiguity # by taking extra axis in W as a channel axis shpW = W.shape[0:cri.dimN] + (W.shape[cri.dimN], 1) + (1,) else: # Neither C nor K axis is present in W shpW = W.shape + (1,) * (3 - ckdim) return shpW
def mskWshape(W, cri)
Get appropriate internal shape (see :class:`CSC_ConvRepIndexing` and :class:`CDU_ConvRepIndexing`) for data fidelity term mask array `W`. The external shape of `W` depends on the external shape of input data array `S`. The simplest criterion for ensuring that the external `W` is compatible with `S` is to ensure that `W` has the same shape as `S`, except that non-singleton dimensions in `S` may be singleton dimensions in `W`. If `W` has a single non-spatial axis, it is assigned as a channel or multi-signal axis depending on the corresponding assignement in `S`. Parameters ---------- W : array_like Data fidelity term weight/mask array cri : :class:`CSC_ConvRepIndexing` object or :class:`CDU_ConvRepIndexing`\ object Object specifying convolutional representation dimensions Returns ------- shp : tuple Appropriate internal mask array shape
3.054755
2.822952
1.082114
vz = v.copy() if isinstance(dsz[0], tuple): # Multi-scale dictionary specification axisN = tuple(range(0, dimN)) m0 = 0 # Initial index of current block of equi-sized filters # Iterate over distinct filter sizes for mb in range(0, len(dsz)): # Determine end index of current block of filters if isinstance(dsz[mb][0], tuple): m1 = m0 + dsz[mb][0][-1] c0 = 0 # Init. idx. of current chnl-block of equi-sized flt. for cb in range(0, len(dsz[mb])): c1 = c0 + dsz[mb][cb][-2] # Construct slice corresponding to cropped part of # current block of filters in output array and set from # input array cbslc = tuple([slice(0, x) for x in dsz[mb][cb][0:dimN]] ) + (slice(c0, c1),) + (Ellipsis,) + \ (slice(m0, m1),) vz[cbslc] -= np.mean(v[cbslc], axisN) c0 = c1 # Update initial index for start of next block else: m1 = m0 + dsz[mb][-1] # Construct slice corresponding to cropped part of # current block of filters in output array and set from # input array mbslc = tuple([slice(0, x) for x in dsz[mb][0:-1]] ) + (Ellipsis,) + (slice(m0, m1),) vz[mbslc] -= np.mean(v[mbslc], axisN) m0 = m1 # Update initial index for start of next block else: # Single scale dictionary specification axisN = tuple(range(0, dimN)) axnslc = tuple([slice(0, x) for x in dsz[0:dimN]]) vz[axnslc] -= np.mean(v[axnslc], axisN) return vz
def zeromean(v, dsz, dimN=2)
Subtract mean value from each filter in the input array v. The `dsz` parameter specifies the support sizes of each filter using the same format as the `dsz` parameter of :func:`bcrop`. Support sizes must be taken into account to ensure that the mean values are computed over the correct number of samples, ignoring the zero-padded region in which the filter is embedded. Parameters ---------- v : array_like Input dictionary array dsz : tuple Filter support size(s) dimN : int, optional (default 2) Number of spatial dimensions Returns ------- vz : ndarray Dictionary array with filter means subtracted
2.925233
2.752953
1.06258
r axisN = tuple(range(0, dimN)) vn = np.sqrt(np.sum(v**2, axisN, keepdims=True)) vn[vn == 0] = 1.0 return np.asarray(v / vn, dtype=v.dtype)
def normalise(v, dimN=2)
r"""Normalise vectors, corresponding to slices along specified number of initial spatial dimensions of an array, to have unit :math:`\ell_2` norm. The remaining axes enumerate the distinct vectors to be normalised. Parameters ---------- v : array_like Array with components to be normalised dimN : int, optional (default 2) Number of initial dimensions over which norm should be computed Returns ------- vnrm : ndarray Normalised array
3.829268
4.18968
0.913976
vp = np.zeros(Nv + v.shape[len(Nv):], dtype=v.dtype) axnslc = tuple([slice(0, x) for x in v.shape]) vp[axnslc] = v return vp
def zpad(v, Nv)
Zero-pad initial axes of array to specified size. Padding is applied to the right, top, etc. of the array indices. Parameters ---------- v : array_like Array to be padded Nv : tuple Sizes to which each of initial indices should be padded Returns ------- vp : ndarray Padded array
4.871636
4.618695
1.054765
if crp: def zpadfn(x): return x else: def zpadfn(x): return zpad(x, Nv) if zm: def zmeanfn(x): return zeromean(x, dsz, dimN) else: def zmeanfn(x): return x return normalise(zmeanfn(zpadfn(bcrop(x, dsz, dimN))), dimN + dimC)
def Pcn(x, dsz, Nv, dimN=2, dimC=1, crp=False, zm=False)
Constraint set projection for convolutional dictionary update problem. Parameters ---------- x : array_like Input array dsz : tuple Filter support size(s), specified using the same format as the `dsz` parameter of :func:`bcrop` Nv : tuple Sizes of problem spatial indices dimN : int, optional (default 2) Number of problem spatial indices dimC : int, optional (default 1) Number of problem channel indices crp : bool, optional (default False) Flag indicating whether the result should be cropped to the support of the largest filter in the dictionary. zm : bool, optional (default False) Flag indicating whether the projection function should include filter mean subtraction Returns ------- y : ndarray Projection of input onto constraint set
3.358868
3.775939
0.889545
fncdict = {(False, False): _Pcn, (False, True): _Pcn_zm, (True, False): _Pcn_crp, (True, True): _Pcn_zm_crp} fnc = fncdict[(crp, zm)] return functools.partial(fnc, dsz=dsz, Nv=Nv, dimN=dimN, dimC=dimC)
def getPcn(dsz, Nv, dimN=2, dimC=1, crp=False, zm=False)
Construct the constraint set projection function for convolutional dictionary update problem. Parameters ---------- dsz : tuple Filter support size(s), specified using the same format as the `dsz` parameter of :func:`bcrop` Nv : tuple Sizes of problem spatial indices dimN : int, optional (default 2) Number of problem spatial indices dimC : int, optional (default 1) Number of problem channel indices crp : bool, optional (default False) Flag indicating whether the result should be cropped to the support of the largest filter in the dictionary. zm : bool, optional (default False) Flag indicating whether the projection function should include filter mean subtraction Returns ------- fn : function Constraint set projection function
2.343852
2.847099
0.823242
return normalise(zpad(bcrop(x, dsz, dimN), Nv), dimN + dimC)
def _Pcn(x, dsz, Nv, dimN=2, dimC=1)
Projection onto dictionary update constraint set: support projection and normalisation. The result has the full spatial dimensions of the input. Parameters ---------- x : array_like Input array dsz : tuple Filter support size(s), specified using the same format as the `dsz` parameter of :func:`bcrop` Nv : tuple Sizes of problem spatial indices dimN : int, optional (default 2) Number of problem spatial indices dimC : int, optional (default 1) Number of problem channel indices Returns ------- y : ndarray Projection of input onto constraint set
12.526287
15.383444
0.814271