repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
bwohlberg/sporco
docs/source/docntbk.py
construct_notebook_index
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. """ # Insert title text txt = '"""\n## %s\n"""\n\n"""' % title # Insert entry for each item in pthlst for pth in pthlst: # If pth refers to a .py file, replace .py with .ipynb, otherwise # assume it's a directory name and append '/index.ipynb' if pth[-3:] == '.py': link = os.path.splitext(pth)[0] + '.ipynb' else: link = os.path.join(pth, 'index.ipynb') txt += '- [%s](%s)\n' % (pthidx[pth], link) txt += '"""' return txt
python
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. """ # Insert title text txt = '"""\n## %s\n"""\n\n"""' % title # Insert entry for each item in pthlst for pth in pthlst: # If pth refers to a .py file, replace .py with .ipynb, otherwise # assume it's a directory name and append '/index.ipynb' if pth[-3:] == '.py': link = os.path.splitext(pth)[0] + '.ipynb' else: link = os.path.join(pth, 'index.ipynb') txt += '- [%s](%s)\n' % (pthidx[pth], link) txt += '"""' return txt
[ "def", "construct_notebook_index", "(", "title", ",", "pthlst", ",", "pthidx", ")", ":", "# Insert title text", "txt", "=", "'\"\"\"\\n## %s\\n\"\"\"\\n\\n\"\"\"'", "%", "title", "# Insert entry for each item in pthlst", "for", "pth", "in", "pthlst", ":", "# If pth refers...
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.
[ "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", "te...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L334-L353
train
210,100
bwohlberg/sporco
docs/source/docntbk.py
notebook_executed
def notebook_executed(pth): """Determine whether the notebook at `pth` has been executed.""" 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
python
def notebook_executed(pth): """Determine whether the notebook at `pth` has been executed.""" 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", ")", ":", "nb", "=", "nbformat", ".", "read", "(", "pth", ",", "as_version", "=", "4", ")", "for", "n", "in", "range", "(", "len", "(", "nb", "[", "'cells'", "]", ")", ")", ":", "if", "nb", "[", "'cells'", ...
Determine whether the notebook at `pth` has been executed.
[ "Determine", "whether", "the", "notebook", "at", "pth", "has", "been", "executed", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L357-L365
train
210,101
bwohlberg/sporco
docs/source/docntbk.py
same_notebook_code
def same_notebook_code(nb1, nb2): """ Return true of the code cells of notebook objects `nb1` and `nb2` are the same. """ # Notebooks do not match of the number of cells differ if len(nb1['cells']) != len(nb2['cells']): return False # Iterate over cells in nb1 for n in range(len(nb1['cells'])): # Notebooks do not match if corresponding cells have different # types if nb1['cells'][n]['cell_type'] != nb2['cells'][n]['cell_type']: return False # Notebooks do not match if source of corresponding code cells # differ if nb1['cells'][n]['cell_type'] == 'code' and \ nb1['cells'][n]['source'] != nb2['cells'][n]['source']: return False return True
python
def same_notebook_code(nb1, nb2): """ Return true of the code cells of notebook objects `nb1` and `nb2` are the same. """ # Notebooks do not match of the number of cells differ if len(nb1['cells']) != len(nb2['cells']): return False # Iterate over cells in nb1 for n in range(len(nb1['cells'])): # Notebooks do not match if corresponding cells have different # types if nb1['cells'][n]['cell_type'] != nb2['cells'][n]['cell_type']: return False # Notebooks do not match if source of corresponding code cells # differ if nb1['cells'][n]['cell_type'] == 'code' and \ nb1['cells'][n]['source'] != nb2['cells'][n]['source']: return False return True
[ "def", "same_notebook_code", "(", "nb1", ",", "nb2", ")", ":", "# Notebooks do not match of the number of cells differ", "if", "len", "(", "nb1", "[", "'cells'", "]", ")", "!=", "len", "(", "nb2", "[", "'cells'", "]", ")", ":", "return", "False", "# Iterate ov...
Return true of the code cells of notebook objects `nb1` and `nb2` are the same.
[ "Return", "true", "of", "the", "code", "cells", "of", "notebook", "objects", "nb1", "and", "nb2", "are", "the", "same", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L369-L391
train
210,102
bwohlberg/sporco
docs/source/docntbk.py
execute_notebook
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. """ 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
python
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. """ 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'", ")", ":", "ep", "=", "ExecutePreprocessor", "(", "timeout", "=", "timeout", ",", "kernel_name", "=", "kernel", ")", "nb", "=", "nbformat", ...
Execute the notebook at `npth` using `dpth` as the execution directory. The execution timeout and kernel are `timeout` and `kernel` respectively.
[ "Execute", "the", "notebook", "at", "npth", "using", "dpth", "as", "the", "execution", "directory", ".", "The", "execution", "timeout", "and", "kernel", "are", "timeout", "and", "kernel", "respectively", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L395-L409
train
210,103
bwohlberg/sporco
docs/source/docntbk.py
replace_markdown_cells
def replace_markdown_cells(src, dst): """ Overwrite markdown cells in notebook object `dst` with corresponding cells in notebook object `src`. """ # It is an error to attempt markdown replacement if src and dst # have different numbers of cells if len(src['cells']) != len(dst['cells']): raise ValueError('notebooks do not have the same number of cells') # Iterate over cells in src for n in range(len(src['cells'])): # It is an error to attempt markdown replacement if any # corresponding pair of cells have different type if src['cells'][n]['cell_type'] != dst['cells'][n]['cell_type']: raise ValueError('cell number %d of different type in src and dst') # If current src cell is a markdown cell, copy the src cell to # the dst cell if src['cells'][n]['cell_type'] == 'markdown': dst['cells'][n]['source'] = src['cells'][n]['source']
python
def replace_markdown_cells(src, dst): """ Overwrite markdown cells in notebook object `dst` with corresponding cells in notebook object `src`. """ # It is an error to attempt markdown replacement if src and dst # have different numbers of cells if len(src['cells']) != len(dst['cells']): raise ValueError('notebooks do not have the same number of cells') # Iterate over cells in src for n in range(len(src['cells'])): # It is an error to attempt markdown replacement if any # corresponding pair of cells have different type if src['cells'][n]['cell_type'] != dst['cells'][n]['cell_type']: raise ValueError('cell number %d of different type in src and dst') # If current src cell is a markdown cell, copy the src cell to # the dst cell if src['cells'][n]['cell_type'] == 'markdown': dst['cells'][n]['source'] = src['cells'][n]['source']
[ "def", "replace_markdown_cells", "(", "src", ",", "dst", ")", ":", "# It is an error to attempt markdown replacement if src and dst", "# have different numbers of cells", "if", "len", "(", "src", "[", "'cells'", "]", ")", "!=", "len", "(", "dst", "[", "'cells'", "]", ...
Overwrite markdown cells in notebook object `dst` with corresponding cells in notebook object `src`.
[ "Overwrite", "markdown", "cells", "in", "notebook", "object", "dst", "with", "corresponding", "cells", "in", "notebook", "object", "src", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L413-L433
train
210,104
bwohlberg/sporco
docs/source/docntbk.py
notebook_substitute_ref_with_url
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. """ # Iterate over cells in notebook for n in range(len(ntbk['cells'])): # Only process cells of type 'markdown' if ntbk['cells'][n]['cell_type'] == 'markdown': # Get text of markdown cell txt = ntbk['cells'][n]['source'] # Replace links to online docs with sphinx cross-references txt = cr.substitute_ref_with_url(txt) # Replace current cell text with processed text ntbk['cells'][n]['source'] = txt
python
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. """ # Iterate over cells in notebook for n in range(len(ntbk['cells'])): # Only process cells of type 'markdown' if ntbk['cells'][n]['cell_type'] == 'markdown': # Get text of markdown cell txt = ntbk['cells'][n]['source'] # Replace links to online docs with sphinx cross-references txt = cr.substitute_ref_with_url(txt) # Replace current cell text with processed text ntbk['cells'][n]['source'] = txt
[ "def", "notebook_substitute_ref_with_url", "(", "ntbk", ",", "cr", ")", ":", "# Iterate over cells in notebook", "for", "n", "in", "range", "(", "len", "(", "ntbk", "[", "'cells'", "]", ")", ")", ":", "# Only process cells of type 'markdown'", "if", "ntbk", "[", ...
In markdown cells of notebook object `ntbk`, replace sphinx cross-references with links to online docs. Parameter `cr` is a CrossReferenceLookup object.
[ "In", "markdown", "cells", "of", "notebook", "object", "ntbk", "replace", "sphinx", "cross", "-", "references", "with", "links", "to", "online", "docs", ".", "Parameter", "cr", "is", "a", "CrossReferenceLookup", "object", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L437-L453
train
210,105
bwohlberg/sporco
docs/source/docntbk.py
preprocess_notebook
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. """ # Iterate over cells in notebook for n in range(len(ntbk['cells'])): # Only process cells of type 'markdown' if ntbk['cells'][n]['cell_type'] == 'markdown': # Get text of markdown cell txt = ntbk['cells'][n]['source'] # Replace links to online docs with sphinx cross-references txt = cr.substitute_url_with_ref(txt) # Replace current cell text with processed text ntbk['cells'][n]['source'] = txt
python
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. """ # Iterate over cells in notebook for n in range(len(ntbk['cells'])): # Only process cells of type 'markdown' if ntbk['cells'][n]['cell_type'] == 'markdown': # Get text of markdown cell txt = ntbk['cells'][n]['source'] # Replace links to online docs with sphinx cross-references txt = cr.substitute_url_with_ref(txt) # Replace current cell text with processed text ntbk['cells'][n]['source'] = txt
[ "def", "preprocess_notebook", "(", "ntbk", ",", "cr", ")", ":", "# Iterate over cells in notebook", "for", "n", "in", "range", "(", "len", "(", "ntbk", "[", "'cells'", "]", ")", ")", ":", "# Only process cells of type 'markdown'", "if", "ntbk", "[", "'cells'", ...
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.
[ "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", "th...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L457-L474
train
210,106
bwohlberg/sporco
docs/source/docntbk.py
write_notebook_rst
def write_notebook_rst(txt, res, fnm, pth): """ Write the converted notebook text `txt` and resources `res` to filename `fnm` in directory `pth`. """ # 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)
python
def write_notebook_rst(txt, res, fnm, pth): """ Write the converted notebook text `txt` and resources `res` to filename `fnm` in directory `pth`. """ # 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", ")", ":", "# Extended filename used for output images", "extfnm", "=", "fnm", "+", "'_files'", "# Directory into which output images are written", "extpth", "=", "os", ".", "path", ".", "jo...
Write the converted notebook text `txt` and resources `res` to filename `fnm` in directory `pth`.
[ "Write", "the", "converted", "notebook", "text", "txt", "and", "resources", "res", "to", "filename", "fnm", "in", "directory", "pth", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L478-L509
train
210,107
bwohlberg/sporco
docs/source/docntbk.py
notebook_to_rst
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. """ # Read the notebook file ntbk = nbformat.read(npth, nbformat.NO_CONVERT) # Convert notebook object to rstpth notebook_object_to_rst(ntbk, rpth, rdir, cr)
python
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. """ # 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", ")", ":", "# Read the notebook file", "ntbk", "=", "nbformat", ".", "read", "(", "npth", ",", "nbformat", ".", "NO_CONVERT", ")", "# Convert notebook object to rstpth", "n...
Convert notebook at `npth` to rst document at `rpth`, in directory `rdir`. Parameter `cr` is a CrossReferenceLookup object.
[ "Convert", "notebook", "at", "npth", "to", "rst", "document", "at", "rpth", "in", "directory", "rdir", ".", "Parameter", "cr", "is", "a", "CrossReferenceLookup", "object", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L513-L522
train
210,108
bwohlberg/sporco
docs/source/docntbk.py
notebook_object_to_rst
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. """ # 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)
python
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. """ # 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", ")", ":", "# Parent directory of file rpth", "rdir", "=", "os", ".", "path", ".", "dirname", "(", "rpth", ")", "# File basename", "rb", "=", "os", ".", "path", ".", "basenam...
Convert notebook object `ntbk` to rst document at `rpth`, in directory `rdir`. Parameter `cr` is a CrossReferenceLookup object.
[ "Convert", "notebook", "object", "ntbk", "to", "rst", "document", "at", "rpth", "in", "directory", "rdir", ".", "Parameter", "cr", "is", "a", "CrossReferenceLookup", "object", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L526-L551
train
210,109
bwohlberg/sporco
docs/source/docntbk.py
make_example_scripts_docs
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. """ # 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))
python
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. """ # 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", ")", ":", "# Ensure that output directory exists", "mkdir", "(", "rpth", ")", "# Iterate over index files", "for", "fp", "in", "glob", "(", "os", ".", "path", ".", "join", "(", "spth", ...
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.
[ "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", "o...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L997-L1056
train
210,110
bwohlberg/sporco
docs/source/docntbk.py
IntersphinxInventory.get_full_name
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. """ # 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)
python
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. """ # 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", ")", ":", "# 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", "...
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.
[ "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", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L634-L668
train
210,111
bwohlberg/sporco
docs/source/docntbk.py
IntersphinxInventory.matching_base_url
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. """ n = len(self.baseurl) return url[0:n] == self.baseurl
python
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. """ n = len(self.baseurl) return url[0:n] == self.baseurl
[ "def", "matching_base_url", "(", "self", ",", "url", ")", ":", "n", "=", "len", "(", "self", ".", "baseurl", ")", "return", "url", "[", "0", ":", "n", "]", "==", "self", ".", "baseurl" ]
Return True if the initial part of `url` matches the base url passed to the initialiser of this object, and False otherwise.
[ "Return", "True", "if", "the", "initial", "part", "of", "url", "matches", "the", "base", "url", "passed", "to", "the", "initialiser", "of", "this", "object", "and", "False", "otherwise", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L694-L701
train
210,112
bwohlberg/sporco
docs/source/docntbk.py
IntersphinxInventory.inventory_maps
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. """ # 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
python
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. """ # 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", ")", ":", "# 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 'p...
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.
[ "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", ...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L743-L776
train
210,113
bwohlberg/sporco
docs/source/docntbk.py
CrossReferenceLookup.get_docs_label
def get_docs_label(self, role, name): """Get an appropriate label to use in a link to the online docs.""" 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
python
def get_docs_label(self, role, name): """Get an appropriate label to use in a link to the online docs.""" 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", ")", ":", "if", "role", "==", "'cite'", ":", "# Get the string used as the citation label in the text", "try", ":", "cstr", "=", "self", ".", "env", ".", "bibtex_cache", ".", "get_label_from_key", "...
Get an appropriate label to use in a link to the online docs.
[ "Get", "an", "appropriate", "label", "to", "use", "in", "a", "link", "to", "the", "online", "docs", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L854-L877
train
210,114
bwohlberg/sporco
docs/source/docntbk.py
CrossReferenceLookup.substitute_ref_with_url
def substitute_ref_with_url(self, txt): """ In the string `txt`, replace sphinx references with corresponding links to online docs. """ # 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
python
def substitute_ref_with_url(self, txt): """ In the string `txt`, replace sphinx references with corresponding links to online docs. """ # 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", ")", ":", "# Find sphinx cross-references", "mi", "=", "re", ".", "finditer", "(", "r':([^:]+):`([^`]+)`'", ",", "txt", ")", "if", "mi", ":", "# Iterate over match objects in iterator returned by re.finditer", "...
In the string `txt`, replace sphinx references with corresponding links to online docs.
[ "In", "the", "string", "txt", "replace", "sphinx", "references", "with", "corresponding", "links", "to", "online", "docs", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L914-L959
train
210,115
bwohlberg/sporco
docs/source/docntbk.py
CrossReferenceLookup.substitute_url_with_ref
def substitute_url_with_ref(self, txt): """ In the string `txt`, replace links to online docs with corresponding sphinx cross-references. """ # 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
python
def substitute_url_with_ref(self, txt): """ In the string `txt`, replace links to online docs with corresponding sphinx cross-references. """ # 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", ")", ":", "# Find links", "mi", "=", "re", ".", "finditer", "(", "r'\\[([^\\]]+|\\[[^\\]]+\\])\\]\\(([^\\)]+)\\)'", ",", "txt", ")", "if", "mi", ":", "# Iterate over match objects in iterator returned by", "# re...
In the string `txt`, replace links to online docs with corresponding sphinx cross-references.
[ "In", "the", "string", "txt", "replace", "links", "to", "online", "docs", "with", "corresponding", "sphinx", "cross", "-", "references", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L963-L991
train
210,116
bwohlberg/sporco
sporco/admm/ccmod.py
ConvCnstrMODBase.obfn_fvarf
def obfn_fvarf(self): """Variable to be evaluated in computing data fidelity term, depending on 'fEvalX' option value. """ return self.Xf if self.opt['fEvalX'] else \ sl.rfftn(self.Y, None, self.cri.axisN)
python
def obfn_fvarf(self): """Variable to be evaluated in computing data fidelity term, depending on 'fEvalX' option value. """ return self.Xf if self.opt['fEvalX'] else \ sl.rfftn(self.Y, None, self.cri.axisN)
[ "def", "obfn_fvarf", "(", "self", ")", ":", "return", "self", ".", "Xf", "if", "self", ".", "opt", "[", "'fEvalX'", "]", "else", "sl", ".", "rfftn", "(", "self", ".", "Y", ",", "None", ",", "self", ".", "cri", ".", "axisN", ")" ]
Variable to be evaluated in computing data fidelity term, depending on 'fEvalX' option value.
[ "Variable", "to", "be", "evaluated", "in", "computing", "data", "fidelity", "term", "depending", "on", "fEvalX", "option", "value", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/ccmod.py#L360-L366
train
210,117
bwohlberg/sporco
sporco/fista/ccmod.py
ConvCnstrMOD.rsdl
def rsdl(self): """Compute fixed point residual in Fourier domain.""" diff = self.Xf - self.Yfprv return sl.rfl2norm2(diff, self.X.shape, axis=self.cri.axisN)
python
def rsdl(self): """Compute fixed point residual in Fourier domain.""" diff = self.Xf - self.Yfprv return sl.rfl2norm2(diff, self.X.shape, axis=self.cri.axisN)
[ "def", "rsdl", "(", "self", ")", ":", "diff", "=", "self", ".", "Xf", "-", "self", ".", "Yfprv", "return", "sl", ".", "rfl2norm2", "(", "diff", ",", "self", ".", "X", ".", "shape", ",", "axis", "=", "self", ".", "cri", ".", "axisN", ")" ]
Compute fixed point residual in Fourier domain.
[ "Compute", "fixed", "point", "residual", "in", "Fourier", "domain", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/fista/ccmod.py#L324-L328
train
210,118
bwohlberg/sporco
sporco/dictlrn/cbpdndl.py
cbpdn_class_label_lookup
def cbpdn_class_label_lookup(label): """Get a CBPDN class from a label string.""" 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)
python
def cbpdn_class_label_lookup(label): """Get a CBPDN class from a label string.""" 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", ")", ":", "clsmod", "=", "{", "'admm'", ":", "admm_cbpdn", ".", "ConvBPDN", ",", "'fista'", ":", "fista_cbpdn", ".", "ConvBPDN", "}", "if", "label", "in", "clsmod", ":", "return", "clsmod", "[", "label", "]"...
Get a CBPDN class from a label string.
[ "Get", "a", "CBPDN", "class", "from", "a", "label", "string", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/cbpdndl.py#L31-L39
train
210,119
bwohlberg/sporco
sporco/dictlrn/cbpdndl.py
ConvBPDNOptionsDefaults
def ConvBPDNOptionsDefaults(method='admm'): """Get defaults dict for the ConvBPDN class specified by the ``method`` parameter. """ 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
python
def ConvBPDNOptionsDefaults(method='admm'): """Get defaults dict for the ConvBPDN class specified by the ``method`` parameter. """ 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'", ")", ":", "dflt", "=", "copy", ".", "deepcopy", "(", "cbpdn_class_label_lookup", "(", "method", ")", ".", "Options", ".", "defaults", ")", "if", "method", "==", "'admm'", ":", "dflt", ".", "up...
Get defaults dict for the ConvBPDN class specified by the ``method`` parameter.
[ "Get", "defaults", "dict", "for", "the", "ConvBPDN", "class", "specified", "by", "the", "method", "parameter", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/cbpdndl.py#L43-L57
train
210,120
bwohlberg/sporco
sporco/dictlrn/cbpdndl.py
ccmod_class_label_lookup
def ccmod_class_label_lookup(label): """Get a CCMOD class from a label string.""" 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)
python
def ccmod_class_label_lookup(label): """Get a CCMOD class from a label string.""" 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", ")", ":", "clsmod", "=", "{", "'ism'", ":", "admm_ccmod", ".", "ConvCnstrMOD_IterSM", ",", "'cg'", ":", "admm_ccmod", ".", "ConvCnstrMOD_CG", ",", "'cns'", ":", "admm_ccmod", ".", "ConvCnstrMOD_Consensus", ",", "'...
Get a CCMOD class from a label string.
[ "Get", "a", "CCMOD", "class", "from", "a", "label", "string", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/cbpdndl.py#L126-L136
train
210,121
bwohlberg/sporco
sporco/dictlrn/cbpdndl.py
ConvCnstrMODOptionsDefaults
def ConvCnstrMODOptionsDefaults(method='fista'): """Get defaults dict for the ConvCnstrMOD class specified by the ``method`` parameter. """ 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
python
def ConvCnstrMODOptionsDefaults(method='fista'): """Get defaults dict for the ConvCnstrMOD class specified by the ``method`` parameter. """ 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'", ")", ":", "dflt", "=", "copy", ".", "deepcopy", "(", "ccmod_class_label_lookup", "(", "method", ")", ".", "Options", ".", "defaults", ")", "if", "method", "==", "'fista'", ":", "dflt", ".",...
Get defaults dict for the ConvCnstrMOD class specified by the ``method`` parameter.
[ "Get", "defaults", "dict", "for", "the", "ConvCnstrMOD", "class", "specified", "by", "the", "method", "parameter", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/cbpdndl.py#L140-L154
train
210,122
bwohlberg/sporco
sporco/dictlrn/bpdndl.py
BPDNDictLearn.evaluate
def evaluate(self): """Evaluate functional value of previous iteration""" 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
python
def evaluate(self): """Evaluate functional value of previous iteration""" 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", ")", ":", "if", "self", ".", "opt", "[", "'AccurateDFid'", "]", ":", "D", "=", "self", ".", "dstep", ".", "var_y", "(", ")", "X", "=", "self", ".", "xstep", ".", "var_y", "(", ")", "S", "=", "self", ".", "xstep",...
Evaluate functional value of previous iteration
[ "Evaluate", "functional", "value", "of", "previous", "iteration" ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/bpdndl.py#L196-L207
train
210,123
bwohlberg/sporco
docs/source/callgraph.py
is_newer_than
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 """ return not os.path.exists(pth1) or not os.path.exists(pth2) or \ os.stat(pth1).st_mtime > os.stat(pth2).st_mtime
python
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 """ 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", "not", "os", ".", "path", ".", "exists", "(", "pth1", ")", "or", "not", "os", ".", "path", ".", "exists", "(", "pth2", ")", "or", "os", ".", "stat", "(", "pth1", ")", ".", "s...
Return true if either file pth1 or file pth2 don't exist, or if pth1 has been modified more recently than pth2
[ "Return", "true", "if", "either", "file", "pth1", "or", "file", "pth2", "don", "t", "exist", "or", "if", "pth1", "has", "been", "modified", "more", "recently", "than", "pth2" ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/callgraph.py#L24-L31
train
210,124
bwohlberg/sporco
sporco/dictlrn/prlcnscdl.py
mpraw_as_np
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 """ 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)
python
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 """ 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", ")", ":", "sz", "=", "int", "(", "np", ".", "product", "(", "shape", ")", ")", "csz", "=", "sz", "*", "np", ".", "dtype", "(", "dtype", ")", ".", "itemsize", "raw", "=", "mp", ".", "RawArray", "...
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
[ "Construct", "a", "numpy", "array", "of", "the", "specified", "shape", "and", "dtype", "for", "which", "the", "underlying", "storage", "is", "a", "multiprocessing", "RawArray", "in", "shared", "memory", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/prlcnscdl.py#L60-L80
train
210,125
bwohlberg/sporco
sporco/dictlrn/prlcnscdl.py
init_mpraw
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 """ globals()[mpv] = mpraw_as_np(npv.shape, npv.dtype) globals()[mpv][:] = npv
python
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 """ globals()[mpv] = mpraw_as_np(npv.shape, npv.dtype) globals()[mpv][:] = npv
[ "def", "init_mpraw", "(", "mpv", ",", "npv", ")", ":", "globals", "(", ")", "[", "mpv", "]", "=", "mpraw_as_np", "(", "npv", ".", "shape", ",", "npv", ".", "dtype", ")", "globals", "(", ")", "[", "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
[ "Set", "a", "global", "variable", "as", "a", "multiprocessing", "RawArray", "in", "shared", "memory", "with", "a", "numpy", "array", "wrapper", "and", "initialise", "its", "value", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/prlcnscdl.py#L108-L121
train
210,126
bwohlberg/sporco
sporco/dictlrn/prlcnscdl.py
cbpdn_setdict
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. """ 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)
python
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. """ 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", "(", ")", ":", "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", ".", "a...
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.
[ "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", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/prlcnscdl.py#L127-L141
train
210,127
bwohlberg/sporco
sporco/dictlrn/prlcnscdl.py
cbpdnmd_ustep
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. """ 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]
python
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. """ 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", ")", ":", "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", ...
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.
[ "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",...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/prlcnscdl.py#L704-L711
train
210,128
bwohlberg/sporco
sporco/dictlrn/prlcnscdl.py
ccmodmd_relax
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. """ 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])
python
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. """ 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", ")", ":", "mp_D_X", "[", "k", "]", "=", "mp_drlx", "*", "mp_D_X", "[", "k", "]", "+", "(", "1", "-", "mp_drlx", ")", "*", "mp_D_Y0", "mp_DX", "[", "k", "]", "=", "mp_drlx", "*", "mp_DX", "[", "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.
[ "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", "varia...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/prlcnscdl.py#L743-L750
train
210,129
bwohlberg/sporco
sporco/fista/bpdn.py
BPDN.eval_grad
def eval_grad(self): """Compute gradient in spatial domain for variable Y.""" # Compute D^T(D Y - S) return self.D.T.dot(self.D.dot(self.Y) - self.S)
python
def eval_grad(self): """Compute gradient in spatial domain for variable Y.""" # Compute D^T(D Y - S) return self.D.T.dot(self.D.dot(self.Y) - self.S)
[ "def", "eval_grad", "(", "self", ")", ":", "# Compute D^T(D Y - S)", "return", "self", ".", "D", ".", "T", ".", "dot", "(", "self", ".", "D", ".", "dot", "(", "self", ".", "Y", ")", "-", "self", ".", "S", ")" ]
Compute gradient in spatial domain for variable Y.
[ "Compute", "gradient", "in", "spatial", "domain", "for", "variable", "Y", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/fista/bpdn.py#L210-L214
train
210,130
bwohlberg/sporco
sporco/fista/bpdn.py
BPDN.rsdl
def rsdl(self): """Compute fixed point residual.""" return np.linalg.norm((self.X - self.Yprv).ravel())
python
def rsdl(self): """Compute fixed point residual.""" return np.linalg.norm((self.X - self.Yprv).ravel())
[ "def", "rsdl", "(", "self", ")", ":", "return", "np", ".", "linalg", ".", "norm", "(", "(", "self", ".", "X", "-", "self", ".", "Yprv", ")", ".", "ravel", "(", ")", ")" ]
Compute fixed point residual.
[ "Compute", "fixed", "point", "residual", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/fista/bpdn.py#L226-L229
train
210,131
bwohlberg/sporco
sporco/fista/cbpdn.py
ConvBPDN.eval_Rf
def eval_Rf(self, Vf): """Evaluate smooth term in Vf.""" return sl.inner(self.Df, Vf, axis=self.cri.axisM) - self.Sf
python
def eval_Rf(self, Vf): """Evaluate smooth term in Vf.""" return sl.inner(self.Df, Vf, axis=self.cri.axisM) - self.Sf
[ "def", "eval_Rf", "(", "self", ",", "Vf", ")", ":", "return", "sl", ".", "inner", "(", "self", ".", "Df", ",", "Vf", ",", "axis", "=", "self", ".", "cri", ".", "axisM", ")", "-", "self", ".", "Sf" ]
Evaluate smooth term in Vf.
[ "Evaluate", "smooth", "term", "in", "Vf", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/fista/cbpdn.py#L281-L284
train
210,132
bwohlberg/sporco
sporco/cnvrep.py
zpad
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 """ 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
python
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 """ 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", ")", ":", "vp", "=", "np", ".", "zeros", "(", "Nv", "+", "v", ".", "shape", "[", "len", "(", "Nv", ")", ":", "]", ",", "dtype", "=", "v", ".", "dtype", ")", "axnslc", "=", "tuple", "(", "[", "slice", "(...
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
[ "Zero", "-", "pad", "initial", "axes", "of", "array", "to", "specified", "size", ".", "Padding", "is", "applied", "to", "the", "right", "top", "etc", ".", "of", "the", "array", "indices", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cnvrep.py#L681-L701
train
210,133
bwohlberg/sporco
sporco/cnvrep.py
Pcn
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 """ 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)
python
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 """ 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", ")", ":", "if", "crp", ":", "def", "zpadfn", "(", "x", ")", ":", "return", "x", "else", ":", "...
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
[ "Constraint", "set", "projection", "for", "convolutional", "dictionary", "update", "problem", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cnvrep.py#L842-L886
train
210,134
bwohlberg/sporco
sporco/cnvrep.py
getPcn
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 """ 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)
python
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 """ 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", ")", ":", "fncdict", "=", "{", "(", "False", ",", "False", ")", ":", "_Pcn", ",", "(", "False", ",", "T...
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
[ "Construct", "the", "constraint", "set", "projection", "function", "for", "convolutional", "dictionary", "update", "problem", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cnvrep.py#L890-L923
train
210,135
bwohlberg/sporco
sporco/util.py
tiledict
def tiledict(D, sz=None): """Construct an image allowing visualization of dictionary content. Parameters ---------- D : array_like Dictionary matrix/array. sz : tuple Size of each block in dictionary. Returns ------- im : ndarray Image tiled with dictionary entries. """ # Handle standard 2D (non-convolutional) dictionary if D.ndim == 2: D = D.reshape((sz + (D.shape[1],))) sz = None dsz = D.shape if D.ndim == 4: axisM = 3 szni = 3 else: axisM = 2 szni = 2 # Construct dictionary atom size vector if not provided if sz is None: sz = np.tile(np.array(dsz[0:2]).reshape([2, 1]), (1, D.shape[axisM])) else: sz = np.array(sum(tuple((x[0:2],) * x[szni] for x in sz), ())).T # Compute the maximum atom dimensions mxsz = np.amax(sz, 1) # Shift and scale values to [0, 1] D = D - D.min() D = D / D.max() # Construct tiled image N = dsz[axisM] Vr = int(np.floor(np.sqrt(N))) Vc = int(np.ceil(N / float(Vr))) if D.ndim == 4: im = np.ones((Vr*mxsz[0] + Vr - 1, Vc*mxsz[1] + Vc - 1, dsz[2])) else: im = np.ones((Vr*mxsz[0] + Vr - 1, Vc*mxsz[1] + Vc - 1)) k = 0 for l in range(0, Vr): for m in range(0, Vc): r = mxsz[0]*l + l c = mxsz[1]*m + m if D.ndim == 4: im[r:(r+sz[0, k]), c:(c+sz[1, k]), :] = D[0:sz[0, k], 0:sz[1, k], :, k] else: im[r:(r+sz[0, k]), c:(c+sz[1, k])] = D[0:sz[0, k], 0:sz[1, k], k] k = k + 1 if k >= N: break if k >= N: break return im
python
def tiledict(D, sz=None): """Construct an image allowing visualization of dictionary content. Parameters ---------- D : array_like Dictionary matrix/array. sz : tuple Size of each block in dictionary. Returns ------- im : ndarray Image tiled with dictionary entries. """ # Handle standard 2D (non-convolutional) dictionary if D.ndim == 2: D = D.reshape((sz + (D.shape[1],))) sz = None dsz = D.shape if D.ndim == 4: axisM = 3 szni = 3 else: axisM = 2 szni = 2 # Construct dictionary atom size vector if not provided if sz is None: sz = np.tile(np.array(dsz[0:2]).reshape([2, 1]), (1, D.shape[axisM])) else: sz = np.array(sum(tuple((x[0:2],) * x[szni] for x in sz), ())).T # Compute the maximum atom dimensions mxsz = np.amax(sz, 1) # Shift and scale values to [0, 1] D = D - D.min() D = D / D.max() # Construct tiled image N = dsz[axisM] Vr = int(np.floor(np.sqrt(N))) Vc = int(np.ceil(N / float(Vr))) if D.ndim == 4: im = np.ones((Vr*mxsz[0] + Vr - 1, Vc*mxsz[1] + Vc - 1, dsz[2])) else: im = np.ones((Vr*mxsz[0] + Vr - 1, Vc*mxsz[1] + Vc - 1)) k = 0 for l in range(0, Vr): for m in range(0, Vc): r = mxsz[0]*l + l c = mxsz[1]*m + m if D.ndim == 4: im[r:(r+sz[0, k]), c:(c+sz[1, k]), :] = D[0:sz[0, k], 0:sz[1, k], :, k] else: im[r:(r+sz[0, k]), c:(c+sz[1, k])] = D[0:sz[0, k], 0:sz[1, k], k] k = k + 1 if k >= N: break if k >= N: break return im
[ "def", "tiledict", "(", "D", ",", "sz", "=", "None", ")", ":", "# Handle standard 2D (non-convolutional) dictionary", "if", "D", ".", "ndim", "==", "2", ":", "D", "=", "D", ".", "reshape", "(", "(", "sz", "+", "(", "D", ".", "shape", "[", "1", "]", ...
Construct an image allowing visualization of dictionary content. Parameters ---------- D : array_like Dictionary matrix/array. sz : tuple Size of each block in dictionary. Returns ------- im : ndarray Image tiled with dictionary entries.
[ "Construct", "an", "image", "allowing", "visualization", "of", "dictionary", "content", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L125-L192
train
210,136
bwohlberg/sporco
sporco/util.py
extractblocks
def extractblocks(img, blksz, stpsz=None): """Extract blocks from an ndarray signal into an ndarray. Parameters ---------- img : ndarray or tuple of ndarrays nd array of images, or tuple of images blksz : tuple tuple of block sizes, blocks are taken starting from the first index of img stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks Returns ------- blks : ndarray image blocks """ # See http://stackoverflow.com/questions/16774148 and # sklearn.feature_extraction.image.extract_patches_2d if isinstance(img, tuple): img = np.stack(img, axis=-1) if stpsz is None: stpsz = (1,) * len(blksz) imgsz = img.shape # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple(int(np.floor((a - b) / c) + 1) for a, b, c in zip_longest(imgsz, blksz, stpsz, fillvalue=1)) # Calculate the strides for blocks blockstrides = tuple(a * b for a, b in zip_longest(img.strides, stpsz, fillvalue=1)) new_shape = blksz + numblocks new_strides = img.strides[:len(blksz)] + blockstrides blks = np.lib.stride_tricks.as_strided(img, new_shape, new_strides) return np.reshape(blks, blksz + (-1,))
python
def extractblocks(img, blksz, stpsz=None): """Extract blocks from an ndarray signal into an ndarray. Parameters ---------- img : ndarray or tuple of ndarrays nd array of images, or tuple of images blksz : tuple tuple of block sizes, blocks are taken starting from the first index of img stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks Returns ------- blks : ndarray image blocks """ # See http://stackoverflow.com/questions/16774148 and # sklearn.feature_extraction.image.extract_patches_2d if isinstance(img, tuple): img = np.stack(img, axis=-1) if stpsz is None: stpsz = (1,) * len(blksz) imgsz = img.shape # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple(int(np.floor((a - b) / c) + 1) for a, b, c in zip_longest(imgsz, blksz, stpsz, fillvalue=1)) # Calculate the strides for blocks blockstrides = tuple(a * b for a, b in zip_longest(img.strides, stpsz, fillvalue=1)) new_shape = blksz + numblocks new_strides = img.strides[:len(blksz)] + blockstrides blks = np.lib.stride_tricks.as_strided(img, new_shape, new_strides) return np.reshape(blks, blksz + (-1,))
[ "def", "extractblocks", "(", "img", ",", "blksz", ",", "stpsz", "=", "None", ")", ":", "# See http://stackoverflow.com/questions/16774148 and", "# sklearn.feature_extraction.image.extract_patches_2d", "if", "isinstance", "(", "img", ",", "tuple", ")", ":", "img", "=", ...
Extract blocks from an ndarray signal into an ndarray. Parameters ---------- img : ndarray or tuple of ndarrays nd array of images, or tuple of images blksz : tuple tuple of block sizes, blocks are taken starting from the first index of img stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks Returns ------- blks : ndarray image blocks
[ "Extract", "blocks", "from", "an", "ndarray", "signal", "into", "an", "ndarray", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L285-L326
train
210,137
bwohlberg/sporco
sporco/util.py
averageblocks
def averageblocks(blks, imgsz, stpsz=None): """Average blocks together from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks Returns ------- imgs : ndarray reconstructed signal, unknown pixels are returned as np.nan """ blksz = blks.shape[:-1] if stpsz is None: stpsz = tuple(1 for _ in blksz) # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple(int(np.floor((a-b)/c)+1) for a, b, c in zip_longest(imgsz, blksz, stpsz, fillvalue=1)) new_shape = blksz + numblocks blks = np.reshape(blks, new_shape) # Construct an imgs matrix of empty lists imgs = np.zeros(imgsz, dtype=blks.dtype) normalizer = np.zeros(imgsz, dtype=blks.dtype) # Iterate over each block and append the values to the corresponding # imgs cell for pos in np.ndindex(numblocks): slices = tuple(slice(a*c, a*c+b) for a, b, c in zip(pos, blksz, stpsz)) imgs[slices+pos[len(blksz):]] += blks[(Ellipsis, )+pos] normalizer[slices+pos[len(blksz):]] += blks.dtype.type(1) return np.where(normalizer > 0, (imgs/normalizer).astype(blks.dtype), np.nan)
python
def averageblocks(blks, imgsz, stpsz=None): """Average blocks together from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks Returns ------- imgs : ndarray reconstructed signal, unknown pixels are returned as np.nan """ blksz = blks.shape[:-1] if stpsz is None: stpsz = tuple(1 for _ in blksz) # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple(int(np.floor((a-b)/c)+1) for a, b, c in zip_longest(imgsz, blksz, stpsz, fillvalue=1)) new_shape = blksz + numblocks blks = np.reshape(blks, new_shape) # Construct an imgs matrix of empty lists imgs = np.zeros(imgsz, dtype=blks.dtype) normalizer = np.zeros(imgsz, dtype=blks.dtype) # Iterate over each block and append the values to the corresponding # imgs cell for pos in np.ndindex(numblocks): slices = tuple(slice(a*c, a*c+b) for a, b, c in zip(pos, blksz, stpsz)) imgs[slices+pos[len(blksz):]] += blks[(Ellipsis, )+pos] normalizer[slices+pos[len(blksz):]] += blks.dtype.type(1) return np.where(normalizer > 0, (imgs/normalizer).astype(blks.dtype), np.nan)
[ "def", "averageblocks", "(", "blks", ",", "imgsz", ",", "stpsz", "=", "None", ")", ":", "blksz", "=", "blks", ".", "shape", "[", ":", "-", "1", "]", "if", "stpsz", "is", "None", ":", "stpsz", "=", "tuple", "(", "1", "for", "_", "in", "blksz", "...
Average blocks together from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks Returns ------- imgs : ndarray reconstructed signal, unknown pixels are returned as np.nan
[ "Average", "blocks", "together", "from", "an", "ndarray", "to", "reconstruct", "ndarray", "signal", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L330-L375
train
210,138
bwohlberg/sporco
sporco/util.py
combineblocks
def combineblocks(blks, imgsz, stpsz=None, fn=np.median): """Combine blocks from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks fn : function, optional (default np.median) the function used to resolve multivalued cells Returns ------- imgs : ndarray reconstructed signal, unknown pixels are returned as np.nan """ # Construct a vectorized append function def listapp(x, y): x.append(y) veclistapp = np.vectorize(listapp, otypes=[np.object_]) blksz = blks.shape[:-1] if stpsz is None: stpsz = tuple(1 for _ in blksz) # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple(int(np.floor((a-b)/c) + 1) for a, b, c in zip_longest(imgsz, blksz, stpsz, fillvalue=1)) new_shape = blksz + numblocks blks = np.reshape(blks, new_shape) # Construct an imgs matrix of empty lists imgs = np.empty(imgsz, dtype=np.object_) imgs.fill([]) imgs = np.frompyfunc(list, 1, 1)(imgs) # Iterate over each block and append the values to the corresponding # imgs cell for pos in np.ndindex(numblocks): slices = tuple(slice(a*c, a*c + b) for a, b, c in zip_longest(pos, blksz, stpsz, fillvalue=1)) veclistapp(imgs[slices].squeeze(), blks[(Ellipsis, ) + pos].squeeze()) return np.vectorize(fn, otypes=[blks.dtype])(imgs)
python
def combineblocks(blks, imgsz, stpsz=None, fn=np.median): """Combine blocks from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks fn : function, optional (default np.median) the function used to resolve multivalued cells Returns ------- imgs : ndarray reconstructed signal, unknown pixels are returned as np.nan """ # Construct a vectorized append function def listapp(x, y): x.append(y) veclistapp = np.vectorize(listapp, otypes=[np.object_]) blksz = blks.shape[:-1] if stpsz is None: stpsz = tuple(1 for _ in blksz) # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple(int(np.floor((a-b)/c) + 1) for a, b, c in zip_longest(imgsz, blksz, stpsz, fillvalue=1)) new_shape = blksz + numblocks blks = np.reshape(blks, new_shape) # Construct an imgs matrix of empty lists imgs = np.empty(imgsz, dtype=np.object_) imgs.fill([]) imgs = np.frompyfunc(list, 1, 1)(imgs) # Iterate over each block and append the values to the corresponding # imgs cell for pos in np.ndindex(numblocks): slices = tuple(slice(a*c, a*c + b) for a, b, c in zip_longest(pos, blksz, stpsz, fillvalue=1)) veclistapp(imgs[slices].squeeze(), blks[(Ellipsis, ) + pos].squeeze()) return np.vectorize(fn, otypes=[blks.dtype])(imgs)
[ "def", "combineblocks", "(", "blks", ",", "imgsz", ",", "stpsz", "=", "None", ",", "fn", "=", "np", ".", "median", ")", ":", "# Construct a vectorized append function", "def", "listapp", "(", "x", ",", "y", ")", ":", "x", ".", "append", "(", "y", ")", ...
Combine blocks from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks fn : function, optional (default np.median) the function used to resolve multivalued cells Returns ------- imgs : ndarray reconstructed signal, unknown pixels are returned as np.nan
[ "Combine", "blocks", "from", "an", "ndarray", "to", "reconstruct", "ndarray", "signal", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L379-L429
train
210,139
bwohlberg/sporco
sporco/util.py
complex_randn
def complex_randn(*args): """Return a complex array of samples drawn from a standard normal distribution. Parameters ---------- d0, d1, ..., dn : int Dimensions of the random array Returns ------- a : ndarray Random array of shape (d0, d1, ..., dn) """ return np.random.randn(*args) + 1j*np.random.randn(*args)
python
def complex_randn(*args): """Return a complex array of samples drawn from a standard normal distribution. Parameters ---------- d0, d1, ..., dn : int Dimensions of the random array Returns ------- a : ndarray Random array of shape (d0, d1, ..., dn) """ return np.random.randn(*args) + 1j*np.random.randn(*args)
[ "def", "complex_randn", "(", "*", "args", ")", ":", "return", "np", ".", "random", ".", "randn", "(", "*", "args", ")", "+", "1j", "*", "np", ".", "random", ".", "randn", "(", "*", "args", ")" ]
Return a complex array of samples drawn from a standard normal distribution. Parameters ---------- d0, d1, ..., dn : int Dimensions of the random array Returns ------- a : ndarray Random array of shape (d0, d1, ..., dn)
[ "Return", "a", "complex", "array", "of", "samples", "drawn", "from", "a", "standard", "normal", "distribution", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L453-L468
train
210,140
bwohlberg/sporco
sporco/util.py
spnoise
def spnoise(s, frc, smn=0.0, smx=1.0): """Return image with salt & pepper noise imposed on it. Parameters ---------- s : ndarray Input image frc : float Desired fraction of pixels corrupted by noise smn : float, optional (default 0.0) Lower value for noise (pepper) smx : float, optional (default 1.0) Upper value for noise (salt) Returns ------- sn : ndarray Noisy image """ sn = s.copy() spm = np.random.uniform(-1.0, 1.0, s.shape) sn[spm < frc - 1.0] = smn sn[spm > 1.0 - frc] = smx return sn
python
def spnoise(s, frc, smn=0.0, smx=1.0): """Return image with salt & pepper noise imposed on it. Parameters ---------- s : ndarray Input image frc : float Desired fraction of pixels corrupted by noise smn : float, optional (default 0.0) Lower value for noise (pepper) smx : float, optional (default 1.0) Upper value for noise (salt) Returns ------- sn : ndarray Noisy image """ sn = s.copy() spm = np.random.uniform(-1.0, 1.0, s.shape) sn[spm < frc - 1.0] = smn sn[spm > 1.0 - frc] = smx return sn
[ "def", "spnoise", "(", "s", ",", "frc", ",", "smn", "=", "0.0", ",", "smx", "=", "1.0", ")", ":", "sn", "=", "s", ".", "copy", "(", ")", "spm", "=", "np", ".", "random", ".", "uniform", "(", "-", "1.0", ",", "1.0", ",", "s", ".", "shape", ...
Return image with salt & pepper noise imposed on it. Parameters ---------- s : ndarray Input image frc : float Desired fraction of pixels corrupted by noise smn : float, optional (default 0.0) Lower value for noise (pepper) smx : float, optional (default 1.0) Upper value for noise (salt) Returns ------- sn : ndarray Noisy image
[ "Return", "image", "with", "salt", "&", "pepper", "noise", "imposed", "on", "it", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L472-L496
train
210,141
bwohlberg/sporco
sporco/util.py
pca
def pca(U, centre=False): """Compute the PCA basis for columns of input array `U`. Parameters ---------- U : array_like 2D data array with rows corresponding to different variables and columns corresponding to different observations center : bool, optional (default False) Flag indicating whether to centre data Returns ------- B : ndarray A 2D array representing the PCA basis; each column is a PCA component. B.T is the analysis transform into the PCA representation, and B is the corresponding synthesis transform S : ndarray The eigenvalues of the PCA components C : ndarray or None None if centering is disabled, otherwise the mean of the data matrix subtracted in performing the centering """ if centre: C = np.mean(U, axis=1, keepdims=True) U = U - C else: C = None B, S, _ = np.linalg.svd(U, full_matrices=False, compute_uv=True) return B, S**2, C
python
def pca(U, centre=False): """Compute the PCA basis for columns of input array `U`. Parameters ---------- U : array_like 2D data array with rows corresponding to different variables and columns corresponding to different observations center : bool, optional (default False) Flag indicating whether to centre data Returns ------- B : ndarray A 2D array representing the PCA basis; each column is a PCA component. B.T is the analysis transform into the PCA representation, and B is the corresponding synthesis transform S : ndarray The eigenvalues of the PCA components C : ndarray or None None if centering is disabled, otherwise the mean of the data matrix subtracted in performing the centering """ if centre: C = np.mean(U, axis=1, keepdims=True) U = U - C else: C = None B, S, _ = np.linalg.svd(U, full_matrices=False, compute_uv=True) return B, S**2, C
[ "def", "pca", "(", "U", ",", "centre", "=", "False", ")", ":", "if", "centre", ":", "C", "=", "np", ".", "mean", "(", "U", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "U", "=", "U", "-", "C", "else", ":", "C", "=", "None", "...
Compute the PCA basis for columns of input array `U`. Parameters ---------- U : array_like 2D data array with rows corresponding to different variables and columns corresponding to different observations center : bool, optional (default False) Flag indicating whether to centre data Returns ------- B : ndarray A 2D array representing the PCA basis; each column is a PCA component. B.T is the analysis transform into the PCA representation, and B is the corresponding synthesis transform S : ndarray The eigenvalues of the PCA components C : ndarray or None None if centering is disabled, otherwise the mean of the data matrix subtracted in performing the centering
[ "Compute", "the", "PCA", "basis", "for", "columns", "of", "input", "array", "U", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L525-L557
train
210,142
bwohlberg/sporco
sporco/util.py
tikhonov_filter
def tikhonov_filter(s, lmbda, npd=16): r"""Lowpass filter based on Tikhonov regularization. Lowpass filter image(s) and return low and high frequency components, consisting of the lowpass filtered image and its difference with the input image. The lowpass filter is equivalent to Tikhonov regularization with `lmbda` as the regularization parameter and a discrete gradient as the operator in the regularization term, i.e. the lowpass component is the solution to .. math:: \mathrm{argmin}_\mathbf{x} \; (1/2) \left\|\mathbf{x} - \mathbf{s} \right\|_2^2 + (\lambda / 2) \sum_i \| G_i \mathbf{x} \|_2^2 \;\;, where :math:`\mathbf{s}` is the input image, :math:`\lambda` is the regularization parameter, and :math:`G_i` is an operator that computes the discrete gradient along image axis :math:`i`. Once the lowpass component :math:`\mathbf{x}` has been computed, the highpass component is just :math:`\mathbf{s} - \mathbf{x}`. Parameters ---------- s : array_like Input image or array of images. lmbda : float Regularization parameter controlling lowpass filtering. npd : int, optional (default=16) Number of samples to pad at image boundaries. Returns ------- sl : array_like Lowpass image or array of images. sh : array_like Highpass image or array of images. """ grv = np.array([-1.0, 1.0]).reshape([2, 1]) gcv = np.array([-1.0, 1.0]).reshape([1, 2]) Gr = sla.fftn(grv, (s.shape[0] + 2*npd, s.shape[1] + 2*npd), (0, 1)) Gc = sla.fftn(gcv, (s.shape[0] + 2*npd, s.shape[1] + 2*npd), (0, 1)) A = 1.0 + lmbda*np.conj(Gr)*Gr + lmbda*np.conj(Gc)*Gc if s.ndim > 2: A = A[(slice(None),)*2 + (np.newaxis,)*(s.ndim-2)] sp = np.pad(s, ((npd, npd),)*2 + ((0, 0),)*(s.ndim-2), 'symmetric') slp = np.real(sla.ifftn(sla.fftn(sp, axes=(0, 1)) / A, axes=(0, 1))) sl = slp[npd:(slp.shape[0] - npd), npd:(slp.shape[1] - npd)] sh = s - sl return sl.astype(s.dtype), sh.astype(s.dtype)
python
def tikhonov_filter(s, lmbda, npd=16): r"""Lowpass filter based on Tikhonov regularization. Lowpass filter image(s) and return low and high frequency components, consisting of the lowpass filtered image and its difference with the input image. The lowpass filter is equivalent to Tikhonov regularization with `lmbda` as the regularization parameter and a discrete gradient as the operator in the regularization term, i.e. the lowpass component is the solution to .. math:: \mathrm{argmin}_\mathbf{x} \; (1/2) \left\|\mathbf{x} - \mathbf{s} \right\|_2^2 + (\lambda / 2) \sum_i \| G_i \mathbf{x} \|_2^2 \;\;, where :math:`\mathbf{s}` is the input image, :math:`\lambda` is the regularization parameter, and :math:`G_i` is an operator that computes the discrete gradient along image axis :math:`i`. Once the lowpass component :math:`\mathbf{x}` has been computed, the highpass component is just :math:`\mathbf{s} - \mathbf{x}`. Parameters ---------- s : array_like Input image or array of images. lmbda : float Regularization parameter controlling lowpass filtering. npd : int, optional (default=16) Number of samples to pad at image boundaries. Returns ------- sl : array_like Lowpass image or array of images. sh : array_like Highpass image or array of images. """ grv = np.array([-1.0, 1.0]).reshape([2, 1]) gcv = np.array([-1.0, 1.0]).reshape([1, 2]) Gr = sla.fftn(grv, (s.shape[0] + 2*npd, s.shape[1] + 2*npd), (0, 1)) Gc = sla.fftn(gcv, (s.shape[0] + 2*npd, s.shape[1] + 2*npd), (0, 1)) A = 1.0 + lmbda*np.conj(Gr)*Gr + lmbda*np.conj(Gc)*Gc if s.ndim > 2: A = A[(slice(None),)*2 + (np.newaxis,)*(s.ndim-2)] sp = np.pad(s, ((npd, npd),)*2 + ((0, 0),)*(s.ndim-2), 'symmetric') slp = np.real(sla.ifftn(sla.fftn(sp, axes=(0, 1)) / A, axes=(0, 1))) sl = slp[npd:(slp.shape[0] - npd), npd:(slp.shape[1] - npd)] sh = s - sl return sl.astype(s.dtype), sh.astype(s.dtype)
[ "def", "tikhonov_filter", "(", "s", ",", "lmbda", ",", "npd", "=", "16", ")", ":", "grv", "=", "np", ".", "array", "(", "[", "-", "1.0", ",", "1.0", "]", ")", ".", "reshape", "(", "[", "2", ",", "1", "]", ")", "gcv", "=", "np", ".", "array"...
r"""Lowpass filter based on Tikhonov regularization. Lowpass filter image(s) and return low and high frequency components, consisting of the lowpass filtered image and its difference with the input image. The lowpass filter is equivalent to Tikhonov regularization with `lmbda` as the regularization parameter and a discrete gradient as the operator in the regularization term, i.e. the lowpass component is the solution to .. math:: \mathrm{argmin}_\mathbf{x} \; (1/2) \left\|\mathbf{x} - \mathbf{s} \right\|_2^2 + (\lambda / 2) \sum_i \| G_i \mathbf{x} \|_2^2 \;\;, where :math:`\mathbf{s}` is the input image, :math:`\lambda` is the regularization parameter, and :math:`G_i` is an operator that computes the discrete gradient along image axis :math:`i`. Once the lowpass component :math:`\mathbf{x}` has been computed, the highpass component is just :math:`\mathbf{s} - \mathbf{x}`. Parameters ---------- s : array_like Input image or array of images. lmbda : float Regularization parameter controlling lowpass filtering. npd : int, optional (default=16) Number of samples to pad at image boundaries. Returns ------- sl : array_like Lowpass image or array of images. sh : array_like Highpass image or array of images.
[ "r", "Lowpass", "filter", "based", "on", "Tikhonov", "regularization", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L561-L609
train
210,143
bwohlberg/sporco
sporco/util.py
gaussian
def gaussian(shape, sd=1.0): """Sample a multivariate Gaussian pdf, normalised to have unit sum. Parameters ---------- shape : tuple Shape of output array. sd : float, optional (default 1.0) Standard deviation of Gaussian pdf. Returns ------- gc : ndarray Sampled Gaussian pdf. """ gfn = lambda x, sd: np.exp(-(x**2) / (2.0 * sd**2)) / \ (np.sqrt(2.0 * np.pi) *sd) gc = 1.0 if isinstance(shape, int): shape = (shape,) for k, n in enumerate(shape): x = np.linspace(-3.0, 3.0, n).reshape( (1,) * k + (n,) + (1,) * (len(shape) - k - 1)) gc = gc * gfn(x, sd) gc /= np.sum(gc) return gc
python
def gaussian(shape, sd=1.0): """Sample a multivariate Gaussian pdf, normalised to have unit sum. Parameters ---------- shape : tuple Shape of output array. sd : float, optional (default 1.0) Standard deviation of Gaussian pdf. Returns ------- gc : ndarray Sampled Gaussian pdf. """ gfn = lambda x, sd: np.exp(-(x**2) / (2.0 * sd**2)) / \ (np.sqrt(2.0 * np.pi) *sd) gc = 1.0 if isinstance(shape, int): shape = (shape,) for k, n in enumerate(shape): x = np.linspace(-3.0, 3.0, n).reshape( (1,) * k + (n,) + (1,) * (len(shape) - k - 1)) gc = gc * gfn(x, sd) gc /= np.sum(gc) return gc
[ "def", "gaussian", "(", "shape", ",", "sd", "=", "1.0", ")", ":", "gfn", "=", "lambda", "x", ",", "sd", ":", "np", ".", "exp", "(", "-", "(", "x", "**", "2", ")", "/", "(", "2.0", "*", "sd", "**", "2", ")", ")", "/", "(", "np", ".", "sq...
Sample a multivariate Gaussian pdf, normalised to have unit sum. Parameters ---------- shape : tuple Shape of output array. sd : float, optional (default 1.0) Standard deviation of Gaussian pdf. Returns ------- gc : ndarray Sampled Gaussian pdf.
[ "Sample", "a", "multivariate", "Gaussian", "pdf", "normalised", "to", "have", "unit", "sum", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L613-L639
train
210,144
bwohlberg/sporco
sporco/util.py
convdicts
def convdicts(): """Access a set of example learned convolutional dictionaries. Returns ------- cdd : dict A dict associating description strings with dictionaries represented as ndarrays Examples -------- Print the dict keys to obtain the identifiers of the available dictionaries >>> from sporco import util >>> cd = util.convdicts() >>> print(cd.keys()) ['G:12x12x72', 'G:8x8x16,12x12x32,16x16x48', ...] Select a specific example dictionary using the corresponding identifier >>> D = cd['G:8x8x96'] """ pth = os.path.join(os.path.dirname(__file__), 'data', 'convdict.npz') npz = np.load(pth) cdd = {} for k in list(npz.keys()): cdd[k] = npz[k] return cdd
python
def convdicts(): """Access a set of example learned convolutional dictionaries. Returns ------- cdd : dict A dict associating description strings with dictionaries represented as ndarrays Examples -------- Print the dict keys to obtain the identifiers of the available dictionaries >>> from sporco import util >>> cd = util.convdicts() >>> print(cd.keys()) ['G:12x12x72', 'G:8x8x16,12x12x32,16x16x48', ...] Select a specific example dictionary using the corresponding identifier >>> D = cd['G:8x8x96'] """ pth = os.path.join(os.path.dirname(__file__), 'data', 'convdict.npz') npz = np.load(pth) cdd = {} for k in list(npz.keys()): cdd[k] = npz[k] return cdd
[ "def", "convdicts", "(", ")", ":", "pth", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'data'", ",", "'convdict.npz'", ")", "npz", "=", "np", ".", "load", "(", "pth", ")", "cdd", "=", ...
Access a set of example learned convolutional dictionaries. Returns ------- cdd : dict A dict associating description strings with dictionaries represented as ndarrays Examples -------- Print the dict keys to obtain the identifiers of the available dictionaries >>> from sporco import util >>> cd = util.convdicts() >>> print(cd.keys()) ['G:12x12x72', 'G:8x8x16,12x12x32,16x16x48', ...] Select a specific example dictionary using the corresponding identifier >>> D = cd['G:8x8x96']
[ "Access", "a", "set", "of", "example", "learned", "convolutional", "dictionaries", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L803-L832
train
210,145
bwohlberg/sporco
sporco/util.py
netgetdata
def netgetdata(url, maxtry=3, timeout=10): """ Get content of a file via a URL. Parameters ---------- url : string URL of the file to be downloaded maxtry : int, optional (default 3) Maximum number of download retries timeout : int, optional (default 10) Timeout in seconds for blocking operations Returns ------- str : io.BytesIO Buffered I/O stream Raises ------ urlerror.URLError (urllib2.URLError in Python 2, urllib.error.URLError in Python 3) If the file cannot be downloaded """ err = ValueError('maxtry parameter should be greater than zero') for ntry in range(maxtry): try: rspns = urlrequest.urlopen(url, timeout=timeout) cntnt = rspns.read() break except urlerror.URLError as e: err = e if not isinstance(e.reason, socket.timeout): raise else: raise err return io.BytesIO(cntnt)
python
def netgetdata(url, maxtry=3, timeout=10): """ Get content of a file via a URL. Parameters ---------- url : string URL of the file to be downloaded maxtry : int, optional (default 3) Maximum number of download retries timeout : int, optional (default 10) Timeout in seconds for blocking operations Returns ------- str : io.BytesIO Buffered I/O stream Raises ------ urlerror.URLError (urllib2.URLError in Python 2, urllib.error.URLError in Python 3) If the file cannot be downloaded """ err = ValueError('maxtry parameter should be greater than zero') for ntry in range(maxtry): try: rspns = urlrequest.urlopen(url, timeout=timeout) cntnt = rspns.read() break except urlerror.URLError as e: err = e if not isinstance(e.reason, socket.timeout): raise else: raise err return io.BytesIO(cntnt)
[ "def", "netgetdata", "(", "url", ",", "maxtry", "=", "3", ",", "timeout", "=", "10", ")", ":", "err", "=", "ValueError", "(", "'maxtry parameter should be greater than zero'", ")", "for", "ntry", "in", "range", "(", "maxtry", ")", ":", "try", ":", "rspns",...
Get content of a file via a URL. Parameters ---------- url : string URL of the file to be downloaded maxtry : int, optional (default 3) Maximum number of download retries timeout : int, optional (default 10) Timeout in seconds for blocking operations Returns ------- str : io.BytesIO Buffered I/O stream Raises ------ urlerror.URLError (urllib2.URLError in Python 2, urllib.error.URLError in Python 3) If the file cannot be downloaded
[ "Get", "content", "of", "a", "file", "via", "a", "URL", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L836-L874
train
210,146
bwohlberg/sporco
sporco/util.py
ExampleImages.image
def image(self, fname, group=None, scaled=None, dtype=None, idxexp=None, zoom=None, gray=None): """Get named image. Parameters ---------- fname : string Filename of image group : string or None, optional (default None) Name of image group scaled : bool or None, optional (default None) Flag indicating whether images should be on the range [0,...,255] with np.uint8 dtype (False), or on the range [0,...,1] with np.float32 dtype (True). If the value is None, scaling behaviour is determined by the `scaling` parameter passed to the object initializer, otherwise that selection is overridden. dtype : data-type or None, optional (default None) Desired data type of images. If `scaled` is True and `dtype` is an integer type, the output data type is np.float32. If the value is None, the data type is determined by the `dtype` parameter passed to the object initializer, otherwise that selection is overridden. idxexp : index expression or None, optional (default None) An index expression selecting, for example, a cropped region of the requested image. This selection is applied *before* any `zoom` rescaling so the expression does not need to be modified when the zoom factor is changed. zoom : float or None, optional (default None) Optional rescaling factor to apply to the images. If the value is None, support rescaling behaviour is determined by the `zoom` parameter passed to the object initializer, otherwise that selection is overridden. gray : bool or None, optional (default None) Flag indicating whether RGB images should be converted to grayscale. If the value is None, behaviour is determined by the `gray` parameter passed to the object initializer. Returns ------- img : ndarray Image array Raises ------ IOError If the image is not accessible """ if scaled is None: scaled = self.scaled if dtype is None: if self.dtype is None: dtype = np.uint8 else: dtype = self.dtype if scaled and np.issubdtype(dtype, np.integer): dtype = np.float32 if zoom is None: zoom = self.zoom if gray is None: gray = self.gray if group is None: pth = os.path.join(self.bpth, fname) else: pth = os.path.join(self.bpth, group, fname) try: img = np.asarray(imageio.imread(pth), dtype=dtype) except IOError: raise IOError('Could not access image %s in group %s' % (fname, group)) if scaled: img /= 255.0 if idxexp is not None: img = img[idxexp] if zoom is not None: if img.ndim == 2: img = sni.zoom(img, zoom) else: img = sni.zoom(img, (zoom,)*2 + (1,)*(img.ndim-2)) if gray: img = rgb2gray(img) return img
python
def image(self, fname, group=None, scaled=None, dtype=None, idxexp=None, zoom=None, gray=None): """Get named image. Parameters ---------- fname : string Filename of image group : string or None, optional (default None) Name of image group scaled : bool or None, optional (default None) Flag indicating whether images should be on the range [0,...,255] with np.uint8 dtype (False), or on the range [0,...,1] with np.float32 dtype (True). If the value is None, scaling behaviour is determined by the `scaling` parameter passed to the object initializer, otherwise that selection is overridden. dtype : data-type or None, optional (default None) Desired data type of images. If `scaled` is True and `dtype` is an integer type, the output data type is np.float32. If the value is None, the data type is determined by the `dtype` parameter passed to the object initializer, otherwise that selection is overridden. idxexp : index expression or None, optional (default None) An index expression selecting, for example, a cropped region of the requested image. This selection is applied *before* any `zoom` rescaling so the expression does not need to be modified when the zoom factor is changed. zoom : float or None, optional (default None) Optional rescaling factor to apply to the images. If the value is None, support rescaling behaviour is determined by the `zoom` parameter passed to the object initializer, otherwise that selection is overridden. gray : bool or None, optional (default None) Flag indicating whether RGB images should be converted to grayscale. If the value is None, behaviour is determined by the `gray` parameter passed to the object initializer. Returns ------- img : ndarray Image array Raises ------ IOError If the image is not accessible """ if scaled is None: scaled = self.scaled if dtype is None: if self.dtype is None: dtype = np.uint8 else: dtype = self.dtype if scaled and np.issubdtype(dtype, np.integer): dtype = np.float32 if zoom is None: zoom = self.zoom if gray is None: gray = self.gray if group is None: pth = os.path.join(self.bpth, fname) else: pth = os.path.join(self.bpth, group, fname) try: img = np.asarray(imageio.imread(pth), dtype=dtype) except IOError: raise IOError('Could not access image %s in group %s' % (fname, group)) if scaled: img /= 255.0 if idxexp is not None: img = img[idxexp] if zoom is not None: if img.ndim == 2: img = sni.zoom(img, zoom) else: img = sni.zoom(img, (zoom,)*2 + (1,)*(img.ndim-2)) if gray: img = rgb2gray(img) return img
[ "def", "image", "(", "self", ",", "fname", ",", "group", "=", "None", ",", "scaled", "=", "None", ",", "dtype", "=", "None", ",", "idxexp", "=", "None", ",", "zoom", "=", "None", ",", "gray", "=", "None", ")", ":", "if", "scaled", "is", "None", ...
Get named image. Parameters ---------- fname : string Filename of image group : string or None, optional (default None) Name of image group scaled : bool or None, optional (default None) Flag indicating whether images should be on the range [0,...,255] with np.uint8 dtype (False), or on the range [0,...,1] with np.float32 dtype (True). If the value is None, scaling behaviour is determined by the `scaling` parameter passed to the object initializer, otherwise that selection is overridden. dtype : data-type or None, optional (default None) Desired data type of images. If `scaled` is True and `dtype` is an integer type, the output data type is np.float32. If the value is None, the data type is determined by the `dtype` parameter passed to the object initializer, otherwise that selection is overridden. idxexp : index expression or None, optional (default None) An index expression selecting, for example, a cropped region of the requested image. This selection is applied *before* any `zoom` rescaling so the expression does not need to be modified when the zoom factor is changed. zoom : float or None, optional (default None) Optional rescaling factor to apply to the images. If the value is None, support rescaling behaviour is determined by the `zoom` parameter passed to the object initializer, otherwise that selection is overridden. gray : bool or None, optional (default None) Flag indicating whether RGB images should be converted to grayscale. If the value is None, behaviour is determined by the `gray` parameter passed to the object initializer. Returns ------- img : ndarray Image array Raises ------ IOError If the image is not accessible
[ "Get", "named", "image", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L1045-L1128
train
210,147
bwohlberg/sporco
sporco/util.py
Timer.elapsed
def elapsed(self, label=None, total=True): """Get elapsed time since timer start. Parameters ---------- label : string, optional (default None) Specify the label of the timer for which the elapsed time is required. If it is ``None``, the default timer with label specified by the ``dfltlbl`` parameter of :meth:`__init__` is selected. total : bool, optional (default True) If ``True`` return the total elapsed time since the first call of :meth:`start` for the selected timer, otherwise return the elapsed time since the most recent call of :meth:`start` for which there has not been a corresponding call to :meth:`stop`. Returns ------- dlt : float Elapsed time """ # Get current time t = timer() # Default label is self.dfltlbl if label is None: label = self.dfltlbl # Return 0.0 if default timer selected and it is not initialised if label not in self.t0: return 0.0 # Raise exception if timer with specified label does not exist if label not in self.t0: raise KeyError('Unrecognized timer key %s' % label) # If total flag is True return sum of accumulated time from # previous start/stop calls and current start call, otherwise # return just the time since the current start call te = 0.0 if self.t0[label] is not None: te = t - self.t0[label] if total: te += self.td[label] return te
python
def elapsed(self, label=None, total=True): """Get elapsed time since timer start. Parameters ---------- label : string, optional (default None) Specify the label of the timer for which the elapsed time is required. If it is ``None``, the default timer with label specified by the ``dfltlbl`` parameter of :meth:`__init__` is selected. total : bool, optional (default True) If ``True`` return the total elapsed time since the first call of :meth:`start` for the selected timer, otherwise return the elapsed time since the most recent call of :meth:`start` for which there has not been a corresponding call to :meth:`stop`. Returns ------- dlt : float Elapsed time """ # Get current time t = timer() # Default label is self.dfltlbl if label is None: label = self.dfltlbl # Return 0.0 if default timer selected and it is not initialised if label not in self.t0: return 0.0 # Raise exception if timer with specified label does not exist if label not in self.t0: raise KeyError('Unrecognized timer key %s' % label) # If total flag is True return sum of accumulated time from # previous start/stop calls and current start call, otherwise # return just the time since the current start call te = 0.0 if self.t0[label] is not None: te = t - self.t0[label] if total: te += self.td[label] return te
[ "def", "elapsed", "(", "self", ",", "label", "=", "None", ",", "total", "=", "True", ")", ":", "# Get current time", "t", "=", "timer", "(", ")", "# Default label is self.dfltlbl", "if", "label", "is", "None", ":", "label", "=", "self", ".", "dfltlbl", "...
Get elapsed time since timer start. Parameters ---------- label : string, optional (default None) Specify the label of the timer for which the elapsed time is required. If it is ``None``, the default timer with label specified by the ``dfltlbl`` parameter of :meth:`__init__` is selected. total : bool, optional (default True) If ``True`` return the total elapsed time since the first call of :meth:`start` for the selected timer, otherwise return the elapsed time since the most recent call of :meth:`start` for which there has not been a corresponding call to :meth:`stop`. Returns ------- dlt : float Elapsed time
[ "Get", "elapsed", "time", "since", "timer", "start", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L1273-L1316
train
210,148
bwohlberg/sporco
sporco/util.py
ContextTimer.elapsed
def elapsed(self, total=True): """Return the elapsed time for the timer. Parameters ---------- total : bool, optional (default True) If ``True`` return the total elapsed time since the first call of :meth:`start` for the selected timer, otherwise return the elapsed time since the most recent call of :meth:`start` for which there has not been a corresponding call to :meth:`stop`. Returns ------- dlt : float Elapsed time """ return self.timer.elapsed(self.label, total=total)
python
def elapsed(self, total=True): """Return the elapsed time for the timer. Parameters ---------- total : bool, optional (default True) If ``True`` return the total elapsed time since the first call of :meth:`start` for the selected timer, otherwise return the elapsed time since the most recent call of :meth:`start` for which there has not been a corresponding call to :meth:`stop`. Returns ------- dlt : float Elapsed time """ return self.timer.elapsed(self.label, total=total)
[ "def", "elapsed", "(", "self", ",", "total", "=", "True", ")", ":", "return", "self", ".", "timer", ".", "elapsed", "(", "self", ".", "label", ",", "total", "=", "total", ")" ]
Return the elapsed time for the timer. Parameters ---------- total : bool, optional (default True) If ``True`` return the total elapsed time since the first call of :meth:`start` for the selected timer, otherwise return the elapsed time since the most recent call of :meth:`start` for which there has not been a corresponding call to :meth:`stop`. Returns ------- dlt : float Elapsed time
[ "Return", "the", "elapsed", "time", "for", "the", "timer", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L1438-L1456
train
210,149
bwohlberg/sporco
sporco/plot.py
attach_keypress
def attach_keypress(fig, scaling=1.1): """ Attach a key press event handler that configures keys for closing a figure and changing the figure size. Keys 'e' and 'c' respectively expand and contract the figure, and key 'q' closes it. **Note:** Resizing may not function correctly with all matplotlib backends (a `bug <https://github.com/matplotlib/matplotlib/issues/10083>`__ has been reported). Parameters ---------- fig : :class:`matplotlib.figure.Figure` object Figure to which event handling is to be attached scaling : float, optional (default 1.1) Scaling factor for figure size changes Returns ------- press : function Key press event handler function """ def press(event): if event.key == 'q': plt.close(fig) elif event.key == 'e': fig.set_size_inches(scaling * fig.get_size_inches(), forward=True) elif event.key == 'c': fig.set_size_inches(fig.get_size_inches() / scaling, forward=True) # Avoid multiple event handlers attached to the same figure if not hasattr(fig, '_sporco_keypress_cid'): cid = fig.canvas.mpl_connect('key_press_event', press) fig._sporco_keypress_cid = cid return press
python
def attach_keypress(fig, scaling=1.1): """ Attach a key press event handler that configures keys for closing a figure and changing the figure size. Keys 'e' and 'c' respectively expand and contract the figure, and key 'q' closes it. **Note:** Resizing may not function correctly with all matplotlib backends (a `bug <https://github.com/matplotlib/matplotlib/issues/10083>`__ has been reported). Parameters ---------- fig : :class:`matplotlib.figure.Figure` object Figure to which event handling is to be attached scaling : float, optional (default 1.1) Scaling factor for figure size changes Returns ------- press : function Key press event handler function """ def press(event): if event.key == 'q': plt.close(fig) elif event.key == 'e': fig.set_size_inches(scaling * fig.get_size_inches(), forward=True) elif event.key == 'c': fig.set_size_inches(fig.get_size_inches() / scaling, forward=True) # Avoid multiple event handlers attached to the same figure if not hasattr(fig, '_sporco_keypress_cid'): cid = fig.canvas.mpl_connect('key_press_event', press) fig._sporco_keypress_cid = cid return press
[ "def", "attach_keypress", "(", "fig", ",", "scaling", "=", "1.1", ")", ":", "def", "press", "(", "event", ")", ":", "if", "event", ".", "key", "==", "'q'", ":", "plt", ".", "close", "(", "fig", ")", "elif", "event", ".", "key", "==", "'e'", ":", ...
Attach a key press event handler that configures keys for closing a figure and changing the figure size. Keys 'e' and 'c' respectively expand and contract the figure, and key 'q' closes it. **Note:** Resizing may not function correctly with all matplotlib backends (a `bug <https://github.com/matplotlib/matplotlib/issues/10083>`__ has been reported). Parameters ---------- fig : :class:`matplotlib.figure.Figure` object Figure to which event handling is to be attached scaling : float, optional (default 1.1) Scaling factor for figure size changes Returns ------- press : function Key press event handler function
[ "Attach", "a", "key", "press", "event", "handler", "that", "configures", "keys", "for", "closing", "a", "figure", "and", "changing", "the", "figure", "size", ".", "Keys", "e", "and", "c", "respectively", "expand", "and", "contract", "the", "figure", "and", ...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/plot.py#L35-L72
train
210,150
bwohlberg/sporco
sporco/plot.py
attach_zoom
def attach_zoom(ax, scaling=2.0): """ Attach an event handler that supports zooming within a plot using the mouse scroll wheel. Parameters ---------- ax : :class:`matplotlib.axes.Axes` object Axes to which event handling is to be attached scaling : float, optional (default 2.0) Scaling factor for zooming in and out Returns ------- zoom : function Mouse scroll wheel event handler function """ # See https://stackoverflow.com/questions/11551049 def zoom(event): # Get the current x and y limits cur_xlim = ax.get_xlim() cur_ylim = ax.get_ylim() # Get event location xdata = event.xdata ydata = event.ydata # Return if cursor is not over valid region of plot if xdata is None or ydata is None: return if event.button == 'up': # Deal with zoom in scale_factor = 1.0 / scaling elif event.button == 'down': # Deal with zoom out scale_factor = scaling # Get distance from the cursor to the edge of the figure frame x_left = xdata - cur_xlim[0] x_right = cur_xlim[1] - xdata y_top = ydata - cur_ylim[0] y_bottom = cur_ylim[1] - ydata # Calculate new x and y limits new_xlim = (xdata - x_left * scale_factor, xdata + x_right * scale_factor) new_ylim = (ydata - y_top * scale_factor, ydata + y_bottom * scale_factor) # Ensure that x limit range is no larger than that of the reference if np.diff(new_xlim) > np.diff(zoom.xlim_ref): new_xlim *= np.diff(zoom.xlim_ref) / np.diff(new_xlim) # Ensure that lower x limit is not less than that of the reference if new_xlim[0] < zoom.xlim_ref[0]: new_xlim += np.array(zoom.xlim_ref[0] - new_xlim[0]) # Ensure that upper x limit is not greater than that of the reference if new_xlim[1] > zoom.xlim_ref[1]: new_xlim -= np.array(new_xlim[1] - zoom.xlim_ref[1]) # Ensure that ylim tuple has the smallest value first if zoom.ylim_ref[1] < zoom.ylim_ref[0]: ylim_ref = zoom.ylim_ref[::-1] new_ylim = new_ylim[::-1] else: ylim_ref = zoom.ylim_ref # Ensure that y limit range is no larger than that of the reference if np.diff(new_ylim) > np.diff(ylim_ref): new_ylim *= np.diff(ylim_ref) / np.diff(new_ylim) # Ensure that lower y limit is not less than that of the reference if new_ylim[0] < ylim_ref[0]: new_ylim += np.array(ylim_ref[0] - new_ylim[0]) # Ensure that upper y limit is not greater than that of the reference if new_ylim[1] > ylim_ref[1]: new_ylim -= np.array(new_ylim[1] - ylim_ref[1]) # Return the ylim tuple to its original order if zoom.ylim_ref[1] < zoom.ylim_ref[0]: new_ylim = new_ylim[::-1] # Set new x and y limits ax.set_xlim(new_xlim) ax.set_ylim(new_ylim) # Force redraw ax.figure.canvas.draw() # Record reference x and y limits prior to any zooming zoom.xlim_ref = ax.get_xlim() zoom.ylim_ref = ax.get_ylim() # Get figure for specified axes and attach the event handler fig = ax.get_figure() fig.canvas.mpl_connect('scroll_event', zoom) return zoom
python
def attach_zoom(ax, scaling=2.0): """ Attach an event handler that supports zooming within a plot using the mouse scroll wheel. Parameters ---------- ax : :class:`matplotlib.axes.Axes` object Axes to which event handling is to be attached scaling : float, optional (default 2.0) Scaling factor for zooming in and out Returns ------- zoom : function Mouse scroll wheel event handler function """ # See https://stackoverflow.com/questions/11551049 def zoom(event): # Get the current x and y limits cur_xlim = ax.get_xlim() cur_ylim = ax.get_ylim() # Get event location xdata = event.xdata ydata = event.ydata # Return if cursor is not over valid region of plot if xdata is None or ydata is None: return if event.button == 'up': # Deal with zoom in scale_factor = 1.0 / scaling elif event.button == 'down': # Deal with zoom out scale_factor = scaling # Get distance from the cursor to the edge of the figure frame x_left = xdata - cur_xlim[0] x_right = cur_xlim[1] - xdata y_top = ydata - cur_ylim[0] y_bottom = cur_ylim[1] - ydata # Calculate new x and y limits new_xlim = (xdata - x_left * scale_factor, xdata + x_right * scale_factor) new_ylim = (ydata - y_top * scale_factor, ydata + y_bottom * scale_factor) # Ensure that x limit range is no larger than that of the reference if np.diff(new_xlim) > np.diff(zoom.xlim_ref): new_xlim *= np.diff(zoom.xlim_ref) / np.diff(new_xlim) # Ensure that lower x limit is not less than that of the reference if new_xlim[0] < zoom.xlim_ref[0]: new_xlim += np.array(zoom.xlim_ref[0] - new_xlim[0]) # Ensure that upper x limit is not greater than that of the reference if new_xlim[1] > zoom.xlim_ref[1]: new_xlim -= np.array(new_xlim[1] - zoom.xlim_ref[1]) # Ensure that ylim tuple has the smallest value first if zoom.ylim_ref[1] < zoom.ylim_ref[0]: ylim_ref = zoom.ylim_ref[::-1] new_ylim = new_ylim[::-1] else: ylim_ref = zoom.ylim_ref # Ensure that y limit range is no larger than that of the reference if np.diff(new_ylim) > np.diff(ylim_ref): new_ylim *= np.diff(ylim_ref) / np.diff(new_ylim) # Ensure that lower y limit is not less than that of the reference if new_ylim[0] < ylim_ref[0]: new_ylim += np.array(ylim_ref[0] - new_ylim[0]) # Ensure that upper y limit is not greater than that of the reference if new_ylim[1] > ylim_ref[1]: new_ylim -= np.array(new_ylim[1] - ylim_ref[1]) # Return the ylim tuple to its original order if zoom.ylim_ref[1] < zoom.ylim_ref[0]: new_ylim = new_ylim[::-1] # Set new x and y limits ax.set_xlim(new_xlim) ax.set_ylim(new_ylim) # Force redraw ax.figure.canvas.draw() # Record reference x and y limits prior to any zooming zoom.xlim_ref = ax.get_xlim() zoom.ylim_ref = ax.get_ylim() # Get figure for specified axes and attach the event handler fig = ax.get_figure() fig.canvas.mpl_connect('scroll_event', zoom) return zoom
[ "def", "attach_zoom", "(", "ax", ",", "scaling", "=", "2.0", ")", ":", "# See https://stackoverflow.com/questions/11551049", "def", "zoom", "(", "event", ")", ":", "# Get the current x and y limits", "cur_xlim", "=", "ax", ".", "get_xlim", "(", ")", "cur_ylim", "=...
Attach an event handler that supports zooming within a plot using the mouse scroll wheel. Parameters ---------- ax : :class:`matplotlib.axes.Axes` object Axes to which event handling is to be attached scaling : float, optional (default 2.0) Scaling factor for zooming in and out Returns ------- zoom : function Mouse scroll wheel event handler function
[ "Attach", "an", "event", "handler", "that", "supports", "zooming", "within", "a", "plot", "using", "the", "mouse", "scroll", "wheel", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/plot.py#L76-L171
train
210,151
bwohlberg/sporco
sporco/plot.py
config_notebook_plotting
def config_notebook_plotting(): """ Configure plotting functions for inline plotting within a Jupyter Notebook shell. This function has no effect when not within a notebook shell, and may therefore be used within a normal python script. """ # Check whether running within a notebook shell and have # not already monkey patched the plot function from sporco.util import in_notebook module = sys.modules[__name__] if in_notebook() and module.plot.__name__ == 'plot': # Set inline backend (i.e. %matplotlib inline) if in a notebook shell set_notebook_plot_backend() # Replace plot function with a wrapper function that discards # its return value (within a notebook with inline plotting, plots # are duplicated if the return value from the original function is # not assigned to a variable) plot_original = module.plot def plot_wrap(*args, **kwargs): plot_original(*args, **kwargs) module.plot = plot_wrap # Replace surf function with a wrapper function that discards # its return value (see comment for plot function) surf_original = module.surf def surf_wrap(*args, **kwargs): surf_original(*args, **kwargs) module.surf = surf_wrap # Replace contour function with a wrapper function that discards # its return value (see comment for plot function) contour_original = module.contour def contour_wrap(*args, **kwargs): contour_original(*args, **kwargs) module.contour = contour_wrap # Replace imview function with a wrapper function that discards # its return value (see comment for plot function) imview_original = module.imview def imview_wrap(*args, **kwargs): imview_original(*args, **kwargs) module.imview = imview_wrap # Disable figure show method (results in a warning if used within # a notebook with inline plotting) import matplotlib.figure def show_disable(self): pass matplotlib.figure.Figure.show = show_disable
python
def config_notebook_plotting(): """ Configure plotting functions for inline plotting within a Jupyter Notebook shell. This function has no effect when not within a notebook shell, and may therefore be used within a normal python script. """ # Check whether running within a notebook shell and have # not already monkey patched the plot function from sporco.util import in_notebook module = sys.modules[__name__] if in_notebook() and module.plot.__name__ == 'plot': # Set inline backend (i.e. %matplotlib inline) if in a notebook shell set_notebook_plot_backend() # Replace plot function with a wrapper function that discards # its return value (within a notebook with inline plotting, plots # are duplicated if the return value from the original function is # not assigned to a variable) plot_original = module.plot def plot_wrap(*args, **kwargs): plot_original(*args, **kwargs) module.plot = plot_wrap # Replace surf function with a wrapper function that discards # its return value (see comment for plot function) surf_original = module.surf def surf_wrap(*args, **kwargs): surf_original(*args, **kwargs) module.surf = surf_wrap # Replace contour function with a wrapper function that discards # its return value (see comment for plot function) contour_original = module.contour def contour_wrap(*args, **kwargs): contour_original(*args, **kwargs) module.contour = contour_wrap # Replace imview function with a wrapper function that discards # its return value (see comment for plot function) imview_original = module.imview def imview_wrap(*args, **kwargs): imview_original(*args, **kwargs) module.imview = imview_wrap # Disable figure show method (results in a warning if used within # a notebook with inline plotting) import matplotlib.figure def show_disable(self): pass matplotlib.figure.Figure.show = show_disable
[ "def", "config_notebook_plotting", "(", ")", ":", "# Check whether running within a notebook shell and have", "# not already monkey patched the plot function", "from", "sporco", ".", "util", "import", "in_notebook", "module", "=", "sys", ".", "modules", "[", "__name__", "]", ...
Configure plotting functions for inline plotting within a Jupyter Notebook shell. This function has no effect when not within a notebook shell, and may therefore be used within a normal python script.
[ "Configure", "plotting", "functions", "for", "inline", "plotting", "within", "a", "Jupyter", "Notebook", "shell", ".", "This", "function", "has", "no", "effect", "when", "not", "within", "a", "notebook", "shell", "and", "may", "therefore", "be", "used", "withi...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/plot.py#L744-L806
train
210,152
bwohlberg/sporco
sporco/dictlrn/onlinecdl.py
OnlineConvBPDNDictLearn.init_vars
def init_vars(self, S, dimK): """Initalise variables required for sparse coding and dictionary update for training data `S`.""" Nv = S.shape[0:self.dimN] if self.cri is None or Nv != self.cri.Nv: self.cri = cr.CDU_ConvRepIndexing(self.dsz, S, dimK, self.dimN) if self.opt['CUDA_CBPDN']: if self.cri.Cd > 1 or self.cri.Cx > 1: raise ValueError('CUDA CBPDN solver can only be used for ' 'single channel problems') if self.cri.K > 1: raise ValueError('CUDA CBPDN solver can not be used with ' 'mini-batches') self.Df = sl.pyfftw_byte_aligned(sl.rfftn(self.D, self.cri.Nv, self.cri.axisN)) self.Gf = sl.pyfftw_empty_aligned(self.Df.shape, self.Df.dtype) self.Z = sl.pyfftw_empty_aligned(self.cri.shpX, self.dtype) else: self.Df[:] = sl.rfftn(self.D, self.cri.Nv, self.cri.axisN)
python
def init_vars(self, S, dimK): """Initalise variables required for sparse coding and dictionary update for training data `S`.""" Nv = S.shape[0:self.dimN] if self.cri is None or Nv != self.cri.Nv: self.cri = cr.CDU_ConvRepIndexing(self.dsz, S, dimK, self.dimN) if self.opt['CUDA_CBPDN']: if self.cri.Cd > 1 or self.cri.Cx > 1: raise ValueError('CUDA CBPDN solver can only be used for ' 'single channel problems') if self.cri.K > 1: raise ValueError('CUDA CBPDN solver can not be used with ' 'mini-batches') self.Df = sl.pyfftw_byte_aligned(sl.rfftn(self.D, self.cri.Nv, self.cri.axisN)) self.Gf = sl.pyfftw_empty_aligned(self.Df.shape, self.Df.dtype) self.Z = sl.pyfftw_empty_aligned(self.cri.shpX, self.dtype) else: self.Df[:] = sl.rfftn(self.D, self.cri.Nv, self.cri.axisN)
[ "def", "init_vars", "(", "self", ",", "S", ",", "dimK", ")", ":", "Nv", "=", "S", ".", "shape", "[", "0", ":", "self", ".", "dimN", "]", "if", "self", ".", "cri", "is", "None", "or", "Nv", "!=", "self", ".", "cri", ".", "Nv", ":", "self", "...
Initalise variables required for sparse coding and dictionary update for training data `S`.
[ "Initalise", "variables", "required", "for", "sparse", "coding", "and", "dictionary", "update", "for", "training", "data", "S", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/onlinecdl.py#L242-L261
train
210,153
bwohlberg/sporco
sporco/dictlrn/onlinecdl.py
OnlineConvBPDNDictLearn.manage_itstat
def manage_itstat(self): """Compute, record, and display iteration statistics.""" # Extract and record iteration stats itst = self.iteration_stats() self.itstat.append(itst) self.display_status(self.fmtstr, itst)
python
def manage_itstat(self): """Compute, record, and display iteration statistics.""" # Extract and record iteration stats itst = self.iteration_stats() self.itstat.append(itst) self.display_status(self.fmtstr, itst)
[ "def", "manage_itstat", "(", "self", ")", ":", "# Extract and record iteration stats", "itst", "=", "self", ".", "iteration_stats", "(", ")", "self", ".", "itstat", ".", "append", "(", "itst", ")", "self", ".", "display_status", "(", "self", ".", "fmtstr", "...
Compute, record, and display iteration statistics.
[ "Compute", "record", "and", "display", "iteration", "statistics", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/onlinecdl.py#L333-L339
train
210,154
bwohlberg/sporco
sporco/dictlrn/onlinecdl.py
OnlineConvBPDNDictLearn.display_start
def display_start(self): """Start status display if option selected.""" if self.opt['Verbose'] and self.opt['StatusHeader']: print(self.hdrstr) print("-" * self.nsep)
python
def display_start(self): """Start status display if option selected.""" if self.opt['Verbose'] and self.opt['StatusHeader']: print(self.hdrstr) print("-" * self.nsep)
[ "def", "display_start", "(", "self", ")", ":", "if", "self", ".", "opt", "[", "'Verbose'", "]", "and", "self", ".", "opt", "[", "'StatusHeader'", "]", ":", "print", "(", "self", ".", "hdrstr", ")", "print", "(", "\"-\"", "*", "self", ".", "nsep", "...
Start status display if option selected.
[ "Start", "status", "display", "if", "option", "selected", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/onlinecdl.py#L427-L432
train
210,155
bwohlberg/sporco
sporco/dictlrn/onlinecdl.py
OnlineConvBPDNMaskDictLearn.xstep
def xstep(self, S, W, lmbda, dimK): """Solve CSC problem for training data `S`.""" if self.opt['CUDA_CBPDN']: Z = cuda.cbpdnmsk(self.D.squeeze(), S[..., 0], W.squeeze(), lmbda, self.opt['CBPDN']) Z = Z.reshape(self.cri.Nv + (1, 1, self.cri.M,)) self.Z[:] = np.asarray(Z, dtype=self.dtype) self.Zf = sl.rfftn(self.Z, self.cri.Nv, self.cri.axisN) self.Sf = sl.rfftn(S.reshape(self.cri.shpS), self.cri.Nv, self.cri.axisN) self.xstep_itstat = None else: # Create X update object (external representation is expected!) xstep = cbpdn.ConvBPDNMaskDcpl(self.D.squeeze(), S, lmbda, W, self.opt['CBPDN'], dimK=dimK, dimN=self.cri.dimN) xstep.solve() self.Sf = sl.rfftn(S.reshape(self.cri.shpS), self.cri.Nv, self.cri.axisN) self.setcoef(xstep.getcoef()) self.xstep_itstat = xstep.itstat[-1] if xstep.itstat else None
python
def xstep(self, S, W, lmbda, dimK): """Solve CSC problem for training data `S`.""" if self.opt['CUDA_CBPDN']: Z = cuda.cbpdnmsk(self.D.squeeze(), S[..., 0], W.squeeze(), lmbda, self.opt['CBPDN']) Z = Z.reshape(self.cri.Nv + (1, 1, self.cri.M,)) self.Z[:] = np.asarray(Z, dtype=self.dtype) self.Zf = sl.rfftn(self.Z, self.cri.Nv, self.cri.axisN) self.Sf = sl.rfftn(S.reshape(self.cri.shpS), self.cri.Nv, self.cri.axisN) self.xstep_itstat = None else: # Create X update object (external representation is expected!) xstep = cbpdn.ConvBPDNMaskDcpl(self.D.squeeze(), S, lmbda, W, self.opt['CBPDN'], dimK=dimK, dimN=self.cri.dimN) xstep.solve() self.Sf = sl.rfftn(S.reshape(self.cri.shpS), self.cri.Nv, self.cri.axisN) self.setcoef(xstep.getcoef()) self.xstep_itstat = xstep.itstat[-1] if xstep.itstat else None
[ "def", "xstep", "(", "self", ",", "S", ",", "W", ",", "lmbda", ",", "dimK", ")", ":", "if", "self", ".", "opt", "[", "'CUDA_CBPDN'", "]", ":", "Z", "=", "cuda", ".", "cbpdnmsk", "(", "self", ".", "D", ".", "squeeze", "(", ")", ",", "S", "[", ...
Solve CSC problem for training data `S`.
[ "Solve", "CSC", "problem", "for", "training", "data", "S", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/onlinecdl.py#L546-L567
train
210,156
bwohlberg/sporco
sporco/cdict.py
keycmp
def keycmp(a, b, pth=()): """Recurse down the tree of nested dicts `b`, at each level checking that it does not have any keys that are not also at the same level in `a`. The key path is recorded in `pth`. If an unknown key is encountered in `b`, an `UnknownKeyError` exception is raised. If a non-dict value is encountered in `b` for which the corresponding value in `a` is a dict, an `InvalidValueError` exception is raised.""" akey = list(a.keys()) # Iterate over all keys in b for key in list(b.keys()): # If a key is encountered that is not in a, raise an # UnknownKeyError exception. if key not in akey: raise UnknownKeyError(pth + (key,)) else: # If corresponding values in a and b for the same key # are both dicts, recursively call this method for # those values. If the value in a is a dict and the # value in b is not, raise an InvalidValueError # exception. if isinstance(a[key], dict): if isinstance(b[key], dict): keycmp(a[key], b[key], pth + (key,)) else: raise InvalidValueError(pth + (key,))
python
def keycmp(a, b, pth=()): """Recurse down the tree of nested dicts `b`, at each level checking that it does not have any keys that are not also at the same level in `a`. The key path is recorded in `pth`. If an unknown key is encountered in `b`, an `UnknownKeyError` exception is raised. If a non-dict value is encountered in `b` for which the corresponding value in `a` is a dict, an `InvalidValueError` exception is raised.""" akey = list(a.keys()) # Iterate over all keys in b for key in list(b.keys()): # If a key is encountered that is not in a, raise an # UnknownKeyError exception. if key not in akey: raise UnknownKeyError(pth + (key,)) else: # If corresponding values in a and b for the same key # are both dicts, recursively call this method for # those values. If the value in a is a dict and the # value in b is not, raise an InvalidValueError # exception. if isinstance(a[key], dict): if isinstance(b[key], dict): keycmp(a[key], b[key], pth + (key,)) else: raise InvalidValueError(pth + (key,))
[ "def", "keycmp", "(", "a", ",", "b", ",", "pth", "=", "(", ")", ")", ":", "akey", "=", "list", "(", "a", ".", "keys", "(", ")", ")", "# Iterate over all keys in b", "for", "key", "in", "list", "(", "b", ".", "keys", "(", ")", ")", ":", "# If a ...
Recurse down the tree of nested dicts `b`, at each level checking that it does not have any keys that are not also at the same level in `a`. The key path is recorded in `pth`. If an unknown key is encountered in `b`, an `UnknownKeyError` exception is raised. If a non-dict value is encountered in `b` for which the corresponding value in `a` is a dict, an `InvalidValueError` exception is raised.
[ "Recurse", "down", "the", "tree", "of", "nested", "dicts", "b", "at", "each", "level", "checking", "that", "it", "does", "not", "have", "any", "keys", "that", "are", "not", "also", "at", "the", "same", "level", "in", "a", ".", "The", "key", "path", "...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cdict.py#L299-L325
train
210,157
bwohlberg/sporco
sporco/cdict.py
ConstrainedDict.update
def update(self, d): """Update the dict with the dict tree in parameter d. Parameters ---------- d : dict New dict content """ # Call __setitem__ for all keys in d for key in list(d.keys()): self.__setitem__(key, d[key])
python
def update(self, d): """Update the dict with the dict tree in parameter d. Parameters ---------- d : dict New dict content """ # Call __setitem__ for all keys in d for key in list(d.keys()): self.__setitem__(key, d[key])
[ "def", "update", "(", "self", ",", "d", ")", ":", "# Call __setitem__ for all keys in d", "for", "key", "in", "list", "(", "d", ".", "keys", "(", ")", ")", ":", "self", ".", "__setitem__", "(", "key", ",", "d", "[", "key", "]", ")" ]
Update the dict with the dict tree in parameter d. Parameters ---------- d : dict New dict content
[ "Update", "the", "dict", "with", "the", "dict", "tree", "in", "parameter", "d", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cdict.py#L110-L121
train
210,158
bwohlberg/sporco
sporco/cdict.py
ConstrainedDict.check
def check(self, key, value): """Check whether key,value pair is allowed. The key is allowed if there is a corresponding key in the defaults class attribute dict. The value is not allowed if it is a dict in the defaults dict and not a dict in value. Parameters ---------- key : str or tuple of str Dict key value : any Dict value corresponding to key """ # This test necessary to avoid unpickling errors in Python 3 if hasattr(self, 'dflt'): # Get corresponding node to self, as determined by pth # attribute, of the defaults dict tree a = self.__class__.getnode(self.dflt, self.pth) # Raise UnknownKeyError exception if key not in corresponding # node of defaults tree if key not in a: raise UnknownKeyError(self.pth + (key,)) # Raise InvalidValueError if the key value in the defaults # tree is a dict and the value parameter is not a dict and elif isinstance(a[key], dict) and not isinstance(value, dict): raise InvalidValueError(self.pth + (key,))
python
def check(self, key, value): """Check whether key,value pair is allowed. The key is allowed if there is a corresponding key in the defaults class attribute dict. The value is not allowed if it is a dict in the defaults dict and not a dict in value. Parameters ---------- key : str or tuple of str Dict key value : any Dict value corresponding to key """ # This test necessary to avoid unpickling errors in Python 3 if hasattr(self, 'dflt'): # Get corresponding node to self, as determined by pth # attribute, of the defaults dict tree a = self.__class__.getnode(self.dflt, self.pth) # Raise UnknownKeyError exception if key not in corresponding # node of defaults tree if key not in a: raise UnknownKeyError(self.pth + (key,)) # Raise InvalidValueError if the key value in the defaults # tree is a dict and the value parameter is not a dict and elif isinstance(a[key], dict) and not isinstance(value, dict): raise InvalidValueError(self.pth + (key,))
[ "def", "check", "(", "self", ",", "key", ",", "value", ")", ":", "# This test necessary to avoid unpickling errors in Python 3", "if", "hasattr", "(", "self", ",", "'dflt'", ")", ":", "# Get corresponding node to self, as determined by pth", "# attribute, of the defaults dict...
Check whether key,value pair is allowed. The key is allowed if there is a corresponding key in the defaults class attribute dict. The value is not allowed if it is a dict in the defaults dict and not a dict in value. Parameters ---------- key : str or tuple of str Dict key value : any Dict value corresponding to key
[ "Check", "whether", "key", "value", "pair", "is", "allowed", ".", "The", "key", "is", "allowed", "if", "there", "is", "a", "corresponding", "key", "in", "the", "defaults", "class", "attribute", "dict", ".", "The", "value", "is", "not", "allowed", "if", "...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cdict.py#L220-L246
train
210,159
bwohlberg/sporco
sporco/cdict.py
ConstrainedDict.getparent
def getparent(d, pth): """Get the parent node of a subdict as specified by the key path in `pth`. Parameters ---------- d : dict Dict tree in which access is required pth : str or tuple of str Dict key """ c = d for key in pth[:-1]: if not isinstance(c, dict): raise InvalidValueError(c) elif key not in c: raise UnknownKeyError(pth) else: c = c.__getitem__(key) return c
python
def getparent(d, pth): """Get the parent node of a subdict as specified by the key path in `pth`. Parameters ---------- d : dict Dict tree in which access is required pth : str or tuple of str Dict key """ c = d for key in pth[:-1]: if not isinstance(c, dict): raise InvalidValueError(c) elif key not in c: raise UnknownKeyError(pth) else: c = c.__getitem__(key) return c
[ "def", "getparent", "(", "d", ",", "pth", ")", ":", "c", "=", "d", "for", "key", "in", "pth", "[", ":", "-", "1", "]", ":", "if", "not", "isinstance", "(", "c", ",", "dict", ")", ":", "raise", "InvalidValueError", "(", "c", ")", "elif", "key", ...
Get the parent node of a subdict as specified by the key path in `pth`. Parameters ---------- d : dict Dict tree in which access is required pth : str or tuple of str Dict key
[ "Get", "the", "parent", "node", "of", "a", "subdict", "as", "specified", "by", "the", "key", "path", "in", "pth", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cdict.py#L251-L271
train
210,160
bwohlberg/sporco
sporco/admm/parcbpdn.py
par_relax_AX
def par_relax_AX(i): """Parallel implementation of relaxation if option ``RelaxParam`` != 1.0. """ global mp_X global mp_Xnr global mp_DX global mp_DXnr mp_Xnr[mp_grp[i]:mp_grp[i+1]] = mp_X[mp_grp[i]:mp_grp[i+1]] mp_DXnr[i] = mp_DX[i] if mp_rlx != 1.0: grpind = slice(mp_grp[i], mp_grp[i+1]) mp_X[grpind] = mp_rlx * mp_X[grpind] + (1-mp_rlx)*mp_Y1[grpind] mp_DX[i] = mp_rlx*mp_DX[i] + (1-mp_rlx)*mp_Y0[i]
python
def par_relax_AX(i): """Parallel implementation of relaxation if option ``RelaxParam`` != 1.0. """ global mp_X global mp_Xnr global mp_DX global mp_DXnr mp_Xnr[mp_grp[i]:mp_grp[i+1]] = mp_X[mp_grp[i]:mp_grp[i+1]] mp_DXnr[i] = mp_DX[i] if mp_rlx != 1.0: grpind = slice(mp_grp[i], mp_grp[i+1]) mp_X[grpind] = mp_rlx * mp_X[grpind] + (1-mp_rlx)*mp_Y1[grpind] mp_DX[i] = mp_rlx*mp_DX[i] + (1-mp_rlx)*mp_Y0[i]
[ "def", "par_relax_AX", "(", "i", ")", ":", "global", "mp_X", "global", "mp_Xnr", "global", "mp_DX", "global", "mp_DXnr", "mp_Xnr", "[", "mp_grp", "[", "i", "]", ":", "mp_grp", "[", "i", "+", "1", "]", "]", "=", "mp_X", "[", "mp_grp", "[", "i", "]",...
Parallel implementation of relaxation if option ``RelaxParam`` != 1.0.
[ "Parallel", "implementation", "of", "relaxation", "if", "option", "RelaxParam", "!", "=", "1", ".", "0", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/parcbpdn.py#L163-L177
train
210,161
bwohlberg/sporco
sporco/admm/parcbpdn.py
par_final_stepgrp
def par_final_stepgrp(i): """The parallel step grouping of the final iteration in solve. A cyclic permutation of the steps is done to require only one merge per iteration, requiring unique initial and final step groups. Parameters ---------- i : int Index of grouping to update """ par_y0bstep(i) par_y1step(i) par_u0step(i) par_u1step(i)
python
def par_final_stepgrp(i): """The parallel step grouping of the final iteration in solve. A cyclic permutation of the steps is done to require only one merge per iteration, requiring unique initial and final step groups. Parameters ---------- i : int Index of grouping to update """ par_y0bstep(i) par_y1step(i) par_u0step(i) par_u1step(i)
[ "def", "par_final_stepgrp", "(", "i", ")", ":", "par_y0bstep", "(", "i", ")", "par_y1step", "(", "i", ")", "par_u0step", "(", "i", ")", "par_u1step", "(", "i", ")" ]
The parallel step grouping of the final iteration in solve. A cyclic permutation of the steps is done to require only one merge per iteration, requiring unique initial and final step groups. Parameters ---------- i : int Index of grouping to update
[ "The", "parallel", "step", "grouping", "of", "the", "final", "iteration", "in", "solve", ".", "A", "cyclic", "permutation", "of", "the", "steps", "is", "done", "to", "require", "only", "one", "merge", "per", "iteration", "requiring", "unique", "initial", "an...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/parcbpdn.py#L299-L313
train
210,162
bwohlberg/sporco
sporco/admm/parcbpdn.py
par_compute_residuals
def par_compute_residuals(i): """Compute components of the residual and stopping thresholds that can be done in parallel. Parameters ---------- i : int Index of group to compute """ # Compute the residuals in parallel, need to check if the residuals # depend on alpha global mp_ry0 global mp_ry1 global mp_sy0 global mp_sy1 global mp_nrmAx global mp_nrmBy global mp_nrmu mp_ry0[i] = np.sum((mp_DXnr[i] - mp_Y0[i])**2) mp_ry1[i] = mp_alpha**2*np.sum((mp_Xnr[mp_grp[i]:mp_grp[i+1]]- mp_Y1[mp_grp[i]:mp_grp[i+1]])**2) mp_sy0[i] = np.sum((mp_Y0old[i] - mp_Y0[i])**2) mp_sy1[i] = mp_alpha**2*np.sum((mp_Y1old[mp_grp[i]:mp_grp[i+1]]- mp_Y1[mp_grp[i]:mp_grp[i+1]])**2) mp_nrmAx[i] = np.sum(mp_DXnr[i]**2) + mp_alpha**2 * np.sum( mp_Xnr[mp_grp[i]:mp_grp[i+1]]**2) mp_nrmBy[i] = np.sum(mp_Y0[i]**2) + mp_alpha**2 * np.sum( mp_Y1[mp_grp[i]:mp_grp[i+1]]**2) mp_nrmu[i] = np.sum(mp_U0[i]**2) + np.sum(mp_U1[mp_grp[i]:mp_grp[i+1]]**2)
python
def par_compute_residuals(i): """Compute components of the residual and stopping thresholds that can be done in parallel. Parameters ---------- i : int Index of group to compute """ # Compute the residuals in parallel, need to check if the residuals # depend on alpha global mp_ry0 global mp_ry1 global mp_sy0 global mp_sy1 global mp_nrmAx global mp_nrmBy global mp_nrmu mp_ry0[i] = np.sum((mp_DXnr[i] - mp_Y0[i])**2) mp_ry1[i] = mp_alpha**2*np.sum((mp_Xnr[mp_grp[i]:mp_grp[i+1]]- mp_Y1[mp_grp[i]:mp_grp[i+1]])**2) mp_sy0[i] = np.sum((mp_Y0old[i] - mp_Y0[i])**2) mp_sy1[i] = mp_alpha**2*np.sum((mp_Y1old[mp_grp[i]:mp_grp[i+1]]- mp_Y1[mp_grp[i]:mp_grp[i+1]])**2) mp_nrmAx[i] = np.sum(mp_DXnr[i]**2) + mp_alpha**2 * np.sum( mp_Xnr[mp_grp[i]:mp_grp[i+1]]**2) mp_nrmBy[i] = np.sum(mp_Y0[i]**2) + mp_alpha**2 * np.sum( mp_Y1[mp_grp[i]:mp_grp[i+1]]**2) mp_nrmu[i] = np.sum(mp_U0[i]**2) + np.sum(mp_U1[mp_grp[i]:mp_grp[i+1]]**2)
[ "def", "par_compute_residuals", "(", "i", ")", ":", "# Compute the residuals in parallel, need to check if the residuals", "# depend on alpha", "global", "mp_ry0", "global", "mp_ry1", "global", "mp_sy0", "global", "mp_sy1", "global", "mp_nrmAx", "global", "mp_nrmBy", "global"...
Compute components of the residual and stopping thresholds that can be done in parallel. Parameters ---------- i : int Index of group to compute
[ "Compute", "components", "of", "the", "residual", "and", "stopping", "thresholds", "that", "can", "be", "done", "in", "parallel", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/parcbpdn.py#L317-L346
train
210,163
bwohlberg/sporco
sporco/admm/parcbpdn.py
ParConvBPDN.init_pool
def init_pool(self): """Initialize multiprocessing pool if necessary.""" # initialize the pool if needed if self.pool is None: if self.nproc > 1: self.pool = mp.Pool(processes=self.nproc) else: self.pool = None else: print('pool already initialized?')
python
def init_pool(self): """Initialize multiprocessing pool if necessary.""" # initialize the pool if needed if self.pool is None: if self.nproc > 1: self.pool = mp.Pool(processes=self.nproc) else: self.pool = None else: print('pool already initialized?')
[ "def", "init_pool", "(", "self", ")", ":", "# initialize the pool if needed", "if", "self", ".", "pool", "is", "None", ":", "if", "self", ".", "nproc", ">", "1", ":", "self", ".", "pool", "=", "mp", ".", "Pool", "(", "processes", "=", "self", ".", "n...
Initialize multiprocessing pool if necessary.
[ "Initialize", "multiprocessing", "pool", "if", "necessary", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/parcbpdn.py#L838-L848
train
210,164
bwohlberg/sporco
sporco/admm/parcbpdn.py
ParConvBPDN.distribute
def distribute(self, f, n): """Distribute the computations amongst the multiprocessing pools Parameters ---------- f : function Function to be distributed to the processors n : int The values in range(0,n) will be passed as arguments to the function f. """ if self.pool is None: return [f(i) for i in range(n)] else: return self.pool.map(f, range(n))
python
def distribute(self, f, n): """Distribute the computations amongst the multiprocessing pools Parameters ---------- f : function Function to be distributed to the processors n : int The values in range(0,n) will be passed as arguments to the function f. """ if self.pool is None: return [f(i) for i in range(n)] else: return self.pool.map(f, range(n))
[ "def", "distribute", "(", "self", ",", "f", ",", "n", ")", ":", "if", "self", ".", "pool", "is", "None", ":", "return", "[", "f", "(", "i", ")", "for", "i", "in", "range", "(", "n", ")", "]", "else", ":", "return", "self", ".", "pool", ".", ...
Distribute the computations amongst the multiprocessing pools Parameters ---------- f : function Function to be distributed to the processors n : int The values in range(0,n) will be passed as arguments to the function f.
[ "Distribute", "the", "computations", "amongst", "the", "multiprocessing", "pools" ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/parcbpdn.py#L852-L867
train
210,165
bwohlberg/sporco
sporco/admm/parcbpdn.py
ParConvBPDN.terminate_pool
def terminate_pool(self): """Terminate and close the multiprocessing pool if necessary.""" if self.pool is not None: self.pool.terminate() self.pool.join() del(self.pool) self.pool = None
python
def terminate_pool(self): """Terminate and close the multiprocessing pool if necessary.""" if self.pool is not None: self.pool.terminate() self.pool.join() del(self.pool) self.pool = None
[ "def", "terminate_pool", "(", "self", ")", ":", "if", "self", ".", "pool", "is", "not", "None", ":", "self", ".", "pool", ".", "terminate", "(", ")", "self", ".", "pool", ".", "join", "(", ")", "del", "(", "self", ".", "pool", ")", "self", ".", ...
Terminate and close the multiprocessing pool if necessary.
[ "Terminate", "and", "close", "the", "multiprocessing", "pool", "if", "necessary", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/parcbpdn.py#L871-L878
train
210,166
bwohlberg/sporco
sporco/admm/cbpdn.py
ConvBPDNProjL1.eval_objfn
def eval_objfn(self): """Compute components of regularisation function as well as total objective function. """ dfd = self.obfn_dfd() prj = sp.proj_l1(self.obfn_gvar(), self.gamma, axis=self.cri.axisN + (self.cri.axisC, self.cri.axisM)) cns = np.linalg.norm(prj - self.obfn_gvar()) return (dfd, cns)
python
def eval_objfn(self): """Compute components of regularisation function as well as total objective function. """ dfd = self.obfn_dfd() prj = sp.proj_l1(self.obfn_gvar(), self.gamma, axis=self.cri.axisN + (self.cri.axisC, self.cri.axisM)) cns = np.linalg.norm(prj - self.obfn_gvar()) return (dfd, cns)
[ "def", "eval_objfn", "(", "self", ")", ":", "dfd", "=", "self", ".", "obfn_dfd", "(", ")", "prj", "=", "sp", ".", "proj_l1", "(", "self", ".", "obfn_gvar", "(", ")", ",", "self", ".", "gamma", ",", "axis", "=", "self", ".", "cri", ".", "axisN", ...
Compute components of regularisation function as well as total objective function.
[ "Compute", "components", "of", "regularisation", "function", "as", "well", "as", "total", "objective", "function", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdn.py#L1373-L1383
train
210,167
bwohlberg/sporco
sporco/admm/cbpdn.py
AddMaskSim.ystep
def ystep(self): """This method is inserted into the inner cbpdn object, replacing its own ystep method, thereby providing a hook for applying the additional steps necessary for the AMS method. """ # Extract AMS part of ystep argument so that it is not # affected by the main part of the ystep amidx = self.index_addmsk() Yi = self.cbpdn.AX[amidx] + self.cbpdn.U[amidx] # Perform main part of ystep from inner cbpdn object self.inner_ystep() # Apply mask to AMS component and insert into Y from inner # cbpdn object Yi[np.where(self.W.astype(np.bool))] = 0.0 self.cbpdn.Y[amidx] = Yi
python
def ystep(self): """This method is inserted into the inner cbpdn object, replacing its own ystep method, thereby providing a hook for applying the additional steps necessary for the AMS method. """ # Extract AMS part of ystep argument so that it is not # affected by the main part of the ystep amidx = self.index_addmsk() Yi = self.cbpdn.AX[amidx] + self.cbpdn.U[amidx] # Perform main part of ystep from inner cbpdn object self.inner_ystep() # Apply mask to AMS component and insert into Y from inner # cbpdn object Yi[np.where(self.W.astype(np.bool))] = 0.0 self.cbpdn.Y[amidx] = Yi
[ "def", "ystep", "(", "self", ")", ":", "# Extract AMS part of ystep argument so that it is not", "# affected by the main part of the ystep", "amidx", "=", "self", ".", "index_addmsk", "(", ")", "Yi", "=", "self", ".", "cbpdn", ".", "AX", "[", "amidx", "]", "+", "s...
This method is inserted into the inner cbpdn object, replacing its own ystep method, thereby providing a hook for applying the additional steps necessary for the AMS method.
[ "This", "method", "is", "inserted", "into", "the", "inner", "cbpdn", "object", "replacing", "its", "own", "ystep", "method", "thereby", "providing", "a", "hook", "for", "applying", "the", "additional", "steps", "necessary", "for", "the", "AMS", "method", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdn.py#L2352-L2367
train
210,168
bwohlberg/sporco
sporco/admm/cbpdn.py
AddMaskSim.obfn_gvar
def obfn_gvar(self): """This method is inserted into the inner cbpdn object, replacing its own obfn_gvar method, thereby providing a hook for applying the additional steps necessary for the AMS method. """ # Get inner cbpdn object gvar gv = self.inner_obfn_gvar().copy() # Set slice corresponding to the coefficient map of the final # filter (the impulse inserted for the AMS method) to zero so # that it does not affect the results (e.g. l1 norm) computed # from this variable by the inner cbpdn object gv[..., -self.cri.Cd:] = 0 return gv
python
def obfn_gvar(self): """This method is inserted into the inner cbpdn object, replacing its own obfn_gvar method, thereby providing a hook for applying the additional steps necessary for the AMS method. """ # Get inner cbpdn object gvar gv = self.inner_obfn_gvar().copy() # Set slice corresponding to the coefficient map of the final # filter (the impulse inserted for the AMS method) to zero so # that it does not affect the results (e.g. l1 norm) computed # from this variable by the inner cbpdn object gv[..., -self.cri.Cd:] = 0 return gv
[ "def", "obfn_gvar", "(", "self", ")", ":", "# Get inner cbpdn object gvar", "gv", "=", "self", ".", "inner_obfn_gvar", "(", ")", ".", "copy", "(", ")", "# Set slice corresponding to the coefficient map of the final", "# filter (the impulse inserted for the AMS method) to zero s...
This method is inserted into the inner cbpdn object, replacing its own obfn_gvar method, thereby providing a hook for applying the additional steps necessary for the AMS method.
[ "This", "method", "is", "inserted", "into", "the", "inner", "cbpdn", "object", "replacing", "its", "own", "obfn_gvar", "method", "thereby", "providing", "a", "hook", "for", "applying", "the", "additional", "steps", "necessary", "for", "the", "AMS", "method", "...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdn.py#L2371-L2385
train
210,169
bwohlberg/sporco
sporco/admm/cbpdn.py
MultiDictConvBPDN.solve
def solve(self): """Call the solve method of the inner cbpdn object and return the result. """ # Call solve method of inner cbpdn object Xi = self.cbpdn.solve() # Copy attributes from inner cbpdn object self.timer = self.cbpdn.timer self.itstat = self.cbpdn.itstat # Return result of inner cbpdn object return Xi
python
def solve(self): """Call the solve method of the inner cbpdn object and return the result. """ # Call solve method of inner cbpdn object Xi = self.cbpdn.solve() # Copy attributes from inner cbpdn object self.timer = self.cbpdn.timer self.itstat = self.cbpdn.itstat # Return result of inner cbpdn object return Xi
[ "def", "solve", "(", "self", ")", ":", "# Call solve method of inner cbpdn object", "Xi", "=", "self", ".", "cbpdn", ".", "solve", "(", ")", "# Copy attributes from inner cbpdn object", "self", ".", "timer", "=", "self", ".", "cbpdn", ".", "timer", "self", ".", ...
Call the solve method of the inner cbpdn object and return the result.
[ "Call", "the", "solve", "method", "of", "the", "inner", "cbpdn", "object", "and", "return", "the", "result", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdn.py#L2843-L2854
train
210,170
bwohlberg/sporco
sporco/admm/cbpdn.py
MultiDictConvBPDN.reconstruct
def reconstruct(self, b, X=None): """Reconstruct representation of signal b in signal set.""" if X is None: X = self.getcoef() Xf = sl.rfftn(X, None, self.cbpdn.cri.axisN) slc = (slice(None),)*self.dimN + \ (slice(self.chncs[b], self.chncs[b+1]),) Sf = np.sum(self.cbpdn.Df[slc] * Xf, axis=self.cbpdn.cri.axisM) return sl.irfftn(Sf, self.cbpdn.cri.Nv, self.cbpdn.cri.axisN)
python
def reconstruct(self, b, X=None): """Reconstruct representation of signal b in signal set.""" if X is None: X = self.getcoef() Xf = sl.rfftn(X, None, self.cbpdn.cri.axisN) slc = (slice(None),)*self.dimN + \ (slice(self.chncs[b], self.chncs[b+1]),) Sf = np.sum(self.cbpdn.Df[slc] * Xf, axis=self.cbpdn.cri.axisM) return sl.irfftn(Sf, self.cbpdn.cri.Nv, self.cbpdn.cri.axisN)
[ "def", "reconstruct", "(", "self", ",", "b", ",", "X", "=", "None", ")", ":", "if", "X", "is", "None", ":", "X", "=", "self", ".", "getcoef", "(", ")", "Xf", "=", "sl", ".", "rfftn", "(", "X", ",", "None", ",", "self", ".", "cbpdn", ".", "c...
Reconstruct representation of signal b in signal set.
[ "Reconstruct", "representation", "of", "signal", "b", "in", "signal", "set", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdn.py#L2872-L2881
train
210,171
bwohlberg/sporco
sporco/common.py
_fix_dynamic_class_lookup
def _fix_dynamic_class_lookup(cls, pstfx): """Fix name lookup problem that prevents pickling of dynamically defined classes. Parameters ---------- cls : class Dynamically generated class to which fix is to be applied pstfx : string Postfix that can be used to identify dynamically generated classes that are equivalent by construction """ # Extended name for the class that will be added to the module namespace extnm = '_' + cls.__name__ + '_' + pstfx # Get the module in which the dynamic class is defined mdl = sys.modules[cls.__module__] # Allow lookup of the dynamically generated class within the module via # its extended name setattr(mdl, extnm, cls) # Change the dynamically generated class name to the extended name if hasattr(cls, '__qualname__'): cls.__qualname__ = extnm else: cls.__name__ = extnm
python
def _fix_dynamic_class_lookup(cls, pstfx): """Fix name lookup problem that prevents pickling of dynamically defined classes. Parameters ---------- cls : class Dynamically generated class to which fix is to be applied pstfx : string Postfix that can be used to identify dynamically generated classes that are equivalent by construction """ # Extended name for the class that will be added to the module namespace extnm = '_' + cls.__name__ + '_' + pstfx # Get the module in which the dynamic class is defined mdl = sys.modules[cls.__module__] # Allow lookup of the dynamically generated class within the module via # its extended name setattr(mdl, extnm, cls) # Change the dynamically generated class name to the extended name if hasattr(cls, '__qualname__'): cls.__qualname__ = extnm else: cls.__name__ = extnm
[ "def", "_fix_dynamic_class_lookup", "(", "cls", ",", "pstfx", ")", ":", "# Extended name for the class that will be added to the module namespace", "extnm", "=", "'_'", "+", "cls", ".", "__name__", "+", "'_'", "+", "pstfx", "# Get the module in which the dynamic class is defi...
Fix name lookup problem that prevents pickling of dynamically defined classes. Parameters ---------- cls : class Dynamically generated class to which fix is to be applied pstfx : string Postfix that can be used to identify dynamically generated classes that are equivalent by construction
[ "Fix", "name", "lookup", "problem", "that", "prevents", "pickling", "of", "dynamically", "defined", "classes", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/common.py#L59-L83
train
210,172
bwohlberg/sporco
sporco/common.py
solve_status_str
def solve_status_str(hdrlbl, fmtmap=None, fwdth0=4, fwdthdlt=6, fprec=2): """Construct header and format details for status display of an iterative solver. Parameters ---------- hdrlbl : tuple of strings Tuple of field header strings fmtmap : dict or None, optional (default None) A dict providing a mapping from field header strings to print format strings, providing a mechanism for fields with print formats that depart from the standard format fwdth0 : int, optional (default 4) Number of characters in first field formatted for integers fwdthdlt : int, optional (default 6) The width of fields formatted for floats is the sum of the value of this parameter and the field precision fprec : int, optional (default 2) Precision of fields formatted for floats Returns ------- hdrstr : string Complete header string fmtstr : string Complete print formatting string for numeric values nsep : integer Number of characters in separator string """ if fmtmap is None: fmtmap = {} fwdthn = fprec + fwdthdlt # Construct a list specifying the format string for each field. # Use format string from fmtmap if specified, otherwise use # a %d specifier with field width fwdth0 for the first field, # or a %e specifier with field width fwdthn and precision # fprec fldfmt = [fmtmap[lbl] if lbl in fmtmap else (('%%%dd' % (fwdth0)) if idx == 0 else (('%%%d.%de' % (fwdthn, fprec)))) for idx, lbl in enumerate(hdrlbl)] fmtstr = (' ').join(fldfmt) # Construct a list of field widths for each field by extracting # field widths from field format strings cre = re.compile(r'%-?(\d+)') fldwid = [] for fmt in fldfmt: mtch = cre.match(fmt) if mtch is None: raise ValueError("Format string '%s' does not contain field " "width" % fmt) else: fldwid.append(int(mtch.group(1))) # Construct list of field header strings formatted to the # appropriate field width, and join to construct a combined field # header string hdrlst = [('%-*s' % (w, t)) for t, w in zip(hdrlbl, fldwid)] hdrstr = (' ').join(hdrlst) return hdrstr, fmtstr, len(hdrstr)
python
def solve_status_str(hdrlbl, fmtmap=None, fwdth0=4, fwdthdlt=6, fprec=2): """Construct header and format details for status display of an iterative solver. Parameters ---------- hdrlbl : tuple of strings Tuple of field header strings fmtmap : dict or None, optional (default None) A dict providing a mapping from field header strings to print format strings, providing a mechanism for fields with print formats that depart from the standard format fwdth0 : int, optional (default 4) Number of characters in first field formatted for integers fwdthdlt : int, optional (default 6) The width of fields formatted for floats is the sum of the value of this parameter and the field precision fprec : int, optional (default 2) Precision of fields formatted for floats Returns ------- hdrstr : string Complete header string fmtstr : string Complete print formatting string for numeric values nsep : integer Number of characters in separator string """ if fmtmap is None: fmtmap = {} fwdthn = fprec + fwdthdlt # Construct a list specifying the format string for each field. # Use format string from fmtmap if specified, otherwise use # a %d specifier with field width fwdth0 for the first field, # or a %e specifier with field width fwdthn and precision # fprec fldfmt = [fmtmap[lbl] if lbl in fmtmap else (('%%%dd' % (fwdth0)) if idx == 0 else (('%%%d.%de' % (fwdthn, fprec)))) for idx, lbl in enumerate(hdrlbl)] fmtstr = (' ').join(fldfmt) # Construct a list of field widths for each field by extracting # field widths from field format strings cre = re.compile(r'%-?(\d+)') fldwid = [] for fmt in fldfmt: mtch = cre.match(fmt) if mtch is None: raise ValueError("Format string '%s' does not contain field " "width" % fmt) else: fldwid.append(int(mtch.group(1))) # Construct list of field header strings formatted to the # appropriate field width, and join to construct a combined field # header string hdrlst = [('%-*s' % (w, t)) for t, w in zip(hdrlbl, fldwid)] hdrstr = (' ').join(hdrlst) return hdrstr, fmtstr, len(hdrstr)
[ "def", "solve_status_str", "(", "hdrlbl", ",", "fmtmap", "=", "None", ",", "fwdth0", "=", "4", ",", "fwdthdlt", "=", "6", ",", "fprec", "=", "2", ")", ":", "if", "fmtmap", "is", "None", ":", "fmtmap", "=", "{", "}", "fwdthn", "=", "fprec", "+", "...
Construct header and format details for status display of an iterative solver. Parameters ---------- hdrlbl : tuple of strings Tuple of field header strings fmtmap : dict or None, optional (default None) A dict providing a mapping from field header strings to print format strings, providing a mechanism for fields with print formats that depart from the standard format fwdth0 : int, optional (default 4) Number of characters in first field formatted for integers fwdthdlt : int, optional (default 6) The width of fields formatted for floats is the sum of the value of this parameter and the field precision fprec : int, optional (default 2) Precision of fields formatted for floats Returns ------- hdrstr : string Complete header string fmtstr : string Complete print formatting string for numeric values nsep : integer Number of characters in separator string
[ "Construct", "header", "and", "format", "details", "for", "status", "display", "of", "an", "iterative", "solver", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/common.py#L224-L288
train
210,173
bwohlberg/sporco
sporco/common.py
IterativeSolver.set_attr
def set_attr(self, name, val, dval=None, dtype=None, reset=False): """Set an object attribute by its name. The attribute value can be specified as a primary value `val`, and as default value 'dval` that will be used if the primary value is None. This arrangement allows an attribute to be set from an entry in an options object, passed as `val`, while specifying a default value to use, passed as `dval` in the event that the options entry is None. Unless `reset` is True, the attribute is only set if it doesn't exist, or if it exists with value None. This arrangement allows for attributes to be set in both base and derived class initialisers, with the derived class value taking preference. Parameters ---------- name : string Attribute name val : any Primary attribute value dval : any Default attribute value in case `val` is None dtype : data-type, optional (default None) If the `dtype` parameter is not None, the attribute `name` is set to `val` (which is assumed to be of numeric type) after conversion to the specified type. reset : bool, optional (default False) Flag indicating whether attribute assignment should be conditional on the attribute not existing or having value None. If False, an attribute value other than None will not be overwritten. """ # If `val` is None and `dval` is not None, replace it with dval if dval is not None and val is None: val = dval # If dtype is not None, assume val is numeric and convert it to # type dtype if dtype is not None and val is not None: if isinstance(dtype, type): val = dtype(val) else: val = dtype.type(val) # Set attribute value depending on reset flag and whether the # attribute exists and is None if reset or not hasattr(self, name) or \ (hasattr(self, name) and getattr(self, name) is None): setattr(self, name, val)
python
def set_attr(self, name, val, dval=None, dtype=None, reset=False): """Set an object attribute by its name. The attribute value can be specified as a primary value `val`, and as default value 'dval` that will be used if the primary value is None. This arrangement allows an attribute to be set from an entry in an options object, passed as `val`, while specifying a default value to use, passed as `dval` in the event that the options entry is None. Unless `reset` is True, the attribute is only set if it doesn't exist, or if it exists with value None. This arrangement allows for attributes to be set in both base and derived class initialisers, with the derived class value taking preference. Parameters ---------- name : string Attribute name val : any Primary attribute value dval : any Default attribute value in case `val` is None dtype : data-type, optional (default None) If the `dtype` parameter is not None, the attribute `name` is set to `val` (which is assumed to be of numeric type) after conversion to the specified type. reset : bool, optional (default False) Flag indicating whether attribute assignment should be conditional on the attribute not existing or having value None. If False, an attribute value other than None will not be overwritten. """ # If `val` is None and `dval` is not None, replace it with dval if dval is not None and val is None: val = dval # If dtype is not None, assume val is numeric and convert it to # type dtype if dtype is not None and val is not None: if isinstance(dtype, type): val = dtype(val) else: val = dtype.type(val) # Set attribute value depending on reset flag and whether the # attribute exists and is None if reset or not hasattr(self, name) or \ (hasattr(self, name) and getattr(self, name) is None): setattr(self, name, val)
[ "def", "set_attr", "(", "self", ",", "name", ",", "val", ",", "dval", "=", "None", ",", "dtype", "=", "None", ",", "reset", "=", "False", ")", ":", "# If `val` is None and `dval` is not None, replace it with dval", "if", "dval", "is", "not", "None", "and", "...
Set an object attribute by its name. The attribute value can be specified as a primary value `val`, and as default value 'dval` that will be used if the primary value is None. This arrangement allows an attribute to be set from an entry in an options object, passed as `val`, while specifying a default value to use, passed as `dval` in the event that the options entry is None. Unless `reset` is True, the attribute is only set if it doesn't exist, or if it exists with value None. This arrangement allows for attributes to be set in both base and derived class initialisers, with the derived class value taking preference. Parameters ---------- name : string Attribute name val : any Primary attribute value dval : any Default attribute value in case `val` is None dtype : data-type, optional (default None) If the `dtype` parameter is not None, the attribute `name` is set to `val` (which is assumed to be of numeric type) after conversion to the specified type. reset : bool, optional (default False) Flag indicating whether attribute assignment should be conditional on the attribute not existing or having value None. If False, an attribute value other than None will not be overwritten.
[ "Set", "an", "object", "attribute", "by", "its", "name", ".", "The", "attribute", "value", "can", "be", "specified", "as", "a", "primary", "value", "val", "and", "as", "default", "value", "dval", "that", "will", "be", "used", "if", "the", "primary", "val...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/common.py#L171-L219
train
210,174
bwohlberg/sporco
sporco/mpiutil.py
_get_rank_limits
def _get_rank_limits(comm, arrlen): """Determine the chunk of the grid that has to be computed per process. The grid has been 'flattened' and has arrlen length. The chunk assigned to each process depends on its rank in the MPI communicator. Parameters ---------- comm : MPI communicator object Describes topology of network: number of processes, rank arrlen : int Number of points in grid search. Returns ------- begin : int Index, with respect to 'flattened' grid, where the chunk for this process starts. end : int Index, with respect to 'flattened' grid, where the chunk for this process ends. """ rank = comm.Get_rank() # Id of this process size = comm.Get_size() # Total number of processes in communicator end = 0 # The scan should be done with ints, not floats ranklen = int(arrlen / size) if rank < arrlen % size: ranklen += 1 # Compute upper limit based on the sizes covered by the processes # with less rank end = comm.scan(sendobj=ranklen, op=MPI.SUM) begin = end - ranklen return (begin, end)
python
def _get_rank_limits(comm, arrlen): """Determine the chunk of the grid that has to be computed per process. The grid has been 'flattened' and has arrlen length. The chunk assigned to each process depends on its rank in the MPI communicator. Parameters ---------- comm : MPI communicator object Describes topology of network: number of processes, rank arrlen : int Number of points in grid search. Returns ------- begin : int Index, with respect to 'flattened' grid, where the chunk for this process starts. end : int Index, with respect to 'flattened' grid, where the chunk for this process ends. """ rank = comm.Get_rank() # Id of this process size = comm.Get_size() # Total number of processes in communicator end = 0 # The scan should be done with ints, not floats ranklen = int(arrlen / size) if rank < arrlen % size: ranklen += 1 # Compute upper limit based on the sizes covered by the processes # with less rank end = comm.scan(sendobj=ranklen, op=MPI.SUM) begin = end - ranklen return (begin, end)
[ "def", "_get_rank_limits", "(", "comm", ",", "arrlen", ")", ":", "rank", "=", "comm", ".", "Get_rank", "(", ")", "# Id of this process", "size", "=", "comm", ".", "Get_size", "(", ")", "# Total number of processes in communicator", "end", "=", "0", "# The scan s...
Determine the chunk of the grid that has to be computed per process. The grid has been 'flattened' and has arrlen length. The chunk assigned to each process depends on its rank in the MPI communicator. Parameters ---------- comm : MPI communicator object Describes topology of network: number of processes, rank arrlen : int Number of points in grid search. Returns ------- begin : int Index, with respect to 'flattened' grid, where the chunk for this process starts. end : int Index, with respect to 'flattened' grid, where the chunk for this process ends.
[ "Determine", "the", "chunk", "of", "the", "grid", "that", "has", "to", "be", "computed", "per", "process", ".", "The", "grid", "has", "been", "flattened", "and", "has", "arrlen", "length", ".", "The", "chunk", "assigned", "to", "each", "process", "depends"...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/mpiutil.py#L28-L63
train
210,175
bwohlberg/sporco
sporco/admm/ccmodmd.py
ConvCnstrMODMaskDcpl_Consensus.relax_AX
def relax_AX(self): """The parent class method that this method overrides only implements the relaxation step for the variables of the baseline consensus algorithm. This method calls the overridden method and then implements the relaxation step for the additional variables required for the mask decoupling modification to the baseline algorithm. """ super(ConvCnstrMODMaskDcpl_Consensus, self).relax_AX() self.AX1nr = sl.irfftn(sl.inner(self.Zf, self.swapaxes(self.Xf), axis=self.cri.axisM), self.cri.Nv, self.cri.axisN) if self.rlx == 1.0: self.AX1 = self.AX1nr else: alpha = self.rlx self.AX1 = alpha*self.AX1nr + (1-alpha)*(self.Y1 + self.S)
python
def relax_AX(self): """The parent class method that this method overrides only implements the relaxation step for the variables of the baseline consensus algorithm. This method calls the overridden method and then implements the relaxation step for the additional variables required for the mask decoupling modification to the baseline algorithm. """ super(ConvCnstrMODMaskDcpl_Consensus, self).relax_AX() self.AX1nr = sl.irfftn(sl.inner(self.Zf, self.swapaxes(self.Xf), axis=self.cri.axisM), self.cri.Nv, self.cri.axisN) if self.rlx == 1.0: self.AX1 = self.AX1nr else: alpha = self.rlx self.AX1 = alpha*self.AX1nr + (1-alpha)*(self.Y1 + self.S)
[ "def", "relax_AX", "(", "self", ")", ":", "super", "(", "ConvCnstrMODMaskDcpl_Consensus", ",", "self", ")", ".", "relax_AX", "(", ")", "self", ".", "AX1nr", "=", "sl", ".", "irfftn", "(", "sl", ".", "inner", "(", "self", ".", "Zf", ",", "self", ".", ...
The parent class method that this method overrides only implements the relaxation step for the variables of the baseline consensus algorithm. This method calls the overridden method and then implements the relaxation step for the additional variables required for the mask decoupling modification to the baseline algorithm.
[ "The", "parent", "class", "method", "that", "this", "method", "overrides", "only", "implements", "the", "relaxation", "step", "for", "the", "variables", "of", "the", "baseline", "consensus", "algorithm", ".", "This", "method", "calls", "the", "overridden", "meth...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/ccmodmd.py#L902-L919
train
210,176
bwohlberg/sporco
sporco/admm/ccmodmd.py
ConvCnstrMODMaskDcpl_Consensus.xstep
def xstep(self): """The xstep of the baseline consensus class from which this class is derived is re-used to implement the xstep of the modified algorithm by replacing ``self.ZSf``, which is constant in the baseline algorithm, with a quantity derived from the additional variables ``self.Y1`` and ``self.U1``. It is also necessary to set the penalty parameter to unity for the duration of the x step. """ self.YU1[:] = self.Y1 - self.U1 self.ZSf = np.conj(self.Zf) * (self.Sf + sl.rfftn( self.YU1, None, self.cri.axisN)) rho = self.rho self.rho = 1.0 super(ConvCnstrMODMaskDcpl_Consensus, self).xstep() self.rho = rho
python
def xstep(self): """The xstep of the baseline consensus class from which this class is derived is re-used to implement the xstep of the modified algorithm by replacing ``self.ZSf``, which is constant in the baseline algorithm, with a quantity derived from the additional variables ``self.Y1`` and ``self.U1``. It is also necessary to set the penalty parameter to unity for the duration of the x step. """ self.YU1[:] = self.Y1 - self.U1 self.ZSf = np.conj(self.Zf) * (self.Sf + sl.rfftn( self.YU1, None, self.cri.axisN)) rho = self.rho self.rho = 1.0 super(ConvCnstrMODMaskDcpl_Consensus, self).xstep() self.rho = rho
[ "def", "xstep", "(", "self", ")", ":", "self", ".", "YU1", "[", ":", "]", "=", "self", ".", "Y1", "-", "self", ".", "U1", "self", ".", "ZSf", "=", "np", ".", "conj", "(", "self", ".", "Zf", ")", "*", "(", "self", ".", "Sf", "+", "sl", "."...
The xstep of the baseline consensus class from which this class is derived is re-used to implement the xstep of the modified algorithm by replacing ``self.ZSf``, which is constant in the baseline algorithm, with a quantity derived from the additional variables ``self.Y1`` and ``self.U1``. It is also necessary to set the penalty parameter to unity for the duration of the x step.
[ "The", "xstep", "of", "the", "baseline", "consensus", "class", "from", "which", "this", "class", "is", "derived", "is", "re", "-", "used", "to", "implement", "the", "xstep", "of", "the", "modified", "algorithm", "by", "replacing", "self", ".", "ZSf", "whic...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/ccmodmd.py#L923-L939
train
210,177
bwohlberg/sporco
sporco/admm/ccmodmd.py
ConvCnstrMODMaskDcpl_Consensus.compute_residuals
def compute_residuals(self): """Compute residuals and stopping thresholds. The parent class method is overridden to ensure that the residual calculations include the additional variables introduced in the modification to the baseline algorithm. """ # The full primary residual is straightforward to compute from # the primary residuals for the baseline algorithm and for the # additional variables r0 = self.rsdl_r(self.AXnr, self.Y) r1 = self.AX1nr - self.Y1 - self.S r = np.sqrt(np.sum(r0**2) + np.sum(r1**2)) # The full dual residual is more complicated to compute than the # full primary residual ATU = self.swapaxes(self.U) + sl.irfftn( np.conj(self.Zf) * sl.rfftn(self.U1, self.cri.Nv, self.cri.axisN), self.cri.Nv, self.cri.axisN) s = self.rho * np.linalg.norm(ATU) # The normalisation factor for the full primal residual is also not # straightforward nAX = np.sqrt(np.linalg.norm(self.AXnr)**2 + np.linalg.norm(self.AX1nr)**2) nY = np.sqrt(np.linalg.norm(self.Y)**2 + np.linalg.norm(self.Y1)**2) rn = max(nAX, nY, np.linalg.norm(self.S)) # The normalisation factor for the full dual residual is # straightforward to compute sn = self.rho * np.sqrt(np.linalg.norm(self.U)**2 + np.linalg.norm(self.U1)**2) # Final residual values and stopping tolerances depend on # whether standard or normalised residuals are specified via the # options object if self.opt['AutoRho', 'StdResiduals']: epri = np.sqrt(self.Nc)*self.opt['AbsStopTol'] + \ rn*self.opt['RelStopTol'] edua = np.sqrt(self.Nx)*self.opt['AbsStopTol'] + \ sn*self.opt['RelStopTol'] else: if rn == 0.0: rn = 1.0 if sn == 0.0: sn = 1.0 r /= rn s /= sn epri = np.sqrt(self.Nc)*self.opt['AbsStopTol']/rn + \ self.opt['RelStopTol'] edua = np.sqrt(self.Nx)*self.opt['AbsStopTol']/sn + \ self.opt['RelStopTol'] return r, s, epri, edua
python
def compute_residuals(self): """Compute residuals and stopping thresholds. The parent class method is overridden to ensure that the residual calculations include the additional variables introduced in the modification to the baseline algorithm. """ # The full primary residual is straightforward to compute from # the primary residuals for the baseline algorithm and for the # additional variables r0 = self.rsdl_r(self.AXnr, self.Y) r1 = self.AX1nr - self.Y1 - self.S r = np.sqrt(np.sum(r0**2) + np.sum(r1**2)) # The full dual residual is more complicated to compute than the # full primary residual ATU = self.swapaxes(self.U) + sl.irfftn( np.conj(self.Zf) * sl.rfftn(self.U1, self.cri.Nv, self.cri.axisN), self.cri.Nv, self.cri.axisN) s = self.rho * np.linalg.norm(ATU) # The normalisation factor for the full primal residual is also not # straightforward nAX = np.sqrt(np.linalg.norm(self.AXnr)**2 + np.linalg.norm(self.AX1nr)**2) nY = np.sqrt(np.linalg.norm(self.Y)**2 + np.linalg.norm(self.Y1)**2) rn = max(nAX, nY, np.linalg.norm(self.S)) # The normalisation factor for the full dual residual is # straightforward to compute sn = self.rho * np.sqrt(np.linalg.norm(self.U)**2 + np.linalg.norm(self.U1)**2) # Final residual values and stopping tolerances depend on # whether standard or normalised residuals are specified via the # options object if self.opt['AutoRho', 'StdResiduals']: epri = np.sqrt(self.Nc)*self.opt['AbsStopTol'] + \ rn*self.opt['RelStopTol'] edua = np.sqrt(self.Nx)*self.opt['AbsStopTol'] + \ sn*self.opt['RelStopTol'] else: if rn == 0.0: rn = 1.0 if sn == 0.0: sn = 1.0 r /= rn s /= sn epri = np.sqrt(self.Nc)*self.opt['AbsStopTol']/rn + \ self.opt['RelStopTol'] edua = np.sqrt(self.Nx)*self.opt['AbsStopTol']/sn + \ self.opt['RelStopTol'] return r, s, epri, edua
[ "def", "compute_residuals", "(", "self", ")", ":", "# The full primary residual is straightforward to compute from", "# the primary residuals for the baseline algorithm and for the", "# additional variables", "r0", "=", "self", ".", "rsdl_r", "(", "self", ".", "AXnr", ",", "sel...
Compute residuals and stopping thresholds. The parent class method is overridden to ensure that the residual calculations include the additional variables introduced in the modification to the baseline algorithm.
[ "Compute", "residuals", "and", "stopping", "thresholds", ".", "The", "parent", "class", "method", "is", "overridden", "to", "ensure", "that", "the", "residual", "calculations", "include", "the", "additional", "variables", "introduced", "in", "the", "modification", ...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/ccmodmd.py#L978-L1032
train
210,178
bwohlberg/sporco
sporco/admm/rpca.py
RobustPCA.obfn_fvar
def obfn_fvar(self): """Variable to be evaluated in computing regularisation term, depending on 'fEvalX' option value. """ if self.opt['fEvalX']: return self.X else: return self.cnst_c() - self.cnst_B(self.Y)
python
def obfn_fvar(self): """Variable to be evaluated in computing regularisation term, depending on 'fEvalX' option value. """ if self.opt['fEvalX']: return self.X else: return self.cnst_c() - self.cnst_B(self.Y)
[ "def", "obfn_fvar", "(", "self", ")", ":", "if", "self", ".", "opt", "[", "'fEvalX'", "]", ":", "return", "self", ".", "X", "else", ":", "return", "self", ".", "cnst_c", "(", ")", "-", "self", ".", "cnst_B", "(", "self", ".", "Y", ")" ]
Variable to be evaluated in computing regularisation term, depending on 'fEvalX' option value.
[ "Variable", "to", "be", "evaluated", "in", "computing", "regularisation", "term", "depending", "on", "fEvalX", "option", "value", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/rpca.py#L191-L199
train
210,179
bwohlberg/sporco
sporco/admm/cmod.py
normalise
def normalise(v): """Normalise columns of matrix. Parameters ---------- v : array_like Array with columns to be normalised Returns ------- vnrm : ndarray Normalised array """ vn = np.sqrt(np.sum(v**2, 0)) vn[vn == 0] = 1.0 return np.asarray(v / vn, dtype=v.dtype)
python
def normalise(v): """Normalise columns of matrix. Parameters ---------- v : array_like Array with columns to be normalised Returns ------- vnrm : ndarray Normalised array """ vn = np.sqrt(np.sum(v**2, 0)) vn[vn == 0] = 1.0 return np.asarray(v / vn, dtype=v.dtype)
[ "def", "normalise", "(", "v", ")", ":", "vn", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "v", "**", "2", ",", "0", ")", ")", "vn", "[", "vn", "==", "0", "]", "=", "1.0", "return", "np", ".", "asarray", "(", "v", "/", "vn", ",", ...
Normalise columns of matrix. Parameters ---------- v : array_like Array with columns to be normalised Returns ------- vnrm : ndarray Normalised array
[ "Normalise", "columns", "of", "matrix", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cmod.py#L327-L343
train
210,180
bwohlberg/sporco
sporco/admm/cmod.py
CnstrMOD.rhochange
def rhochange(self): """Re-factorise matrix when rho changes""" self.lu, self.piv = sl.lu_factor(self.Z, self.rho) self.lu = np.asarray(self.lu, dtype=self.dtype)
python
def rhochange(self): """Re-factorise matrix when rho changes""" self.lu, self.piv = sl.lu_factor(self.Z, self.rho) self.lu = np.asarray(self.lu, dtype=self.dtype)
[ "def", "rhochange", "(", "self", ")", ":", "self", ".", "lu", ",", "self", ".", "piv", "=", "sl", ".", "lu_factor", "(", "self", ".", "Z", ",", "self", ".", "rho", ")", "self", ".", "lu", "=", "np", ".", "asarray", "(", "self", ".", "lu", ","...
Re-factorise matrix when rho changes
[ "Re", "-", "factorise", "matrix", "when", "rho", "changes" ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cmod.py#L279-L283
train
210,181
bwohlberg/sporco
sporco/cupy/_cp_util.py
cupy_wrapper
def cupy_wrapper(func): """A wrapper function that converts numpy ndarray arguments to cupy arrays, and convert any cupy arrays returned by the wrapped function into numpy ndarrays. """ @functools.wraps(func) def wrapped(*args, **kwargs): args = list(args) for n, a in enumerate(args): if isinstance(a, np.ndarray): args[n] = cp.asarray(a) for k, v in kwargs.items(): if isinstance(v, np.ndarray): kwargs[k] = cp.asarray(v) rtn = func(*args, **kwargs) if isinstance(rtn, (list, tuple)): for n, a in enumerate(rtn): if isinstance(a, cp.core.core.ndarray): rtn[n] = cp.asnumpy(a) else: if isinstance(rtn, cp.core.core.ndarray): rtn = cp.asnumpy(rtn) return rtn return wrapped
python
def cupy_wrapper(func): """A wrapper function that converts numpy ndarray arguments to cupy arrays, and convert any cupy arrays returned by the wrapped function into numpy ndarrays. """ @functools.wraps(func) def wrapped(*args, **kwargs): args = list(args) for n, a in enumerate(args): if isinstance(a, np.ndarray): args[n] = cp.asarray(a) for k, v in kwargs.items(): if isinstance(v, np.ndarray): kwargs[k] = cp.asarray(v) rtn = func(*args, **kwargs) if isinstance(rtn, (list, tuple)): for n, a in enumerate(rtn): if isinstance(a, cp.core.core.ndarray): rtn[n] = cp.asnumpy(a) else: if isinstance(rtn, cp.core.core.ndarray): rtn = cp.asnumpy(rtn) return rtn return wrapped
[ "def", "cupy_wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "for", "n", ",", "a", "in", "enumerate",...
A wrapper function that converts numpy ndarray arguments to cupy arrays, and convert any cupy arrays returned by the wrapped function into numpy ndarrays.
[ "A", "wrapper", "function", "that", "converts", "numpy", "ndarray", "arguments", "to", "cupy", "arrays", "and", "convert", "any", "cupy", "arrays", "returned", "by", "the", "wrapped", "function", "into", "numpy", "ndarrays", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cupy/_cp_util.py#L40-L64
train
210,182
bwohlberg/sporco
sporco/admm/cbpdntv.py
ConvBPDNRecTV.block_sep1
def block_sep1(self, Y): """Separate variable into component corresponding to Y1 in Y.""" Y1 = Y[..., self.cri.M:] # If cri.Cd > 1 (multi-channel dictionary), we need to undo the # reshape performed in block_cat if self.cri.Cd > 1: shp = list(Y1.shape) shp[self.cri.axisM] = self.cri.dimN shp[self.cri.axisC] = self.cri.Cd Y1 = Y1.reshape(shp) # Axes are swapped here for similar reasons to those # motivating swapping in cbpdn.ConvTwoBlockCnstrnt.block_sep0 Y1 = np.swapaxes(Y1[..., np.newaxis], self.cri.axisM, -1) return Y1
python
def block_sep1(self, Y): """Separate variable into component corresponding to Y1 in Y.""" Y1 = Y[..., self.cri.M:] # If cri.Cd > 1 (multi-channel dictionary), we need to undo the # reshape performed in block_cat if self.cri.Cd > 1: shp = list(Y1.shape) shp[self.cri.axisM] = self.cri.dimN shp[self.cri.axisC] = self.cri.Cd Y1 = Y1.reshape(shp) # Axes are swapped here for similar reasons to those # motivating swapping in cbpdn.ConvTwoBlockCnstrnt.block_sep0 Y1 = np.swapaxes(Y1[..., np.newaxis], self.cri.axisM, -1) return Y1
[ "def", "block_sep1", "(", "self", ",", "Y", ")", ":", "Y1", "=", "Y", "[", "...", ",", "self", ".", "cri", ".", "M", ":", "]", "# If cri.Cd > 1 (multi-channel dictionary), we need to undo the", "# reshape performed in block_cat", "if", "self", ".", "cri", ".", ...
Separate variable into component corresponding to Y1 in Y.
[ "Separate", "variable", "into", "component", "corresponding", "to", "Y1", "in", "Y", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdntv.py#L978-L995
train
210,183
bwohlberg/sporco
sporco/admm/cbpdntv.py
ConvBPDNRecTV.block_cat
def block_cat(self, Y0, Y1): """Concatenate components corresponding to Y0 and Y1 blocks into Y. """ # Axes are swapped here for similar reasons to those # motivating swapping in cbpdn.ConvTwoBlockCnstrnt.block_cat Y1sa = np.swapaxes(Y1, self.cri.axisM, -1)[..., 0] # If cri.Cd > 1 (multi-channel dictionary) Y0 has a singleton # channel axis but Y1 has a non-singleton channel axis. To make # it possible to concatenate Y0 and Y1, we reshape Y1 by a # partial ravel of axisM and axisC onto axisM. if self.cri.Cd > 1: shp = list(Y1sa.shape) shp[self.cri.axisM] *= shp[self.cri.axisC] shp[self.cri.axisC] = 1 Y1sa = Y1sa.reshape(shp) return np.concatenate((Y0, Y1sa), axis=self.cri.axisM)
python
def block_cat(self, Y0, Y1): """Concatenate components corresponding to Y0 and Y1 blocks into Y. """ # Axes are swapped here for similar reasons to those # motivating swapping in cbpdn.ConvTwoBlockCnstrnt.block_cat Y1sa = np.swapaxes(Y1, self.cri.axisM, -1)[..., 0] # If cri.Cd > 1 (multi-channel dictionary) Y0 has a singleton # channel axis but Y1 has a non-singleton channel axis. To make # it possible to concatenate Y0 and Y1, we reshape Y1 by a # partial ravel of axisM and axisC onto axisM. if self.cri.Cd > 1: shp = list(Y1sa.shape) shp[self.cri.axisM] *= shp[self.cri.axisC] shp[self.cri.axisC] = 1 Y1sa = Y1sa.reshape(shp) return np.concatenate((Y0, Y1sa), axis=self.cri.axisM)
[ "def", "block_cat", "(", "self", ",", "Y0", ",", "Y1", ")", ":", "# Axes are swapped here for similar reasons to those", "# motivating swapping in cbpdn.ConvTwoBlockCnstrnt.block_cat", "Y1sa", "=", "np", ".", "swapaxes", "(", "Y1", ",", "self", ".", "cri", ".", "axisM...
Concatenate components corresponding to Y0 and Y1 blocks into Y.
[ "Concatenate", "components", "corresponding", "to", "Y0", "and", "Y1", "blocks", "into", "Y", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdntv.py#L999-L1018
train
210,184
bwohlberg/sporco
sporco/admm/cbpdntv.py
ConvBPDNRecTV.obfn_g0var
def obfn_g0var(self): """Variable to be evaluated in computing the TV regularisation term, depending on the ``gEvalY`` option value. """ # Use of self.block_sep0(self.AXnr) instead of self.cnst_A0(self.X) # reduces number of calls to self.cnst_A0 return self.var_y0() if self.opt['gEvalY'] else \ self.block_sep0(self.AXnr)
python
def obfn_g0var(self): """Variable to be evaluated in computing the TV regularisation term, depending on the ``gEvalY`` option value. """ # Use of self.block_sep0(self.AXnr) instead of self.cnst_A0(self.X) # reduces number of calls to self.cnst_A0 return self.var_y0() if self.opt['gEvalY'] else \ self.block_sep0(self.AXnr)
[ "def", "obfn_g0var", "(", "self", ")", ":", "# Use of self.block_sep0(self.AXnr) instead of self.cnst_A0(self.X)", "# reduces number of calls to self.cnst_A0", "return", "self", ".", "var_y0", "(", ")", "if", "self", ".", "opt", "[", "'gEvalY'", "]", "else", "self", "."...
Variable to be evaluated in computing the TV regularisation term, depending on the ``gEvalY`` option value.
[ "Variable", "to", "be", "evaluated", "in", "computing", "the", "TV", "regularisation", "term", "depending", "on", "the", "gEvalY", "option", "value", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdntv.py#L1165-L1173
train
210,185
bwohlberg/sporco
sporco/admm/bpdn.py
GenericBPDN.rhochange
def rhochange(self): """Re-factorise matrix when rho changes.""" self.lu, self.piv = sl.cho_factor(self.D, self.rho) self.lu = np.asarray(self.lu, dtype=self.dtype)
python
def rhochange(self): """Re-factorise matrix when rho changes.""" self.lu, self.piv = sl.cho_factor(self.D, self.rho) self.lu = np.asarray(self.lu, dtype=self.dtype)
[ "def", "rhochange", "(", "self", ")", ":", "self", ".", "lu", ",", "self", ".", "piv", "=", "sl", ".", "cho_factor", "(", "self", ".", "D", ",", "self", ".", "rho", ")", "self", ".", "lu", "=", "np", ".", "asarray", "(", "self", ".", "lu", ",...
Re-factorise matrix when rho changes.
[ "Re", "-", "factorise", "matrix", "when", "rho", "changes", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/bpdn.py#L262-L266
train
210,186
bwohlberg/sporco
sporco/admm/spline.py
SplineL1.rhochange
def rhochange(self): """Action to be taken when rho parameter is changed.""" self.Gamma = 1.0 / (1.0 + (self.lmbda/self.rho)*(self.Alpha**2))
python
def rhochange(self): """Action to be taken when rho parameter is changed.""" self.Gamma = 1.0 / (1.0 + (self.lmbda/self.rho)*(self.Alpha**2))
[ "def", "rhochange", "(", "self", ")", ":", "self", ".", "Gamma", "=", "1.0", "/", "(", "1.0", "+", "(", "self", ".", "lmbda", "/", "self", ".", "rho", ")", "*", "(", "self", ".", "Alpha", "**", "2", ")", ")" ]
Action to be taken when rho parameter is changed.
[ "Action", "to", "be", "taken", "when", "rho", "parameter", "is", "changed", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/spline.py#L215-L218
train
210,187
bwohlberg/sporco
sporco/cupy/_gputil.py
gpu_info
def gpu_info(): """Return a list of namedtuples representing attributes of each GPU device. """ GPUInfo = namedtuple('GPUInfo', ['name', 'driver', 'totalmem', 'freemem']) gpus = GPUtil.getGPUs() info = [] for g in gpus: info.append(GPUInfo(g.name, g.driver, g.memoryTotal, g.memoryFree)) return info
python
def gpu_info(): """Return a list of namedtuples representing attributes of each GPU device. """ GPUInfo = namedtuple('GPUInfo', ['name', 'driver', 'totalmem', 'freemem']) gpus = GPUtil.getGPUs() info = [] for g in gpus: info.append(GPUInfo(g.name, g.driver, g.memoryTotal, g.memoryFree)) return info
[ "def", "gpu_info", "(", ")", ":", "GPUInfo", "=", "namedtuple", "(", "'GPUInfo'", ",", "[", "'name'", ",", "'driver'", ",", "'totalmem'", ",", "'freemem'", "]", ")", "gpus", "=", "GPUtil", ".", "getGPUs", "(", ")", "info", "=", "[", "]", "for", "g", ...
Return a list of namedtuples representing attributes of each GPU device.
[ "Return", "a", "list", "of", "namedtuples", "representing", "attributes", "of", "each", "GPU", "device", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cupy/_gputil.py#L18-L28
train
210,188
bwohlberg/sporco
sporco/cupy/_gputil.py
gpu_load
def gpu_load(wproc=0.5, wmem=0.5): """Return a list of namedtuples representing the current load for each GPU device. The processor and memory loads are fractions between 0 and 1. The weighted load represents a weighted average of processor and memory loads using the parameters `wproc` and `wmem` respectively. """ GPULoad = namedtuple('GPULoad', ['processor', 'memory', 'weighted']) gpus = GPUtil.getGPUs() load = [] for g in gpus: wload = (wproc * g.load + wmem * g.memoryUtil) / (wproc + wmem) load.append(GPULoad(g.load, g.memoryUtil, wload)) return load
python
def gpu_load(wproc=0.5, wmem=0.5): """Return a list of namedtuples representing the current load for each GPU device. The processor and memory loads are fractions between 0 and 1. The weighted load represents a weighted average of processor and memory loads using the parameters `wproc` and `wmem` respectively. """ GPULoad = namedtuple('GPULoad', ['processor', 'memory', 'weighted']) gpus = GPUtil.getGPUs() load = [] for g in gpus: wload = (wproc * g.load + wmem * g.memoryUtil) / (wproc + wmem) load.append(GPULoad(g.load, g.memoryUtil, wload)) return load
[ "def", "gpu_load", "(", "wproc", "=", "0.5", ",", "wmem", "=", "0.5", ")", ":", "GPULoad", "=", "namedtuple", "(", "'GPULoad'", ",", "[", "'processor'", ",", "'memory'", ",", "'weighted'", "]", ")", "gpus", "=", "GPUtil", ".", "getGPUs", "(", ")", "l...
Return a list of namedtuples representing the current load for each GPU device. The processor and memory loads are fractions between 0 and 1. The weighted load represents a weighted average of processor and memory loads using the parameters `wproc` and `wmem` respectively.
[ "Return", "a", "list", "of", "namedtuples", "representing", "the", "current", "load", "for", "each", "GPU", "device", ".", "The", "processor", "and", "memory", "loads", "are", "fractions", "between", "0", "and", "1", ".", "The", "weighted", "load", "represen...
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cupy/_gputil.py#L31-L45
train
210,189
bwohlberg/sporco
sporco/cupy/_gputil.py
device_by_load
def device_by_load(wproc=0.5, wmem=0.5): """Get a list of GPU device ids ordered by increasing weighted average of processor and memory load. """ gl = gpu_load(wproc=wproc, wmem=wmem) # return np.argsort(np.asarray(gl)[:, -1]).tolist() return [idx for idx, load in sorted(enumerate( [g.weighted for g in gl]), key=(lambda x: x[1]))]
python
def device_by_load(wproc=0.5, wmem=0.5): """Get a list of GPU device ids ordered by increasing weighted average of processor and memory load. """ gl = gpu_load(wproc=wproc, wmem=wmem) # return np.argsort(np.asarray(gl)[:, -1]).tolist() return [idx for idx, load in sorted(enumerate( [g.weighted for g in gl]), key=(lambda x: x[1]))]
[ "def", "device_by_load", "(", "wproc", "=", "0.5", ",", "wmem", "=", "0.5", ")", ":", "gl", "=", "gpu_load", "(", "wproc", "=", "wproc", ",", "wmem", "=", "wmem", ")", "# return np.argsort(np.asarray(gl)[:, -1]).tolist()", "return", "[", "idx", "for", "idx",...
Get a list of GPU device ids ordered by increasing weighted average of processor and memory load.
[ "Get", "a", "list", "of", "GPU", "device", "ids", "ordered", "by", "increasing", "weighted", "average", "of", "processor", "and", "memory", "load", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cupy/_gputil.py#L48-L56
train
210,190
bwohlberg/sporco
sporco/cupy/_gputil.py
select_device_by_load
def select_device_by_load(wproc=0.5, wmem=0.5): """Set the current device for cupy as the device with the lowest weighted average of processor and memory load. """ ids = device_by_load(wproc=wproc, wmem=wmem) cp.cuda.Device(ids[0]).use() return ids[0]
python
def select_device_by_load(wproc=0.5, wmem=0.5): """Set the current device for cupy as the device with the lowest weighted average of processor and memory load. """ ids = device_by_load(wproc=wproc, wmem=wmem) cp.cuda.Device(ids[0]).use() return ids[0]
[ "def", "select_device_by_load", "(", "wproc", "=", "0.5", ",", "wmem", "=", "0.5", ")", ":", "ids", "=", "device_by_load", "(", "wproc", "=", "wproc", ",", "wmem", "=", "wmem", ")", "cp", ".", "cuda", ".", "Device", "(", "ids", "[", "0", "]", ")", ...
Set the current device for cupy as the device with the lowest weighted average of processor and memory load.
[ "Set", "the", "current", "device", "for", "cupy", "as", "the", "device", "with", "the", "lowest", "weighted", "average", "of", "processor", "and", "memory", "load", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cupy/_gputil.py#L59-L66
train
210,191
bwohlberg/sporco
sporco/cupy/__init__.py
load_module
def load_module(name): """Load the named module without registering it in ``sys.modules``. Parameters ---------- name : string Module name Returns ------- mod : module Loaded module """ spec = importlib.util.find_spec(name) mod = importlib.util.module_from_spec(spec) mod.__spec__ = spec mod.__loader__ = spec.loader spec.loader.exec_module(mod) return mod
python
def load_module(name): """Load the named module without registering it in ``sys.modules``. Parameters ---------- name : string Module name Returns ------- mod : module Loaded module """ spec = importlib.util.find_spec(name) mod = importlib.util.module_from_spec(spec) mod.__spec__ = spec mod.__loader__ = spec.loader spec.loader.exec_module(mod) return mod
[ "def", "load_module", "(", "name", ")", ":", "spec", "=", "importlib", ".", "util", ".", "find_spec", "(", "name", ")", "mod", "=", "importlib", ".", "util", ".", "module_from_spec", "(", "spec", ")", "mod", ".", "__spec__", "=", "spec", "mod", ".", ...
Load the named module without registering it in ``sys.modules``. Parameters ---------- name : string Module name Returns ------- mod : module Loaded module
[ "Load", "the", "named", "module", "without", "registering", "it", "in", "sys", ".", "modules", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cupy/__init__.py#L89-L108
train
210,192
bwohlberg/sporco
sporco/cupy/__init__.py
patch_module
def patch_module(name, pname, pfile=None, attrib=None): """Create a patched copy of the named module and register it in ``sys.modules``. Parameters ---------- name : string Name of source module pname : string Name of patched copy of module pfile : string or None, optional (default None) Value to assign as source file name of patched module attrib : dict or None, optional (default None) Dict of attribute names and values to assign to patched module Returns ------- mod : module Patched module """ if attrib is None: attrib = {} spec = importlib.util.find_spec(name) spec.name = pname if pfile is not None: spec.origin = pfile spec.loader.name = pname mod = importlib.util.module_from_spec(spec) mod.__spec__ = spec mod.__loader__ = spec.loader sys.modules[pname] = mod spec.loader.exec_module(mod) for k, v in attrib.items(): setattr(mod, k, v) return mod
python
def patch_module(name, pname, pfile=None, attrib=None): """Create a patched copy of the named module and register it in ``sys.modules``. Parameters ---------- name : string Name of source module pname : string Name of patched copy of module pfile : string or None, optional (default None) Value to assign as source file name of patched module attrib : dict or None, optional (default None) Dict of attribute names and values to assign to patched module Returns ------- mod : module Patched module """ if attrib is None: attrib = {} spec = importlib.util.find_spec(name) spec.name = pname if pfile is not None: spec.origin = pfile spec.loader.name = pname mod = importlib.util.module_from_spec(spec) mod.__spec__ = spec mod.__loader__ = spec.loader sys.modules[pname] = mod spec.loader.exec_module(mod) for k, v in attrib.items(): setattr(mod, k, v) return mod
[ "def", "patch_module", "(", "name", ",", "pname", ",", "pfile", "=", "None", ",", "attrib", "=", "None", ")", ":", "if", "attrib", "is", "None", ":", "attrib", "=", "{", "}", "spec", "=", "importlib", ".", "util", ".", "find_spec", "(", "name", ")"...
Create a patched copy of the named module and register it in ``sys.modules``. Parameters ---------- name : string Name of source module pname : string Name of patched copy of module pfile : string or None, optional (default None) Value to assign as source file name of patched module attrib : dict or None, optional (default None) Dict of attribute names and values to assign to patched module Returns ------- mod : module Patched module
[ "Create", "a", "patched", "copy", "of", "the", "named", "module", "and", "register", "it", "in", "sys", ".", "modules", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cupy/__init__.py#L111-L146
train
210,193
bwohlberg/sporco
sporco/cupy/__init__.py
sporco_cupy_patch_module
def sporco_cupy_patch_module(name, attrib=None): """Create a copy of the named sporco module, patch it to replace numpy with cupy, and register it in ``sys.modules``. Parameters ---------- name : string Name of source module attrib : dict or None, optional (default None) Dict of attribute names and values to assign to patched module Returns ------- mod : module Patched module """ # Patched module name is constructed from source module name # by replacing 'sporco.' with 'sporco.cupy.' pname = re.sub('^sporco.', 'sporco.cupy.', name) # Attribute dict always maps cupy module to 'np' attribute in # patched module if attrib is None: attrib = {} attrib.update({'np': cp}) # Create patched module mod = patch_module(name, pname, pfile='patched', attrib=attrib) mod.__spec__.has_location = False return mod
python
def sporco_cupy_patch_module(name, attrib=None): """Create a copy of the named sporco module, patch it to replace numpy with cupy, and register it in ``sys.modules``. Parameters ---------- name : string Name of source module attrib : dict or None, optional (default None) Dict of attribute names and values to assign to patched module Returns ------- mod : module Patched module """ # Patched module name is constructed from source module name # by replacing 'sporco.' with 'sporco.cupy.' pname = re.sub('^sporco.', 'sporco.cupy.', name) # Attribute dict always maps cupy module to 'np' attribute in # patched module if attrib is None: attrib = {} attrib.update({'np': cp}) # Create patched module mod = patch_module(name, pname, pfile='patched', attrib=attrib) mod.__spec__.has_location = False return mod
[ "def", "sporco_cupy_patch_module", "(", "name", ",", "attrib", "=", "None", ")", ":", "# Patched module name is constructed from source module name", "# by replacing 'sporco.' with 'sporco.cupy.'", "pname", "=", "re", ".", "sub", "(", "'^sporco.'", ",", "'sporco.cupy.'", ",...
Create a copy of the named sporco module, patch it to replace numpy with cupy, and register it in ``sys.modules``. Parameters ---------- name : string Name of source module attrib : dict or None, optional (default None) Dict of attribute names and values to assign to patched module Returns ------- mod : module Patched module
[ "Create", "a", "copy", "of", "the", "named", "sporco", "module", "patch", "it", "to", "replace", "numpy", "with", "cupy", "and", "register", "it", "in", "sys", ".", "modules", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cupy/__init__.py#L149-L177
train
210,194
bwohlberg/sporco
sporco/cupy/__init__.py
_list2array
def _list2array(lst): """Convert a list to a numpy array.""" if lst and isinstance(lst[0], cp.ndarray): return cp.hstack(lst) else: return cp.asarray(lst)
python
def _list2array(lst): """Convert a list to a numpy array.""" if lst and isinstance(lst[0], cp.ndarray): return cp.hstack(lst) else: return cp.asarray(lst)
[ "def", "_list2array", "(", "lst", ")", ":", "if", "lst", "and", "isinstance", "(", "lst", "[", "0", "]", ",", "cp", ".", "ndarray", ")", ":", "return", "cp", ".", "hstack", "(", "lst", ")", "else", ":", "return", "cp", ".", "asarray", "(", "lst",...
Convert a list to a numpy array.
[ "Convert", "a", "list", "to", "a", "numpy", "array", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cupy/__init__.py#L180-L186
train
210,195
bwohlberg/sporco
docs/source/automodule.py
sort_by_list_order
def sort_by_list_order(sortlist, reflist, reverse=False, fltr=False, slemap=None): """ Sort a list according to the order of entries in a reference list. Parameters ---------- sortlist : list List to be sorted reflist : list Reference list defining sorting order reverse : bool, optional (default False) Flag indicating whether to sort in reverse order fltr : bool, optional (default False) Flag indicating whether to filter `sortlist` to remove any entries that are not in `reflist` slemap : function or None, optional (default None) Function mapping a sortlist entry to the form of an entry in `reflist` Returns ------- sortedlist : list Sorted (and possibly filtered) version of sortlist """ def keyfunc(entry): if slemap is not None: rle = slemap(entry) if rle in reflist: # Ordering index taken from reflist return reflist.index(rle) else: # Ordering index taken from sortlist, offset # by the length of reflist so that entries # that are not in reflist retain their order # in sortlist return sortlist.index(entry) + len(reflist) if fltr: if slemap: sortlist = filter(lambda x: slemap(x) in reflist, sortlist) else: sortlist = filter(lambda x: x in reflist, sortlist) return sorted(sortlist, key=keyfunc, reverse=reverse)
python
def sort_by_list_order(sortlist, reflist, reverse=False, fltr=False, slemap=None): """ Sort a list according to the order of entries in a reference list. Parameters ---------- sortlist : list List to be sorted reflist : list Reference list defining sorting order reverse : bool, optional (default False) Flag indicating whether to sort in reverse order fltr : bool, optional (default False) Flag indicating whether to filter `sortlist` to remove any entries that are not in `reflist` slemap : function or None, optional (default None) Function mapping a sortlist entry to the form of an entry in `reflist` Returns ------- sortedlist : list Sorted (and possibly filtered) version of sortlist """ def keyfunc(entry): if slemap is not None: rle = slemap(entry) if rle in reflist: # Ordering index taken from reflist return reflist.index(rle) else: # Ordering index taken from sortlist, offset # by the length of reflist so that entries # that are not in reflist retain their order # in sortlist return sortlist.index(entry) + len(reflist) if fltr: if slemap: sortlist = filter(lambda x: slemap(x) in reflist, sortlist) else: sortlist = filter(lambda x: x in reflist, sortlist) return sorted(sortlist, key=keyfunc, reverse=reverse)
[ "def", "sort_by_list_order", "(", "sortlist", ",", "reflist", ",", "reverse", "=", "False", ",", "fltr", "=", "False", ",", "slemap", "=", "None", ")", ":", "def", "keyfunc", "(", "entry", ")", ":", "if", "slemap", "is", "not", "None", ":", "rle", "=...
Sort a list according to the order of entries in a reference list. Parameters ---------- sortlist : list List to be sorted reflist : list Reference list defining sorting order reverse : bool, optional (default False) Flag indicating whether to sort in reverse order fltr : bool, optional (default False) Flag indicating whether to filter `sortlist` to remove any entries that are not in `reflist` slemap : function or None, optional (default None) Function mapping a sortlist entry to the form of an entry in `reflist` Returns ------- sortedlist : list Sorted (and possibly filtered) version of sortlist
[ "Sort", "a", "list", "according", "to", "the", "order", "of", "entries", "in", "a", "reference", "list", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/automodule.py#L36-L81
train
210,196
bwohlberg/sporco
docs/source/automodule.py
get_module_classes
def get_module_classes(module): """ Get a list of module member classes. Parameters ---------- module : string or module object Module for which member list is to be generated Returns ------- mbrlst : list List of module functions """ clslst = get_module_members(module, type=inspect.isclass) return list(filter(lambda cls: not issubclass(cls, Exception), clslst))
python
def get_module_classes(module): """ Get a list of module member classes. Parameters ---------- module : string or module object Module for which member list is to be generated Returns ------- mbrlst : list List of module functions """ clslst = get_module_members(module, type=inspect.isclass) return list(filter(lambda cls: not issubclass(cls, Exception), clslst))
[ "def", "get_module_classes", "(", "module", ")", ":", "clslst", "=", "get_module_members", "(", "module", ",", "type", "=", "inspect", ".", "isclass", ")", "return", "list", "(", "filter", "(", "lambda", "cls", ":", "not", "issubclass", "(", "cls", ",", ...
Get a list of module member classes. Parameters ---------- module : string or module object Module for which member list is to be generated Returns ------- mbrlst : list List of module functions
[ "Get", "a", "list", "of", "module", "member", "classes", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/automodule.py#L234-L251
train
210,197
bwohlberg/sporco
docs/source/automodule.py
write_module_docs
def write_module_docs(pkgname, modpath, tmpltpath, outpath): """ Write the autosummary style docs for the specified package. Parameters ---------- pkgname : string Name of package to document modpath : string Path to package source root directory tmpltpath : string Directory path for autosummary template files outpath : string Directory path for RST output files """ dw = DocWriter(outpath, tmpltpath) modlst = get_module_names(modpath, pkgname) print('Making api docs:', end='') for modname in modlst: # Don't generate docs for cupy or cuda subpackages if 'cupy' in modname or 'cuda' in modname: continue try: mod = importlib.import_module(modname) except ModuleNotFoundError: print('Error importing module %s' % modname) continue # Skip any virtual modules created by the copy-and-patch # approach in sporco.cupy. These should already have been # skipped due to the test for cupy above. if mod.__file__ == 'patched': continue # Construct api docs for the current module if the docs file # does not exist, or if its source file has been updated more # recently than an existing docs file if hasattr(mod, '__path__'): srcpath = mod.__path__[0] else: srcpath = mod.__file__ dstpath = os.path.join(outpath, modname + '.rst') if is_newer_than(srcpath, dstpath): print(' %s' % modname, end='') dw.write(mod) print('')
python
def write_module_docs(pkgname, modpath, tmpltpath, outpath): """ Write the autosummary style docs for the specified package. Parameters ---------- pkgname : string Name of package to document modpath : string Path to package source root directory tmpltpath : string Directory path for autosummary template files outpath : string Directory path for RST output files """ dw = DocWriter(outpath, tmpltpath) modlst = get_module_names(modpath, pkgname) print('Making api docs:', end='') for modname in modlst: # Don't generate docs for cupy or cuda subpackages if 'cupy' in modname or 'cuda' in modname: continue try: mod = importlib.import_module(modname) except ModuleNotFoundError: print('Error importing module %s' % modname) continue # Skip any virtual modules created by the copy-and-patch # approach in sporco.cupy. These should already have been # skipped due to the test for cupy above. if mod.__file__ == 'patched': continue # Construct api docs for the current module if the docs file # does not exist, or if its source file has been updated more # recently than an existing docs file if hasattr(mod, '__path__'): srcpath = mod.__path__[0] else: srcpath = mod.__file__ dstpath = os.path.join(outpath, modname + '.rst') if is_newer_than(srcpath, dstpath): print(' %s' % modname, end='') dw.write(mod) print('')
[ "def", "write_module_docs", "(", "pkgname", ",", "modpath", ",", "tmpltpath", ",", "outpath", ")", ":", "dw", "=", "DocWriter", "(", "outpath", ",", "tmpltpath", ")", "modlst", "=", "get_module_names", "(", "modpath", ",", "pkgname", ")", "print", "(", "'M...
Write the autosummary style docs for the specified package. Parameters ---------- pkgname : string Name of package to document modpath : string Path to package source root directory tmpltpath : string Directory path for autosummary template files outpath : string Directory path for RST output files
[ "Write", "the", "autosummary", "style", "docs", "for", "the", "specified", "package", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/automodule.py#L335-L386
train
210,198
bwohlberg/sporco
docs/source/automodule.py
DocWriter.write
def write(self, module): """ Write the RST source document for generating the docs for a specified module. Parameters ---------- module : module object Module for which member list is to be generated """ modname = module.__name__ # Based on code in generate_autosummary_docs in https://git.io/fxpJS ns = {} ns['members'] = dir(module) ns['functions'] = list(map(lambda x: x.__name__, get_module_functions(module))) ns['classes'] = list(map(lambda x: x.__name__, get_module_classes(module))) ns['exceptions'] = list(map(lambda x: x.__name__, get_module_exceptions(module))) ns['fullname'] = modname ns['module'] = modname ns['objname'] = modname ns['name'] = modname.split('.')[-1] ns['objtype'] = 'module' ns['underline'] = len(modname) * '=' rndr = self.template.render(**ns) rstfile = os.path.join(self.outpath, modname + '.rst') with open(rstfile, 'w') as f: f.write(rndr)
python
def write(self, module): """ Write the RST source document for generating the docs for a specified module. Parameters ---------- module : module object Module for which member list is to be generated """ modname = module.__name__ # Based on code in generate_autosummary_docs in https://git.io/fxpJS ns = {} ns['members'] = dir(module) ns['functions'] = list(map(lambda x: x.__name__, get_module_functions(module))) ns['classes'] = list(map(lambda x: x.__name__, get_module_classes(module))) ns['exceptions'] = list(map(lambda x: x.__name__, get_module_exceptions(module))) ns['fullname'] = modname ns['module'] = modname ns['objname'] = modname ns['name'] = modname.split('.')[-1] ns['objtype'] = 'module' ns['underline'] = len(modname) * '=' rndr = self.template.render(**ns) rstfile = os.path.join(self.outpath, modname + '.rst') with open(rstfile, 'w') as f: f.write(rndr)
[ "def", "write", "(", "self", ",", "module", ")", ":", "modname", "=", "module", ".", "__name__", "# Based on code in generate_autosummary_docs in https://git.io/fxpJS", "ns", "=", "{", "}", "ns", "[", "'members'", "]", "=", "dir", "(", "module", ")", "ns", "["...
Write the RST source document for generating the docs for a specified module. Parameters ---------- module : module object Module for which member list is to be generated
[ "Write", "the", "RST", "source", "document", "for", "generating", "the", "docs", "for", "a", "specified", "module", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/automodule.py#L300-L332
train
210,199