id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
231,500
odlgroup/odl
odl/contrib/shearlab/shearlab_operator.py
ShearlabOperator.inverse
def inverse(self): """The inverse operator.""" op = self class ShearlabOperatorInverse(odl.Operator): """Inverse of the shearlet transform. See Also -------- odl.contrib.shearlab.ShearlabOperator """ def __init__(self): """Initialize a new instance.""" self.mutex = op.mutex self.shearlet_system = op.shearlet_system super(ShearlabOperatorInverse, self).__init__( op.range, op.domain, True) def _call(self, x): """``self(x)``.""" with op.mutex: x = np.moveaxis(x, 0, -1) return shearrec2D(x, op.shearlet_system) @property def adjoint(self): """The inverse operator.""" op = self class ShearlabOperatorInverseAdjoint(odl.Operator): """ Adjoint of the inverse/Inverse of the adjoint of shearlet transform. See Also -------- odl.contrib.shearlab.ShearlabOperator """ def __init__(self): """Initialize a new instance.""" self.mutex = op.mutex self.shearlet_system = op.shearlet_system super(ShearlabOperatorInverseAdjoint, self).__init__( op.range, op.domain, True) def _call(self, x): """``self(x)``.""" with op.mutex: result = shearrecadjoint2D(x, op.shearlet_system) return np.moveaxis(result, -1, 0) @property def adjoint(self): """The adjoint operator.""" return op @property def inverse(self): """The inverse operator.""" return op.inverse.adjoint return ShearlabOperatorInverseAdjoint() @property def inverse(self): """The inverse operator.""" return op return ShearlabOperatorInverse()
python
def inverse(self): op = self class ShearlabOperatorInverse(odl.Operator): """Inverse of the shearlet transform. See Also -------- odl.contrib.shearlab.ShearlabOperator """ def __init__(self): """Initialize a new instance.""" self.mutex = op.mutex self.shearlet_system = op.shearlet_system super(ShearlabOperatorInverse, self).__init__( op.range, op.domain, True) def _call(self, x): """``self(x)``.""" with op.mutex: x = np.moveaxis(x, 0, -1) return shearrec2D(x, op.shearlet_system) @property def adjoint(self): op = self class ShearlabOperatorInverseAdjoint(odl.Operator): """ Adjoint of the inverse/Inverse of the adjoint of shearlet transform. See Also -------- odl.contrib.shearlab.ShearlabOperator """ def __init__(self): """Initialize a new instance.""" self.mutex = op.mutex self.shearlet_system = op.shearlet_system super(ShearlabOperatorInverseAdjoint, self).__init__( op.range, op.domain, True) def _call(self, x): """``self(x)``.""" with op.mutex: result = shearrecadjoint2D(x, op.shearlet_system) return np.moveaxis(result, -1, 0) @property def adjoint(self): """The adjoint operator.""" return op @property def inverse(self): return op.inverse.adjoint return ShearlabOperatorInverseAdjoint() @property def inverse(self): return op return ShearlabOperatorInverse()
[ "def", "inverse", "(", "self", ")", ":", "op", "=", "self", "class", "ShearlabOperatorInverse", "(", "odl", ".", "Operator", ")", ":", "\"\"\"Inverse of the shearlet transform.\n\n See Also\n --------\n odl.contrib.shearlab.ShearlabOperator\n ...
The inverse operator.
[ "The", "inverse", "operator", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/shearlab/shearlab_operator.py#L138-L211
231,501
odlgroup/odl
odl/phantom/misc_phantoms.py
submarine
def submarine(space, smooth=True, taper=20.0): """Return a 'submarine' phantom consisting in an ellipsoid and a box. Parameters ---------- space : `DiscreteLp` Discretized space in which the phantom is supposed to be created. smooth : bool, optional If ``True``, the boundaries are smoothed out. Otherwise, the function steps from 0 to 1 at the boundaries. taper : float, optional Tapering parameter for the boundary smoothing. Larger values mean faster taper, i.e. sharper boundaries. Returns ------- phantom : ``space`` element The submarine phantom in ``space``. """ if space.ndim == 2: if smooth: return _submarine_2d_smooth(space, taper) else: return _submarine_2d_nonsmooth(space) else: raise ValueError('phantom only defined in 2 dimensions, got {}' ''.format(space.ndim))
python
def submarine(space, smooth=True, taper=20.0): if space.ndim == 2: if smooth: return _submarine_2d_smooth(space, taper) else: return _submarine_2d_nonsmooth(space) else: raise ValueError('phantom only defined in 2 dimensions, got {}' ''.format(space.ndim))
[ "def", "submarine", "(", "space", ",", "smooth", "=", "True", ",", "taper", "=", "20.0", ")", ":", "if", "space", ".", "ndim", "==", "2", ":", "if", "smooth", ":", "return", "_submarine_2d_smooth", "(", "space", ",", "taper", ")", "else", ":", "retur...
Return a 'submarine' phantom consisting in an ellipsoid and a box. Parameters ---------- space : `DiscreteLp` Discretized space in which the phantom is supposed to be created. smooth : bool, optional If ``True``, the boundaries are smoothed out. Otherwise, the function steps from 0 to 1 at the boundaries. taper : float, optional Tapering parameter for the boundary smoothing. Larger values mean faster taper, i.e. sharper boundaries. Returns ------- phantom : ``space`` element The submarine phantom in ``space``.
[ "Return", "a", "submarine", "phantom", "consisting", "in", "an", "ellipsoid", "and", "a", "box", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/phantom/misc_phantoms.py#L19-L45
231,502
odlgroup/odl
odl/phantom/misc_phantoms.py
_submarine_2d_smooth
def _submarine_2d_smooth(space, taper): """Return a 2d smooth 'submarine' phantom.""" def logistic(x, c): """Smoothed step function from 0 to 1, centered at 0.""" return 1. / (1 + np.exp(-c * x)) def blurred_ellipse(x): """Blurred characteristic function of an ellipse. If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``, the ellipse is centered at ``(0.6, 0.3)`` and has half-axes ``(0.4, 0.14)``. For other domains, the values are scaled accordingly. """ halfaxes = np.array([0.4, 0.14]) * space.domain.extent center = np.array([0.6, 0.3]) * space.domain.extent center += space.domain.min() # Efficiently calculate |z|^2, z = (x - center) / radii sq_ndist = np.zeros_like(x[0]) for xi, rad, cen in zip(x, halfaxes, center): sq_ndist = sq_ndist + ((xi - cen) / rad) ** 2 out = np.sqrt(sq_ndist) out -= 1 # Return logistic(taper * (1 - |z|)) return logistic(out, -taper) def blurred_rect(x): """Blurred characteristic function of a rectangle. If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``, the rect has lower left ``(0.56, 0.4)`` and upper right ``(0.76, 0.6)``. For other domains, the values are scaled accordingly. """ xlower = np.array([0.56, 0.4]) * space.domain.extent xlower += space.domain.min() xupper = np.array([0.76, 0.6]) * space.domain.extent xupper += space.domain.min() out = np.ones_like(x[0]) for xi, low, upp in zip(x, xlower, xupper): length = upp - low out = out * (logistic((xi - low) / length, taper) * logistic((upp - xi) / length, taper)) return out out = space.element(blurred_ellipse) out += space.element(blurred_rect) return out.ufuncs.minimum(1, out=out)
python
def _submarine_2d_smooth(space, taper): def logistic(x, c): """Smoothed step function from 0 to 1, centered at 0.""" return 1. / (1 + np.exp(-c * x)) def blurred_ellipse(x): """Blurred characteristic function of an ellipse. If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``, the ellipse is centered at ``(0.6, 0.3)`` and has half-axes ``(0.4, 0.14)``. For other domains, the values are scaled accordingly. """ halfaxes = np.array([0.4, 0.14]) * space.domain.extent center = np.array([0.6, 0.3]) * space.domain.extent center += space.domain.min() # Efficiently calculate |z|^2, z = (x - center) / radii sq_ndist = np.zeros_like(x[0]) for xi, rad, cen in zip(x, halfaxes, center): sq_ndist = sq_ndist + ((xi - cen) / rad) ** 2 out = np.sqrt(sq_ndist) out -= 1 # Return logistic(taper * (1 - |z|)) return logistic(out, -taper) def blurred_rect(x): """Blurred characteristic function of a rectangle. If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``, the rect has lower left ``(0.56, 0.4)`` and upper right ``(0.76, 0.6)``. For other domains, the values are scaled accordingly. """ xlower = np.array([0.56, 0.4]) * space.domain.extent xlower += space.domain.min() xupper = np.array([0.76, 0.6]) * space.domain.extent xupper += space.domain.min() out = np.ones_like(x[0]) for xi, low, upp in zip(x, xlower, xupper): length = upp - low out = out * (logistic((xi - low) / length, taper) * logistic((upp - xi) / length, taper)) return out out = space.element(blurred_ellipse) out += space.element(blurred_rect) return out.ufuncs.minimum(1, out=out)
[ "def", "_submarine_2d_smooth", "(", "space", ",", "taper", ")", ":", "def", "logistic", "(", "x", ",", "c", ")", ":", "\"\"\"Smoothed step function from 0 to 1, centered at 0.\"\"\"", "return", "1.", "/", "(", "1", "+", "np", ".", "exp", "(", "-", "c", "*", ...
Return a 2d smooth 'submarine' phantom.
[ "Return", "a", "2d", "smooth", "submarine", "phantom", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/phantom/misc_phantoms.py#L48-L99
231,503
odlgroup/odl
odl/phantom/misc_phantoms.py
_submarine_2d_nonsmooth
def _submarine_2d_nonsmooth(space): """Return a 2d nonsmooth 'submarine' phantom.""" def ellipse(x): """Characteristic function of an ellipse. If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``, the ellipse is centered at ``(0.6, 0.3)`` and has half-axes ``(0.4, 0.14)``. For other domains, the values are scaled accordingly. """ halfaxes = np.array([0.4, 0.14]) * space.domain.extent center = np.array([0.6, 0.3]) * space.domain.extent center += space.domain.min() sq_ndist = np.zeros_like(x[0]) for xi, rad, cen in zip(x, halfaxes, center): sq_ndist = sq_ndist + ((xi - cen) / rad) ** 2 return np.where(sq_ndist <= 1, 1, 0) def rect(x): """Characteristic function of a rectangle. If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``, the rect has lower left ``(0.56, 0.4)`` and upper right ``(0.76, 0.6)``. For other domains, the values are scaled accordingly. """ xlower = np.array([0.56, 0.4]) * space.domain.extent xlower += space.domain.min() xupper = np.array([0.76, 0.6]) * space.domain.extent xupper += space.domain.min() out = np.ones_like(x[0]) for xi, low, upp in zip(x, xlower, xupper): out = out * ((xi >= low) & (xi <= upp)) return out out = space.element(ellipse) out += space.element(rect) return out.ufuncs.minimum(1, out=out)
python
def _submarine_2d_nonsmooth(space): def ellipse(x): """Characteristic function of an ellipse. If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``, the ellipse is centered at ``(0.6, 0.3)`` and has half-axes ``(0.4, 0.14)``. For other domains, the values are scaled accordingly. """ halfaxes = np.array([0.4, 0.14]) * space.domain.extent center = np.array([0.6, 0.3]) * space.domain.extent center += space.domain.min() sq_ndist = np.zeros_like(x[0]) for xi, rad, cen in zip(x, halfaxes, center): sq_ndist = sq_ndist + ((xi - cen) / rad) ** 2 return np.where(sq_ndist <= 1, 1, 0) def rect(x): """Characteristic function of a rectangle. If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``, the rect has lower left ``(0.56, 0.4)`` and upper right ``(0.76, 0.6)``. For other domains, the values are scaled accordingly. """ xlower = np.array([0.56, 0.4]) * space.domain.extent xlower += space.domain.min() xupper = np.array([0.76, 0.6]) * space.domain.extent xupper += space.domain.min() out = np.ones_like(x[0]) for xi, low, upp in zip(x, xlower, xupper): out = out * ((xi >= low) & (xi <= upp)) return out out = space.element(ellipse) out += space.element(rect) return out.ufuncs.minimum(1, out=out)
[ "def", "_submarine_2d_nonsmooth", "(", "space", ")", ":", "def", "ellipse", "(", "x", ")", ":", "\"\"\"Characteristic function of an ellipse.\n\n If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``,\n the ellipse is centered at ``(0.6, 0.3)`` and has half-axes\n ``(0....
Return a 2d nonsmooth 'submarine' phantom.
[ "Return", "a", "2d", "nonsmooth", "submarine", "phantom", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/phantom/misc_phantoms.py#L102-L143
231,504
odlgroup/odl
odl/phantom/misc_phantoms.py
text
def text(space, text, font=None, border=0.2, inverted=True): """Create phantom from text. The text is represented by a scalar image taking values in [0, 1]. Depending on the choice of font, the text may or may not be anti-aliased. anti-aliased text can take any value between 0 and 1, while non-anti-aliased text produces a binary image. This method requires the ``pillow`` package. Parameters ---------- space : `DiscreteLp` Discretized space in which the phantom is supposed to be created. Must be two-dimensional. text : str The text that should be written onto the background. font : str, optional The font that should be used to write the text. Available options are platform dependent. Default: Platform dependent. 'arial' for windows, 'LiberationSans-Regular' for linux and 'Helvetica' for OSX border : float, optional Padding added around the text. 0.0 indicates that the phantom should occupy all of the space along its largest dimension while 1.0 gives a maximally padded image (text not visible). inverted : bool, optional If the phantom should be given in inverted style, i.e. white on black. Returns ------- phantom : ``space`` element The text phantom in ``space``. Notes ----- The set of available fonts is highly platform dependent, and there is no obvious way (except from trial and error) to find what fonts are supported on an arbitrary platform. In general, the fonts ``'arial'``, ``'calibri'`` and ``'impact'`` tend to be available on windows. Platform dependent tricks: **Linux**:: $ find /usr/share/fonts -name "*.[to]tf" """ from PIL import Image, ImageDraw, ImageFont if space.ndim != 2: raise ValueError('`space` must be two-dimensional') if font is None: platform = sys.platform if platform == 'win32': # Windows font = 'arial' elif platform == 'darwin': # Mac OSX font = 'Helvetica' else: # Assume platform is linux font = 'LiberationSans-Regular' text = str(text) # Figure out what font size we should use by creating a very high # resolution font and calculating the size of the text in this font init_size = 1000 init_pil_font = ImageFont.truetype(font + ".ttf", size=init_size, encoding="unic") init_text_width, init_text_height = init_pil_font.getsize(text) # True size is given by how much too large (or small) the example was scaled_init_size = (1.0 - border) * init_size size = scaled_init_size * min([space.shape[0] / init_text_width, space.shape[1] / init_text_height]) size = int(size) # Create font pil_font = ImageFont.truetype(font + ".ttf", size=size, encoding="unic") text_width, text_height = pil_font.getsize(text) # create a blank canvas with extra space between lines canvas = Image.new('RGB', space.shape, (255, 255, 255)) # draw the text onto the canvas draw = ImageDraw.Draw(canvas) offset = ((space.shape[0] - text_width) // 2, (space.shape[1] - text_height) // 2) white = "#000000" draw.text(offset, text, font=pil_font, fill=white) # Convert the canvas into an array with values in [0, 1] arr = np.asarray(canvas) arr = np.sum(arr, -1) arr = arr / np.max(arr) arr = np.rot90(arr, -1) if inverted: arr = 1 - arr return space.element(arr)
python
def text(space, text, font=None, border=0.2, inverted=True): from PIL import Image, ImageDraw, ImageFont if space.ndim != 2: raise ValueError('`space` must be two-dimensional') if font is None: platform = sys.platform if platform == 'win32': # Windows font = 'arial' elif platform == 'darwin': # Mac OSX font = 'Helvetica' else: # Assume platform is linux font = 'LiberationSans-Regular' text = str(text) # Figure out what font size we should use by creating a very high # resolution font and calculating the size of the text in this font init_size = 1000 init_pil_font = ImageFont.truetype(font + ".ttf", size=init_size, encoding="unic") init_text_width, init_text_height = init_pil_font.getsize(text) # True size is given by how much too large (or small) the example was scaled_init_size = (1.0 - border) * init_size size = scaled_init_size * min([space.shape[0] / init_text_width, space.shape[1] / init_text_height]) size = int(size) # Create font pil_font = ImageFont.truetype(font + ".ttf", size=size, encoding="unic") text_width, text_height = pil_font.getsize(text) # create a blank canvas with extra space between lines canvas = Image.new('RGB', space.shape, (255, 255, 255)) # draw the text onto the canvas draw = ImageDraw.Draw(canvas) offset = ((space.shape[0] - text_width) // 2, (space.shape[1] - text_height) // 2) white = "#000000" draw.text(offset, text, font=pil_font, fill=white) # Convert the canvas into an array with values in [0, 1] arr = np.asarray(canvas) arr = np.sum(arr, -1) arr = arr / np.max(arr) arr = np.rot90(arr, -1) if inverted: arr = 1 - arr return space.element(arr)
[ "def", "text", "(", "space", ",", "text", ",", "font", "=", "None", ",", "border", "=", "0.2", ",", "inverted", "=", "True", ")", ":", "from", "PIL", "import", "Image", ",", "ImageDraw", ",", "ImageFont", "if", "space", ".", "ndim", "!=", "2", ":",...
Create phantom from text. The text is represented by a scalar image taking values in [0, 1]. Depending on the choice of font, the text may or may not be anti-aliased. anti-aliased text can take any value between 0 and 1, while non-anti-aliased text produces a binary image. This method requires the ``pillow`` package. Parameters ---------- space : `DiscreteLp` Discretized space in which the phantom is supposed to be created. Must be two-dimensional. text : str The text that should be written onto the background. font : str, optional The font that should be used to write the text. Available options are platform dependent. Default: Platform dependent. 'arial' for windows, 'LiberationSans-Regular' for linux and 'Helvetica' for OSX border : float, optional Padding added around the text. 0.0 indicates that the phantom should occupy all of the space along its largest dimension while 1.0 gives a maximally padded image (text not visible). inverted : bool, optional If the phantom should be given in inverted style, i.e. white on black. Returns ------- phantom : ``space`` element The text phantom in ``space``. Notes ----- The set of available fonts is highly platform dependent, and there is no obvious way (except from trial and error) to find what fonts are supported on an arbitrary platform. In general, the fonts ``'arial'``, ``'calibri'`` and ``'impact'`` tend to be available on windows. Platform dependent tricks: **Linux**:: $ find /usr/share/fonts -name "*.[to]tf"
[ "Create", "phantom", "from", "text", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/phantom/misc_phantoms.py#L146-L251
231,505
odlgroup/odl
odl/space/weighting.py
Weighting.norm
def norm(self, x): """Calculate the norm of an element. This is the standard implementation using `inner`. Subclasses should override it for optimization purposes. Parameters ---------- x1 : `LinearSpaceElement` Element whose norm is calculated. Returns ------- norm : float The norm of the element. """ return float(np.sqrt(self.inner(x, x).real))
python
def norm(self, x): return float(np.sqrt(self.inner(x, x).real))
[ "def", "norm", "(", "self", ",", "x", ")", ":", "return", "float", "(", "np", ".", "sqrt", "(", "self", ".", "inner", "(", "x", ",", "x", ")", ".", "real", ")", ")" ]
Calculate the norm of an element. This is the standard implementation using `inner`. Subclasses should override it for optimization purposes. Parameters ---------- x1 : `LinearSpaceElement` Element whose norm is calculated. Returns ------- norm : float The norm of the element.
[ "Calculate", "the", "norm", "of", "an", "element", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/weighting.py#L116-L132
231,506
odlgroup/odl
odl/space/weighting.py
MatrixWeighting.is_valid
def is_valid(self): """Test if the matrix is positive definite Hermitian. If the matrix decomposition is available, this test checks if all eigenvalues are positive. Otherwise, the test tries to calculate a Cholesky decomposition, which can be very time-consuming for large matrices. Sparse matrices are not supported. """ # Lazy import to improve `import odl` time import scipy.sparse if scipy.sparse.isspmatrix(self.matrix): raise NotImplementedError('validation not supported for sparse ' 'matrices') elif self._eigval is not None: return np.all(np.greater(self._eigval, 0)) else: try: np.linalg.cholesky(self.matrix) return np.array_equal(self.matrix, self.matrix.conj().T) except np.linalg.LinAlgError: return False
python
def is_valid(self): # Lazy import to improve `import odl` time import scipy.sparse if scipy.sparse.isspmatrix(self.matrix): raise NotImplementedError('validation not supported for sparse ' 'matrices') elif self._eigval is not None: return np.all(np.greater(self._eigval, 0)) else: try: np.linalg.cholesky(self.matrix) return np.array_equal(self.matrix, self.matrix.conj().T) except np.linalg.LinAlgError: return False
[ "def", "is_valid", "(", "self", ")", ":", "# Lazy import to improve `import odl` time", "import", "scipy", ".", "sparse", "if", "scipy", ".", "sparse", ".", "isspmatrix", "(", "self", ".", "matrix", ")", ":", "raise", "NotImplementedError", "(", "'validation not s...
Test if the matrix is positive definite Hermitian. If the matrix decomposition is available, this test checks if all eigenvalues are positive. Otherwise, the test tries to calculate a Cholesky decomposition, which can be very time-consuming for large matrices. Sparse matrices are not supported.
[ "Test", "if", "the", "matrix", "is", "positive", "definite", "Hermitian", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/weighting.py#L263-L285
231,507
odlgroup/odl
odl/space/weighting.py
MatrixWeighting.matrix_decomp
def matrix_decomp(self, cache=None): """Compute a Hermitian eigenbasis decomposition of the matrix. Parameters ---------- cache : bool or None, optional If ``True``, store the decomposition internally. For None, the ``cache_mat_decomp`` from class initialization is used. Returns ------- eigval : `numpy.ndarray` One-dimensional array of eigenvalues. Its length is equal to the number of matrix rows. eigvec : `numpy.ndarray` Two-dimensional array of eigenvectors. It has the same shape as the decomposed matrix. See Also -------- scipy.linalg.decomp.eigh : Implementation of the decomposition. Standard parameters are used here. Raises ------ NotImplementedError if the matrix is sparse (not supported by scipy 0.17) """ # Lazy import to improve `import odl` time import scipy.linalg import scipy.sparse # TODO: fix dead link `scipy.linalg.decomp.eigh` if scipy.sparse.isspmatrix(self.matrix): raise NotImplementedError('sparse matrix not supported') if cache is None: cache = self._cache_mat_decomp if self._eigval is None or self._eigvec is None: eigval, eigvec = scipy.linalg.eigh(self.matrix) if cache: self._eigval = eigval self._eigvec = eigvec else: eigval, eigvec = self._eigval, self._eigvec return eigval, eigvec
python
def matrix_decomp(self, cache=None): # Lazy import to improve `import odl` time import scipy.linalg import scipy.sparse # TODO: fix dead link `scipy.linalg.decomp.eigh` if scipy.sparse.isspmatrix(self.matrix): raise NotImplementedError('sparse matrix not supported') if cache is None: cache = self._cache_mat_decomp if self._eigval is None or self._eigvec is None: eigval, eigvec = scipy.linalg.eigh(self.matrix) if cache: self._eigval = eigval self._eigvec = eigvec else: eigval, eigvec = self._eigval, self._eigvec return eigval, eigvec
[ "def", "matrix_decomp", "(", "self", ",", "cache", "=", "None", ")", ":", "# Lazy import to improve `import odl` time", "import", "scipy", ".", "linalg", "import", "scipy", ".", "sparse", "# TODO: fix dead link `scipy.linalg.decomp.eigh`", "if", "scipy", ".", "sparse", ...
Compute a Hermitian eigenbasis decomposition of the matrix. Parameters ---------- cache : bool or None, optional If ``True``, store the decomposition internally. For None, the ``cache_mat_decomp`` from class initialization is used. Returns ------- eigval : `numpy.ndarray` One-dimensional array of eigenvalues. Its length is equal to the number of matrix rows. eigvec : `numpy.ndarray` Two-dimensional array of eigenvectors. It has the same shape as the decomposed matrix. See Also -------- scipy.linalg.decomp.eigh : Implementation of the decomposition. Standard parameters are used here. Raises ------ NotImplementedError if the matrix is sparse (not supported by scipy 0.17)
[ "Compute", "a", "Hermitian", "eigenbasis", "decomposition", "of", "the", "matrix", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/weighting.py#L287-L335
231,508
odlgroup/odl
odl/space/weighting.py
ArrayWeighting.equiv
def equiv(self, other): """Return True if other is an equivalent weighting. Returns ------- equivalent : bool ``True`` if ``other`` is a `Weighting` instance with the same `Weighting.impl`, which yields the same result as this weighting for any input, ``False`` otherwise. This is checked by entry-wise comparison of arrays/constants. """ # Optimization for equality if self == other: return True elif (not isinstance(other, Weighting) or self.exponent != other.exponent): return False elif isinstance(other, MatrixWeighting): return other.equiv(self) elif isinstance(other, ConstWeighting): return np.array_equiv(self.array, other.const) else: return np.array_equal(self.array, other.array)
python
def equiv(self, other): # Optimization for equality if self == other: return True elif (not isinstance(other, Weighting) or self.exponent != other.exponent): return False elif isinstance(other, MatrixWeighting): return other.equiv(self) elif isinstance(other, ConstWeighting): return np.array_equiv(self.array, other.const) else: return np.array_equal(self.array, other.array)
[ "def", "equiv", "(", "self", ",", "other", ")", ":", "# Optimization for equality", "if", "self", "==", "other", ":", "return", "True", "elif", "(", "not", "isinstance", "(", "other", ",", "Weighting", ")", "or", "self", ".", "exponent", "!=", "other", "...
Return True if other is an equivalent weighting. Returns ------- equivalent : bool ``True`` if ``other`` is a `Weighting` instance with the same `Weighting.impl`, which yields the same result as this weighting for any input, ``False`` otherwise. This is checked by entry-wise comparison of arrays/constants.
[ "Return", "True", "if", "other", "is", "an", "equivalent", "weighting", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/weighting.py#L530-L552
231,509
odlgroup/odl
odl/solvers/nonsmooth/difference_convex.py
dca
def dca(x, f, g, niter, callback=None): r"""Subgradient DCA of Tao and An. This algorithm solves a problem of the form :: min_x f(x) - g(x), where ``f`` and ``g`` are proper, convex and lower semicontinuous functions. Parameters ---------- x : `LinearSpaceElement` Initial point, updated in-place. f : `Functional` Convex functional. Needs to implement ``f.convex_conj.gradient``. g : `Functional` Convex functional. Needs to implement ``g.gradient``. niter : int Number of iterations. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- The algorithm is described in Section 3 and in particular in Theorem 3 of `[TA1997] <http://journals.math.ac.vn/acta/pdf/9701289.pdf>`_. The problem .. math:: \min f(x) - g(x) has the first-order optimality condition :math:`0 \in \partial f(x) - \partial g(x)`, i.e., aims at finding an :math:`x` so that there exists a common element .. math:: y \in \partial f(x) \cap \partial g(x). The element :math:`y` can be seen as a solution of the Toland dual problem .. math:: \min g^*(y) - f^*(y) and the iteration is given by .. math:: y_n \in \partial g(x_n), \qquad x_{n+1} \in \partial f^*(y_n), for :math:`n\geq 0`. Here, a subgradient is found by evaluating the gradient method of the respective functionals. References ---------- [TA1997] Tao, P D, and An, L T H. *Convex analysis approach to d.c. programming: Theory, algorithms and applications*. Acta Mathematica Vietnamica, 22.1 (1997), pp 289--355. See also -------- prox_dca : Solver with a proximal step for ``f`` and a subgradient step for ``g``. doubleprox_dc : Solver with proximal steps for all the nonsmooth convex functionals and a gradient step for a smooth functional. """ space = f.domain if g.domain != space: raise ValueError('`f.domain` and `g.domain` need to be equal, but ' '{} != {}'.format(space, g.domain)) f_convex_conj = f.convex_conj for _ in range(niter): f_convex_conj.gradient(g.gradient(x), out=x) if callback is not None: callback(x)
python
def dca(x, f, g, niter, callback=None): r"""Subgradient DCA of Tao and An. This algorithm solves a problem of the form :: min_x f(x) - g(x), where ``f`` and ``g`` are proper, convex and lower semicontinuous functions. Parameters ---------- x : `LinearSpaceElement` Initial point, updated in-place. f : `Functional` Convex functional. Needs to implement ``f.convex_conj.gradient``. g : `Functional` Convex functional. Needs to implement ``g.gradient``. niter : int Number of iterations. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- The algorithm is described in Section 3 and in particular in Theorem 3 of `[TA1997] <http://journals.math.ac.vn/acta/pdf/9701289.pdf>`_. The problem .. math:: \min f(x) - g(x) has the first-order optimality condition :math:`0 \in \partial f(x) - \partial g(x)`, i.e., aims at finding an :math:`x` so that there exists a common element .. math:: y \in \partial f(x) \cap \partial g(x). The element :math:`y` can be seen as a solution of the Toland dual problem .. math:: \min g^*(y) - f^*(y) and the iteration is given by .. math:: y_n \in \partial g(x_n), \qquad x_{n+1} \in \partial f^*(y_n), for :math:`n\geq 0`. Here, a subgradient is found by evaluating the gradient method of the respective functionals. References ---------- [TA1997] Tao, P D, and An, L T H. *Convex analysis approach to d.c. programming: Theory, algorithms and applications*. Acta Mathematica Vietnamica, 22.1 (1997), pp 289--355. See also -------- prox_dca : Solver with a proximal step for ``f`` and a subgradient step for ``g``. doubleprox_dc : Solver with proximal steps for all the nonsmooth convex functionals and a gradient step for a smooth functional. """ space = f.domain if g.domain != space: raise ValueError('`f.domain` and `g.domain` need to be equal, but ' '{} != {}'.format(space, g.domain)) f_convex_conj = f.convex_conj for _ in range(niter): f_convex_conj.gradient(g.gradient(x), out=x) if callback is not None: callback(x)
[ "def", "dca", "(", "x", ",", "f", ",", "g", ",", "niter", ",", "callback", "=", "None", ")", ":", "space", "=", "f", ".", "domain", "if", "g", ".", "domain", "!=", "space", ":", "raise", "ValueError", "(", "'`f.domain` and `g.domain` need to be equal, bu...
r"""Subgradient DCA of Tao and An. This algorithm solves a problem of the form :: min_x f(x) - g(x), where ``f`` and ``g`` are proper, convex and lower semicontinuous functions. Parameters ---------- x : `LinearSpaceElement` Initial point, updated in-place. f : `Functional` Convex functional. Needs to implement ``f.convex_conj.gradient``. g : `Functional` Convex functional. Needs to implement ``g.gradient``. niter : int Number of iterations. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- The algorithm is described in Section 3 and in particular in Theorem 3 of `[TA1997] <http://journals.math.ac.vn/acta/pdf/9701289.pdf>`_. The problem .. math:: \min f(x) - g(x) has the first-order optimality condition :math:`0 \in \partial f(x) - \partial g(x)`, i.e., aims at finding an :math:`x` so that there exists a common element .. math:: y \in \partial f(x) \cap \partial g(x). The element :math:`y` can be seen as a solution of the Toland dual problem .. math:: \min g^*(y) - f^*(y) and the iteration is given by .. math:: y_n \in \partial g(x_n), \qquad x_{n+1} \in \partial f^*(y_n), for :math:`n\geq 0`. Here, a subgradient is found by evaluating the gradient method of the respective functionals. References ---------- [TA1997] Tao, P D, and An, L T H. *Convex analysis approach to d.c. programming: Theory, algorithms and applications*. Acta Mathematica Vietnamica, 22.1 (1997), pp 289--355. See also -------- prox_dca : Solver with a proximal step for ``f`` and a subgradient step for ``g``. doubleprox_dc : Solver with proximal steps for all the nonsmooth convex functionals and a gradient step for a smooth functional.
[ "r", "Subgradient", "DCA", "of", "Tao", "and", "An", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/nonsmooth/difference_convex.py#L21-L95
231,510
odlgroup/odl
odl/solvers/nonsmooth/difference_convex.py
prox_dca
def prox_dca(x, f, g, niter, gamma, callback=None): r"""Proximal DCA of Sun, Sampaio and Candido. This algorithm solves a problem of the form :: min_x f(x) - g(x) where ``f`` and ``g`` are two proper, convex and lower semicontinuous functions. Parameters ---------- x : `LinearSpaceElement` Initial point, updated in-place. f : `Functional` Convex functional. Needs to implement ``f.proximal``. g : `Functional` Convex functional. Needs to implement ``g.gradient``. niter : int Number of iterations. gamma : positive float Stepsize in the primal updates. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- The algorithm was proposed as Algorithm 2.3 in `[SSC2003] <http://www.global-sci.org/jcm/readabs.php?vol=21&no=4&page=451&year=2003&ppage=462>`_. It solves the problem .. math :: \min f(x) - g(x) by using subgradients of :math:`g` and proximal points of :math:`f`. The iteration is given by .. math :: y_n \in \partial g(x_n), \qquad x_{n+1} = \mathrm{Prox}_{\gamma f}(x_n + \gamma y_n). In contrast to `dca`, `prox_dca` uses proximal steps with respect to the convex part ``f``. Both algorithms use subgradients of the concave part ``g``. References ---------- [SSC2003] Sun, W, Sampaio R J B, and Candido M A B. *Proximal point algorithm for minimization of DC function*. Journal of Computational Mathematics, 21.4 (2003), pp 451--462. See also -------- dca : Solver with subgradinet steps for all the functionals. doubleprox_dc : Solver with proximal steps for all the nonsmooth convex functionals and a gradient step for a smooth functional. """ space = f.domain if g.domain != space: raise ValueError('`f.domain` and `g.domain` need to be equal, but ' '{} != {}'.format(space, g.domain)) for _ in range(niter): f.proximal(gamma)(x.lincomb(1, x, gamma, g.gradient(x)), out=x) if callback is not None: callback(x)
python
def prox_dca(x, f, g, niter, gamma, callback=None): r"""Proximal DCA of Sun, Sampaio and Candido. This algorithm solves a problem of the form :: min_x f(x) - g(x) where ``f`` and ``g`` are two proper, convex and lower semicontinuous functions. Parameters ---------- x : `LinearSpaceElement` Initial point, updated in-place. f : `Functional` Convex functional. Needs to implement ``f.proximal``. g : `Functional` Convex functional. Needs to implement ``g.gradient``. niter : int Number of iterations. gamma : positive float Stepsize in the primal updates. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- The algorithm was proposed as Algorithm 2.3 in `[SSC2003] <http://www.global-sci.org/jcm/readabs.php?vol=21&no=4&page=451&year=2003&ppage=462>`_. It solves the problem .. math :: \min f(x) - g(x) by using subgradients of :math:`g` and proximal points of :math:`f`. The iteration is given by .. math :: y_n \in \partial g(x_n), \qquad x_{n+1} = \mathrm{Prox}_{\gamma f}(x_n + \gamma y_n). In contrast to `dca`, `prox_dca` uses proximal steps with respect to the convex part ``f``. Both algorithms use subgradients of the concave part ``g``. References ---------- [SSC2003] Sun, W, Sampaio R J B, and Candido M A B. *Proximal point algorithm for minimization of DC function*. Journal of Computational Mathematics, 21.4 (2003), pp 451--462. See also -------- dca : Solver with subgradinet steps for all the functionals. doubleprox_dc : Solver with proximal steps for all the nonsmooth convex functionals and a gradient step for a smooth functional. """ space = f.domain if g.domain != space: raise ValueError('`f.domain` and `g.domain` need to be equal, but ' '{} != {}'.format(space, g.domain)) for _ in range(niter): f.proximal(gamma)(x.lincomb(1, x, gamma, g.gradient(x)), out=x) if callback is not None: callback(x)
[ "def", "prox_dca", "(", "x", ",", "f", ",", "g", ",", "niter", ",", "gamma", ",", "callback", "=", "None", ")", ":", "space", "=", "f", ".", "domain", "if", "g", ".", "domain", "!=", "space", ":", "raise", "ValueError", "(", "'`f.domain` and `g.domai...
r"""Proximal DCA of Sun, Sampaio and Candido. This algorithm solves a problem of the form :: min_x f(x) - g(x) where ``f`` and ``g`` are two proper, convex and lower semicontinuous functions. Parameters ---------- x : `LinearSpaceElement` Initial point, updated in-place. f : `Functional` Convex functional. Needs to implement ``f.proximal``. g : `Functional` Convex functional. Needs to implement ``g.gradient``. niter : int Number of iterations. gamma : positive float Stepsize in the primal updates. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- The algorithm was proposed as Algorithm 2.3 in `[SSC2003] <http://www.global-sci.org/jcm/readabs.php?vol=21&no=4&page=451&year=2003&ppage=462>`_. It solves the problem .. math :: \min f(x) - g(x) by using subgradients of :math:`g` and proximal points of :math:`f`. The iteration is given by .. math :: y_n \in \partial g(x_n), \qquad x_{n+1} = \mathrm{Prox}_{\gamma f}(x_n + \gamma y_n). In contrast to `dca`, `prox_dca` uses proximal steps with respect to the convex part ``f``. Both algorithms use subgradients of the concave part ``g``. References ---------- [SSC2003] Sun, W, Sampaio R J B, and Candido M A B. *Proximal point algorithm for minimization of DC function*. Journal of Computational Mathematics, 21.4 (2003), pp 451--462. See also -------- dca : Solver with subgradinet steps for all the functionals. doubleprox_dc : Solver with proximal steps for all the nonsmooth convex functionals and a gradient step for a smooth functional.
[ "r", "Proximal", "DCA", "of", "Sun", "Sampaio", "and", "Candido", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/nonsmooth/difference_convex.py#L98-L166
231,511
odlgroup/odl
odl/solvers/nonsmooth/difference_convex.py
doubleprox_dc
def doubleprox_dc(x, y, f, phi, g, K, niter, gamma, mu, callback=None): r"""Double-proxmial gradient d.c. algorithm of Banert and Bot. This algorithm solves a problem of the form :: min_x f(x) + phi(x) - g(Kx). Parameters ---------- x : `LinearSpaceElement` Initial primal guess, updated in-place. y : `LinearSpaceElement` Initial dual guess, updated in-place. f : `Functional` Convex functional. Needs to implement ``g.proximal``. phi : `Functional` Convex functional. Needs to implement ``phi.gradient``. Convergence can be guaranteed if the gradient is Lipschitz continuous. g : `Functional` Convex functional. Needs to implement ``h.convex_conj.proximal``. K : `Operator` Linear operator. Needs to implement ``K.adjoint`` niter : int Number of iterations. gamma : positive float Stepsize in the primal updates. mu : positive float Stepsize in the dual updates. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- This algorithm is proposed in `[BB2016] <https://arxiv.org/abs/1610.06538>`_ and solves the d.c. problem .. math :: \min_x f(x) + \varphi(x) - g(Kx) together with its Toland dual .. math :: \min_y g^*(y) - (f + \varphi)^*(K^* y). The iterations are given by .. math :: x_{n+1} &= \mathrm{Prox}_{\gamma f} (x_n + \gamma (K^* y_n - \nabla \varphi(x_n))), \\ y_{n+1} &= \mathrm{Prox}_{\mu g^*} (y_n + \mu K x_{n+1}). To guarantee convergence, the parameter :math:`\gamma` must satisfy :math:`0 < \gamma < 2/L` where :math:`L` is the Lipschitz constant of :math:`\nabla \varphi`. References ---------- [BB2016] Banert, S, and Bot, R I. *A general double-proximal gradient algorithm for d.c. programming*. arXiv:1610.06538 [math.OC] (2016). See also -------- dca : Solver with subgradient steps for all the functionals. prox_dca : Solver with a proximal step for ``f`` and a subgradient step for ``g``. """ primal_space = f.domain dual_space = g.domain if phi.domain != primal_space: raise ValueError('`f.domain` and `phi.domain` need to be equal, but ' '{} != {}'.format(primal_space, phi.domain)) if K.domain != primal_space: raise ValueError('`f.domain` and `K.domain` need to be equal, but ' '{} != {}'.format(primal_space, K.domain)) if K.range != dual_space: raise ValueError('`g.domain` and `K.range` need to be equal, but ' '{} != {}'.format(dual_space, K.range)) g_convex_conj = g.convex_conj for _ in range(niter): f.proximal(gamma)(x.lincomb(1, x, gamma, K.adjoint(y) - phi.gradient(x)), out=x) g_convex_conj.proximal(mu)(y.lincomb(1, y, mu, K(x)), out=y) if callback is not None: callback(x)
python
def doubleprox_dc(x, y, f, phi, g, K, niter, gamma, mu, callback=None): r"""Double-proxmial gradient d.c. algorithm of Banert and Bot. This algorithm solves a problem of the form :: min_x f(x) + phi(x) - g(Kx). Parameters ---------- x : `LinearSpaceElement` Initial primal guess, updated in-place. y : `LinearSpaceElement` Initial dual guess, updated in-place. f : `Functional` Convex functional. Needs to implement ``g.proximal``. phi : `Functional` Convex functional. Needs to implement ``phi.gradient``. Convergence can be guaranteed if the gradient is Lipschitz continuous. g : `Functional` Convex functional. Needs to implement ``h.convex_conj.proximal``. K : `Operator` Linear operator. Needs to implement ``K.adjoint`` niter : int Number of iterations. gamma : positive float Stepsize in the primal updates. mu : positive float Stepsize in the dual updates. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- This algorithm is proposed in `[BB2016] <https://arxiv.org/abs/1610.06538>`_ and solves the d.c. problem .. math :: \min_x f(x) + \varphi(x) - g(Kx) together with its Toland dual .. math :: \min_y g^*(y) - (f + \varphi)^*(K^* y). The iterations are given by .. math :: x_{n+1} &= \mathrm{Prox}_{\gamma f} (x_n + \gamma (K^* y_n - \nabla \varphi(x_n))), \\ y_{n+1} &= \mathrm{Prox}_{\mu g^*} (y_n + \mu K x_{n+1}). To guarantee convergence, the parameter :math:`\gamma` must satisfy :math:`0 < \gamma < 2/L` where :math:`L` is the Lipschitz constant of :math:`\nabla \varphi`. References ---------- [BB2016] Banert, S, and Bot, R I. *A general double-proximal gradient algorithm for d.c. programming*. arXiv:1610.06538 [math.OC] (2016). See also -------- dca : Solver with subgradient steps for all the functionals. prox_dca : Solver with a proximal step for ``f`` and a subgradient step for ``g``. """ primal_space = f.domain dual_space = g.domain if phi.domain != primal_space: raise ValueError('`f.domain` and `phi.domain` need to be equal, but ' '{} != {}'.format(primal_space, phi.domain)) if K.domain != primal_space: raise ValueError('`f.domain` and `K.domain` need to be equal, but ' '{} != {}'.format(primal_space, K.domain)) if K.range != dual_space: raise ValueError('`g.domain` and `K.range` need to be equal, but ' '{} != {}'.format(dual_space, K.range)) g_convex_conj = g.convex_conj for _ in range(niter): f.proximal(gamma)(x.lincomb(1, x, gamma, K.adjoint(y) - phi.gradient(x)), out=x) g_convex_conj.proximal(mu)(y.lincomb(1, y, mu, K(x)), out=y) if callback is not None: callback(x)
[ "def", "doubleprox_dc", "(", "x", ",", "y", ",", "f", ",", "phi", ",", "g", ",", "K", ",", "niter", ",", "gamma", ",", "mu", ",", "callback", "=", "None", ")", ":", "primal_space", "=", "f", ".", "domain", "dual_space", "=", "g", ".", "domain", ...
r"""Double-proxmial gradient d.c. algorithm of Banert and Bot. This algorithm solves a problem of the form :: min_x f(x) + phi(x) - g(Kx). Parameters ---------- x : `LinearSpaceElement` Initial primal guess, updated in-place. y : `LinearSpaceElement` Initial dual guess, updated in-place. f : `Functional` Convex functional. Needs to implement ``g.proximal``. phi : `Functional` Convex functional. Needs to implement ``phi.gradient``. Convergence can be guaranteed if the gradient is Lipschitz continuous. g : `Functional` Convex functional. Needs to implement ``h.convex_conj.proximal``. K : `Operator` Linear operator. Needs to implement ``K.adjoint`` niter : int Number of iterations. gamma : positive float Stepsize in the primal updates. mu : positive float Stepsize in the dual updates. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- This algorithm is proposed in `[BB2016] <https://arxiv.org/abs/1610.06538>`_ and solves the d.c. problem .. math :: \min_x f(x) + \varphi(x) - g(Kx) together with its Toland dual .. math :: \min_y g^*(y) - (f + \varphi)^*(K^* y). The iterations are given by .. math :: x_{n+1} &= \mathrm{Prox}_{\gamma f} (x_n + \gamma (K^* y_n - \nabla \varphi(x_n))), \\ y_{n+1} &= \mathrm{Prox}_{\mu g^*} (y_n + \mu K x_{n+1}). To guarantee convergence, the parameter :math:`\gamma` must satisfy :math:`0 < \gamma < 2/L` where :math:`L` is the Lipschitz constant of :math:`\nabla \varphi`. References ---------- [BB2016] Banert, S, and Bot, R I. *A general double-proximal gradient algorithm for d.c. programming*. arXiv:1610.06538 [math.OC] (2016). See also -------- dca : Solver with subgradient steps for all the functionals. prox_dca : Solver with a proximal step for ``f`` and a subgradient step for ``g``.
[ "r", "Double", "-", "proxmial", "gradient", "d", ".", "c", ".", "algorithm", "of", "Banert", "and", "Bot", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/nonsmooth/difference_convex.py#L169-L257
231,512
odlgroup/odl
odl/solvers/nonsmooth/difference_convex.py
doubleprox_dc_simple
def doubleprox_dc_simple(x, y, f, phi, g, K, niter, gamma, mu): """Non-optimized version of ``doubleprox_dc``. This function is intended for debugging. It makes a lot of copies and performs no error checking. """ for _ in range(niter): f.proximal(gamma)(x + gamma * K.adjoint(y) - gamma * phi.gradient(x), out=x) g.convex_conj.proximal(mu)(y + mu * K(x), out=y)
python
def doubleprox_dc_simple(x, y, f, phi, g, K, niter, gamma, mu): for _ in range(niter): f.proximal(gamma)(x + gamma * K.adjoint(y) - gamma * phi.gradient(x), out=x) g.convex_conj.proximal(mu)(y + mu * K(x), out=y)
[ "def", "doubleprox_dc_simple", "(", "x", ",", "y", ",", "f", ",", "phi", ",", "g", ",", "K", ",", "niter", ",", "gamma", ",", "mu", ")", ":", "for", "_", "in", "range", "(", "niter", ")", ":", "f", ".", "proximal", "(", "gamma", ")", "(", "x"...
Non-optimized version of ``doubleprox_dc``. This function is intended for debugging. It makes a lot of copies and performs no error checking.
[ "Non", "-", "optimized", "version", "of", "doubleprox_dc", ".", "This", "function", "is", "intended", "for", "debugging", ".", "It", "makes", "a", "lot", "of", "copies", "and", "performs", "no", "error", "checking", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/nonsmooth/difference_convex.py#L260-L268
231,513
odlgroup/odl
odl/operator/oputils.py
matrix_representation
def matrix_representation(op): """Return a matrix representation of a linear operator. Parameters ---------- op : `Operator` The linear operator of which one wants a matrix representation. If the domain or range is a `ProductSpace`, it must be a power-space. Returns ------- matrix : `numpy.ndarray` The matrix representation of the operator. The shape will be ``op.domain.shape + op.range.shape`` and the dtype is the promoted (greatest) dtype of the domain and range. Examples -------- Approximate a matrix on its own: >>> mat = np.array([[1, 2, 3], ... [4, 5, 6], ... [7, 8, 9]]) >>> op = odl.MatrixOperator(mat) >>> matrix_representation(op) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) It also works with `ProductSpace`'s and higher dimensional `TensorSpace`'s. In this case, the returned "matrix" will also be higher dimensional: >>> space = odl.uniform_discr([0, 0], [2, 2], (2, 2)) >>> grad = odl.Gradient(space) >>> tensor = odl.matrix_representation(grad) >>> tensor.shape == (2, 2, 2, 2, 2) True Since the "matrix" is now higher dimensional, we need to use e.g. `numpy.tensordot` if we want to compute with the matrix representation: >>> x = space.element(lambda x: x[0] ** 2 + 2 * x[1] ** 2) >>> grad(x) ProductSpace(uniform_discr([ 0., 0.], [ 2., 2.], (2, 2)), 2).element([ <BLANKLINE> [[ 2. , 2. ], [-2.75, -6.75]], <BLANKLINE> [[ 4. , -4.75], [ 4. , -6.75]] ]) >>> np.tensordot(tensor, x, axes=grad.domain.ndim) array([[[ 2. , 2. ], [-2.75, -6.75]], <BLANKLINE> [[ 4. , -4.75], [ 4. , -6.75]]]) Notes ---------- The algorithm works by letting the operator act on all unit vectors, and stacking the output as a matrix. """ if not op.is_linear: raise ValueError('the operator is not linear') if not (isinstance(op.domain, TensorSpace) or (isinstance(op.domain, ProductSpace) and op.domain.is_power_space and all(isinstance(spc, TensorSpace) for spc in op.domain))): raise TypeError('operator domain {!r} is neither `TensorSpace` ' 'nor `ProductSpace` with only equal `TensorSpace` ' 'components'.format(op.domain)) if not (isinstance(op.range, TensorSpace) or (isinstance(op.range, ProductSpace) and op.range.is_power_space and all(isinstance(spc, TensorSpace) for spc in op.range))): raise TypeError('operator range {!r} is neither `TensorSpace` ' 'nor `ProductSpace` with only equal `TensorSpace` ' 'components'.format(op.range)) # Generate the matrix dtype = np.promote_types(op.domain.dtype, op.range.dtype) matrix = np.zeros(op.range.shape + op.domain.shape, dtype=dtype) tmp_ran = op.range.element() # Store for reuse in loop tmp_dom = op.domain.zero() # Store for reuse in loop for j in nd_iterator(op.domain.shape): tmp_dom[j] = 1.0 op(tmp_dom, out=tmp_ran) matrix[(Ellipsis,) + j] = tmp_ran.asarray() tmp_dom[j] = 0.0 return matrix
python
def matrix_representation(op): if not op.is_linear: raise ValueError('the operator is not linear') if not (isinstance(op.domain, TensorSpace) or (isinstance(op.domain, ProductSpace) and op.domain.is_power_space and all(isinstance(spc, TensorSpace) for spc in op.domain))): raise TypeError('operator domain {!r} is neither `TensorSpace` ' 'nor `ProductSpace` with only equal `TensorSpace` ' 'components'.format(op.domain)) if not (isinstance(op.range, TensorSpace) or (isinstance(op.range, ProductSpace) and op.range.is_power_space and all(isinstance(spc, TensorSpace) for spc in op.range))): raise TypeError('operator range {!r} is neither `TensorSpace` ' 'nor `ProductSpace` with only equal `TensorSpace` ' 'components'.format(op.range)) # Generate the matrix dtype = np.promote_types(op.domain.dtype, op.range.dtype) matrix = np.zeros(op.range.shape + op.domain.shape, dtype=dtype) tmp_ran = op.range.element() # Store for reuse in loop tmp_dom = op.domain.zero() # Store for reuse in loop for j in nd_iterator(op.domain.shape): tmp_dom[j] = 1.0 op(tmp_dom, out=tmp_ran) matrix[(Ellipsis,) + j] = tmp_ran.asarray() tmp_dom[j] = 0.0 return matrix
[ "def", "matrix_representation", "(", "op", ")", ":", "if", "not", "op", ".", "is_linear", ":", "raise", "ValueError", "(", "'the operator is not linear'", ")", "if", "not", "(", "isinstance", "(", "op", ".", "domain", ",", "TensorSpace", ")", "or", "(", "i...
Return a matrix representation of a linear operator. Parameters ---------- op : `Operator` The linear operator of which one wants a matrix representation. If the domain or range is a `ProductSpace`, it must be a power-space. Returns ------- matrix : `numpy.ndarray` The matrix representation of the operator. The shape will be ``op.domain.shape + op.range.shape`` and the dtype is the promoted (greatest) dtype of the domain and range. Examples -------- Approximate a matrix on its own: >>> mat = np.array([[1, 2, 3], ... [4, 5, 6], ... [7, 8, 9]]) >>> op = odl.MatrixOperator(mat) >>> matrix_representation(op) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) It also works with `ProductSpace`'s and higher dimensional `TensorSpace`'s. In this case, the returned "matrix" will also be higher dimensional: >>> space = odl.uniform_discr([0, 0], [2, 2], (2, 2)) >>> grad = odl.Gradient(space) >>> tensor = odl.matrix_representation(grad) >>> tensor.shape == (2, 2, 2, 2, 2) True Since the "matrix" is now higher dimensional, we need to use e.g. `numpy.tensordot` if we want to compute with the matrix representation: >>> x = space.element(lambda x: x[0] ** 2 + 2 * x[1] ** 2) >>> grad(x) ProductSpace(uniform_discr([ 0., 0.], [ 2., 2.], (2, 2)), 2).element([ <BLANKLINE> [[ 2. , 2. ], [-2.75, -6.75]], <BLANKLINE> [[ 4. , -4.75], [ 4. , -6.75]] ]) >>> np.tensordot(tensor, x, axes=grad.domain.ndim) array([[[ 2. , 2. ], [-2.75, -6.75]], <BLANKLINE> [[ 4. , -4.75], [ 4. , -6.75]]]) Notes ---------- The algorithm works by letting the operator act on all unit vectors, and stacking the output as a matrix.
[ "Return", "a", "matrix", "representation", "of", "a", "linear", "operator", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/oputils.py#L24-L121
231,514
odlgroup/odl
odl/operator/oputils.py
power_method_opnorm
def power_method_opnorm(op, xstart=None, maxiter=100, rtol=1e-05, atol=1e-08, callback=None): r"""Estimate the operator norm with the power method. Parameters ---------- op : `Operator` Operator whose norm is to be estimated. If its `Operator.range` range does not coincide with its `Operator.domain`, an `Operator.adjoint` must be defined (which implies that the operator must be linear). xstart : ``op.domain`` `element-like`, optional Starting point of the iteration. By default an `Operator.domain` element containing noise is used. maxiter : positive int, optional Number of iterations to perform. If the domain and range of ``op`` do not match, it needs to be an even number. If ``None`` is given, iterate until convergence. rtol : float, optional Relative tolerance parameter (see Notes). atol : float, optional Absolute tolerance parameter (see Notes). callback : callable, optional Function called with the current iterate in each iteration. Returns ------- est_opnorm : float The estimated operator norm of ``op``. Examples -------- Verify that the identity operator has norm close to 1: >>> space = odl.uniform_discr(0, 1, 5) >>> id = odl.IdentityOperator(space) >>> estimation = power_method_opnorm(id) >>> round(estimation, ndigits=3) 1.0 Notes ----- The operator norm :math:`||A||` is defined by as the smallest number such that .. math:: ||A(x)|| \leq ||A|| ||x|| for all :math:`x` in the domain of :math:`A`. The operator is evaluated until ``maxiter`` operator calls or until the relative error is small enough. The error measure is given by ``abs(a - b) <= (atol + rtol * abs(b))``, where ``a`` and ``b`` are consecutive iterates. """ if maxiter is None: maxiter = np.iinfo(int).max maxiter, maxiter_in = int(maxiter), maxiter if maxiter <= 0: raise ValueError('`maxiter` must be positive, got {}' ''.format(maxiter_in)) if op.domain == op.range: use_normal = False ncalls = maxiter else: # Do the power iteration for A*A; the norm of A*A(x_N) is then # an estimate of the square of the operator norm # We do only half the number of iterations compared to the usual # case to have the same number of operator evaluations. use_normal = True ncalls = maxiter // 2 if ncalls * 2 != maxiter: raise ValueError('``maxiter`` must be an even number for ' 'non-self-adjoint operator, got {}' ''.format(maxiter_in)) # Make sure starting point is ok or select initial guess if xstart is None: x = noise_element(op.domain) else: # copy to ensure xstart is not modified x = op.domain.element(xstart).copy() # Take first iteration step to normalize input x_norm = x.norm() if x_norm == 0: raise ValueError('``xstart`` must be nonzero') x /= x_norm # utility to calculate opnorm from xnorm def calc_opnorm(x_norm): if use_normal: return np.sqrt(x_norm) else: return x_norm # initial guess of opnorm opnorm = calc_opnorm(x_norm) # temporary to improve performance tmp = op.range.element() # Use the power method to estimate opnorm for i in range(ncalls): if use_normal: op(x, out=tmp) op.adjoint(tmp, out=x) else: op(x, out=tmp) x, tmp = tmp, x # Calculate x norm and verify it is valid x_norm = x.norm() if x_norm == 0: raise ValueError('reached ``x=0`` after {} iterations'.format(i)) if not np.isfinite(x_norm): raise ValueError('reached nonfinite ``x={}`` after {} iterations' ''.format(x, i)) # Calculate opnorm opnorm, opnorm_old = calc_opnorm(x_norm), opnorm # If the breaking condition holds, stop. Else rescale and go on. if np.isclose(opnorm, opnorm_old, rtol, atol): break else: x /= x_norm if callback is not None: callback(x) return opnorm
python
def power_method_opnorm(op, xstart=None, maxiter=100, rtol=1e-05, atol=1e-08, callback=None): r"""Estimate the operator norm with the power method. Parameters ---------- op : `Operator` Operator whose norm is to be estimated. If its `Operator.range` range does not coincide with its `Operator.domain`, an `Operator.adjoint` must be defined (which implies that the operator must be linear). xstart : ``op.domain`` `element-like`, optional Starting point of the iteration. By default an `Operator.domain` element containing noise is used. maxiter : positive int, optional Number of iterations to perform. If the domain and range of ``op`` do not match, it needs to be an even number. If ``None`` is given, iterate until convergence. rtol : float, optional Relative tolerance parameter (see Notes). atol : float, optional Absolute tolerance parameter (see Notes). callback : callable, optional Function called with the current iterate in each iteration. Returns ------- est_opnorm : float The estimated operator norm of ``op``. Examples -------- Verify that the identity operator has norm close to 1: >>> space = odl.uniform_discr(0, 1, 5) >>> id = odl.IdentityOperator(space) >>> estimation = power_method_opnorm(id) >>> round(estimation, ndigits=3) 1.0 Notes ----- The operator norm :math:`||A||` is defined by as the smallest number such that .. math:: ||A(x)|| \leq ||A|| ||x|| for all :math:`x` in the domain of :math:`A`. The operator is evaluated until ``maxiter`` operator calls or until the relative error is small enough. The error measure is given by ``abs(a - b) <= (atol + rtol * abs(b))``, where ``a`` and ``b`` are consecutive iterates. """ if maxiter is None: maxiter = np.iinfo(int).max maxiter, maxiter_in = int(maxiter), maxiter if maxiter <= 0: raise ValueError('`maxiter` must be positive, got {}' ''.format(maxiter_in)) if op.domain == op.range: use_normal = False ncalls = maxiter else: # Do the power iteration for A*A; the norm of A*A(x_N) is then # an estimate of the square of the operator norm # We do only half the number of iterations compared to the usual # case to have the same number of operator evaluations. use_normal = True ncalls = maxiter // 2 if ncalls * 2 != maxiter: raise ValueError('``maxiter`` must be an even number for ' 'non-self-adjoint operator, got {}' ''.format(maxiter_in)) # Make sure starting point is ok or select initial guess if xstart is None: x = noise_element(op.domain) else: # copy to ensure xstart is not modified x = op.domain.element(xstart).copy() # Take first iteration step to normalize input x_norm = x.norm() if x_norm == 0: raise ValueError('``xstart`` must be nonzero') x /= x_norm # utility to calculate opnorm from xnorm def calc_opnorm(x_norm): if use_normal: return np.sqrt(x_norm) else: return x_norm # initial guess of opnorm opnorm = calc_opnorm(x_norm) # temporary to improve performance tmp = op.range.element() # Use the power method to estimate opnorm for i in range(ncalls): if use_normal: op(x, out=tmp) op.adjoint(tmp, out=x) else: op(x, out=tmp) x, tmp = tmp, x # Calculate x norm and verify it is valid x_norm = x.norm() if x_norm == 0: raise ValueError('reached ``x=0`` after {} iterations'.format(i)) if not np.isfinite(x_norm): raise ValueError('reached nonfinite ``x={}`` after {} iterations' ''.format(x, i)) # Calculate opnorm opnorm, opnorm_old = calc_opnorm(x_norm), opnorm # If the breaking condition holds, stop. Else rescale and go on. if np.isclose(opnorm, opnorm_old, rtol, atol): break else: x /= x_norm if callback is not None: callback(x) return opnorm
[ "def", "power_method_opnorm", "(", "op", ",", "xstart", "=", "None", ",", "maxiter", "=", "100", ",", "rtol", "=", "1e-05", ",", "atol", "=", "1e-08", ",", "callback", "=", "None", ")", ":", "if", "maxiter", "is", "None", ":", "maxiter", "=", "np", ...
r"""Estimate the operator norm with the power method. Parameters ---------- op : `Operator` Operator whose norm is to be estimated. If its `Operator.range` range does not coincide with its `Operator.domain`, an `Operator.adjoint` must be defined (which implies that the operator must be linear). xstart : ``op.domain`` `element-like`, optional Starting point of the iteration. By default an `Operator.domain` element containing noise is used. maxiter : positive int, optional Number of iterations to perform. If the domain and range of ``op`` do not match, it needs to be an even number. If ``None`` is given, iterate until convergence. rtol : float, optional Relative tolerance parameter (see Notes). atol : float, optional Absolute tolerance parameter (see Notes). callback : callable, optional Function called with the current iterate in each iteration. Returns ------- est_opnorm : float The estimated operator norm of ``op``. Examples -------- Verify that the identity operator has norm close to 1: >>> space = odl.uniform_discr(0, 1, 5) >>> id = odl.IdentityOperator(space) >>> estimation = power_method_opnorm(id) >>> round(estimation, ndigits=3) 1.0 Notes ----- The operator norm :math:`||A||` is defined by as the smallest number such that .. math:: ||A(x)|| \leq ||A|| ||x|| for all :math:`x` in the domain of :math:`A`. The operator is evaluated until ``maxiter`` operator calls or until the relative error is small enough. The error measure is given by ``abs(a - b) <= (atol + rtol * abs(b))``, where ``a`` and ``b`` are consecutive iterates.
[ "r", "Estimate", "the", "operator", "norm", "with", "the", "power", "method", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/oputils.py#L124-L259
231,515
odlgroup/odl
odl/operator/oputils.py
as_scipy_operator
def as_scipy_operator(op): """Wrap ``op`` as a ``scipy.sparse.linalg.LinearOperator``. This is intended to be used with the scipy sparse linear solvers. Parameters ---------- op : `Operator` A linear operator that should be wrapped Returns ------- ``scipy.sparse.linalg.LinearOperator`` : linear_op The wrapped operator, has attributes ``matvec`` which calls ``op``, and ``rmatvec`` which calls ``op.adjoint``. Examples -------- Wrap operator and solve simple problem (here toy problem ``Ix = b``) >>> op = odl.IdentityOperator(odl.rn(3)) >>> scipy_op = as_scipy_operator(op) >>> import scipy.sparse.linalg as scipy_solvers >>> result, status = scipy_solvers.cg(scipy_op, [0, 1, 0]) >>> result array([ 0., 1., 0.]) Notes ----- If the data representation of ``op``'s domain and range is of type `NumpyTensorSpace` this incurs no significant overhead. If the space type is ``CudaFn`` or some other nonlocal type, the overhead is significant. """ # Lazy import to improve `import odl` time import scipy.sparse if not op.is_linear: raise ValueError('`op` needs to be linear') dtype = op.domain.dtype if op.range.dtype != dtype: raise ValueError('dtypes of ``op.domain`` and ``op.range`` needs to ' 'match') shape = (native(op.range.size), native(op.domain.size)) def matvec(v): return (op(v.reshape(op.domain.shape))).asarray().ravel() def rmatvec(v): return (op.adjoint(v.reshape(op.range.shape))).asarray().ravel() return scipy.sparse.linalg.LinearOperator(shape=shape, matvec=matvec, rmatvec=rmatvec, dtype=dtype)
python
def as_scipy_operator(op): # Lazy import to improve `import odl` time import scipy.sparse if not op.is_linear: raise ValueError('`op` needs to be linear') dtype = op.domain.dtype if op.range.dtype != dtype: raise ValueError('dtypes of ``op.domain`` and ``op.range`` needs to ' 'match') shape = (native(op.range.size), native(op.domain.size)) def matvec(v): return (op(v.reshape(op.domain.shape))).asarray().ravel() def rmatvec(v): return (op.adjoint(v.reshape(op.range.shape))).asarray().ravel() return scipy.sparse.linalg.LinearOperator(shape=shape, matvec=matvec, rmatvec=rmatvec, dtype=dtype)
[ "def", "as_scipy_operator", "(", "op", ")", ":", "# Lazy import to improve `import odl` time", "import", "scipy", ".", "sparse", "if", "not", "op", ".", "is_linear", ":", "raise", "ValueError", "(", "'`op` needs to be linear'", ")", "dtype", "=", "op", ".", "domai...
Wrap ``op`` as a ``scipy.sparse.linalg.LinearOperator``. This is intended to be used with the scipy sparse linear solvers. Parameters ---------- op : `Operator` A linear operator that should be wrapped Returns ------- ``scipy.sparse.linalg.LinearOperator`` : linear_op The wrapped operator, has attributes ``matvec`` which calls ``op``, and ``rmatvec`` which calls ``op.adjoint``. Examples -------- Wrap operator and solve simple problem (here toy problem ``Ix = b``) >>> op = odl.IdentityOperator(odl.rn(3)) >>> scipy_op = as_scipy_operator(op) >>> import scipy.sparse.linalg as scipy_solvers >>> result, status = scipy_solvers.cg(scipy_op, [0, 1, 0]) >>> result array([ 0., 1., 0.]) Notes ----- If the data representation of ``op``'s domain and range is of type `NumpyTensorSpace` this incurs no significant overhead. If the space type is ``CudaFn`` or some other nonlocal type, the overhead is significant.
[ "Wrap", "op", "as", "a", "scipy", ".", "sparse", ".", "linalg", ".", "LinearOperator", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/oputils.py#L262-L318
231,516
odlgroup/odl
odl/operator/oputils.py
as_scipy_functional
def as_scipy_functional(func, return_gradient=False): """Wrap ``op`` as a function operating on linear arrays. This is intended to be used with the `scipy solvers <https://docs.scipy.org/doc/scipy/reference/optimize.html>`_. Parameters ---------- func : `Functional`. A functional that should be wrapped return_gradient : bool, optional ``True`` if the gradient of the functional should also be returned, ``False`` otherwise. Returns ------- function : ``callable`` The wrapped functional. gradient : ``callable``, optional The wrapped gradient. Only returned if ``return_gradient`` is true. Examples -------- Wrap functional and solve simple problem (here toy problem ``min_x ||x||^2``): >>> func = odl.solvers.L2NormSquared(odl.rn(3)) >>> scipy_func = odl.as_scipy_functional(func) >>> from scipy.optimize import minimize >>> result = minimize(scipy_func, x0=[0, 1, 0]) >>> np.allclose(result.x, [0, 0, 0]) True The gradient (jacobian) can also be provided: >>> func = odl.solvers.L2NormSquared(odl.rn(3)) >>> scipy_func, scipy_grad = odl.as_scipy_functional(func, True) >>> from scipy.optimize import minimize >>> result = minimize(scipy_func, x0=[0, 1, 0], jac=scipy_grad) >>> np.allclose(result.x, [0, 0, 0]) True Notes ----- If the data representation of ``op``'s domain is of type `NumpyTensorSpace`, this incurs no significant overhead. If the space type is ``CudaFn`` or some other nonlocal type, the overhead is significant. """ def func_call(arr): return func(np.asarray(arr).reshape(func.domain.shape)) if return_gradient: def func_gradient_call(arr): return np.asarray( func.gradient(np.asarray(arr).reshape(func.domain.shape))) return func_call, func_gradient_call else: return func_call
python
def as_scipy_functional(func, return_gradient=False): def func_call(arr): return func(np.asarray(arr).reshape(func.domain.shape)) if return_gradient: def func_gradient_call(arr): return np.asarray( func.gradient(np.asarray(arr).reshape(func.domain.shape))) return func_call, func_gradient_call else: return func_call
[ "def", "as_scipy_functional", "(", "func", ",", "return_gradient", "=", "False", ")", ":", "def", "func_call", "(", "arr", ")", ":", "return", "func", "(", "np", ".", "asarray", "(", "arr", ")", ".", "reshape", "(", "func", ".", "domain", ".", "shape",...
Wrap ``op`` as a function operating on linear arrays. This is intended to be used with the `scipy solvers <https://docs.scipy.org/doc/scipy/reference/optimize.html>`_. Parameters ---------- func : `Functional`. A functional that should be wrapped return_gradient : bool, optional ``True`` if the gradient of the functional should also be returned, ``False`` otherwise. Returns ------- function : ``callable`` The wrapped functional. gradient : ``callable``, optional The wrapped gradient. Only returned if ``return_gradient`` is true. Examples -------- Wrap functional and solve simple problem (here toy problem ``min_x ||x||^2``): >>> func = odl.solvers.L2NormSquared(odl.rn(3)) >>> scipy_func = odl.as_scipy_functional(func) >>> from scipy.optimize import minimize >>> result = minimize(scipy_func, x0=[0, 1, 0]) >>> np.allclose(result.x, [0, 0, 0]) True The gradient (jacobian) can also be provided: >>> func = odl.solvers.L2NormSquared(odl.rn(3)) >>> scipy_func, scipy_grad = odl.as_scipy_functional(func, True) >>> from scipy.optimize import minimize >>> result = minimize(scipy_func, x0=[0, 1, 0], jac=scipy_grad) >>> np.allclose(result.x, [0, 0, 0]) True Notes ----- If the data representation of ``op``'s domain is of type `NumpyTensorSpace`, this incurs no significant overhead. If the space type is ``CudaFn`` or some other nonlocal type, the overhead is significant.
[ "Wrap", "op", "as", "a", "function", "operating", "on", "linear", "arrays", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/oputils.py#L321-L379
231,517
odlgroup/odl
odl/operator/oputils.py
as_proximal_lang_operator
def as_proximal_lang_operator(op, norm_bound=None): """Wrap ``op`` as a ``proximal.BlackBox``. This is intended to be used with the `ProxImaL language solvers. <https://github.com/comp-imaging/proximal>`_ For documentation on the proximal language (ProxImaL) see [Hei+2016]. Parameters ---------- op : `Operator` Linear operator to be wrapped. Its domain and range must implement ``shape``, and elements in these need to implement ``asarray``. norm_bound : float, optional An upper bound on the spectral norm of the operator. Note that this is the norm as defined by ProxImaL, and hence use the unweighted spaces. Returns ------- ``proximal.BlackBox`` : proximal_lang_operator The wrapped operator. Notes ----- If the data representation of ``op``'s domain and range is of type `NumpyTensorSpace` this incurs no significant overhead. If the data space is implemented with CUDA or some other non-local representation, the overhead is significant. References ---------- [Hei+2016] Heide, F et al. *ProxImaL: Efficient Image Optimization using Proximal Algorithms*. ACM Transactions on Graphics (TOG), 2016. """ # TODO: use out parameter once "as editable array" is added def forward(inp, out): out[:] = op(inp).asarray() def adjoint(inp, out): out[:] = op.adjoint(inp).asarray() import proximal return proximal.LinOpFactory(input_shape=op.domain.shape, output_shape=op.range.shape, forward=forward, adjoint=adjoint, norm_bound=norm_bound)
python
def as_proximal_lang_operator(op, norm_bound=None): # TODO: use out parameter once "as editable array" is added def forward(inp, out): out[:] = op(inp).asarray() def adjoint(inp, out): out[:] = op.adjoint(inp).asarray() import proximal return proximal.LinOpFactory(input_shape=op.domain.shape, output_shape=op.range.shape, forward=forward, adjoint=adjoint, norm_bound=norm_bound)
[ "def", "as_proximal_lang_operator", "(", "op", ",", "norm_bound", "=", "None", ")", ":", "# TODO: use out parameter once \"as editable array\" is added", "def", "forward", "(", "inp", ",", "out", ")", ":", "out", "[", ":", "]", "=", "op", "(", "inp", ")", ".",...
Wrap ``op`` as a ``proximal.BlackBox``. This is intended to be used with the `ProxImaL language solvers. <https://github.com/comp-imaging/proximal>`_ For documentation on the proximal language (ProxImaL) see [Hei+2016]. Parameters ---------- op : `Operator` Linear operator to be wrapped. Its domain and range must implement ``shape``, and elements in these need to implement ``asarray``. norm_bound : float, optional An upper bound on the spectral norm of the operator. Note that this is the norm as defined by ProxImaL, and hence use the unweighted spaces. Returns ------- ``proximal.BlackBox`` : proximal_lang_operator The wrapped operator. Notes ----- If the data representation of ``op``'s domain and range is of type `NumpyTensorSpace` this incurs no significant overhead. If the data space is implemented with CUDA or some other non-local representation, the overhead is significant. References ---------- [Hei+2016] Heide, F et al. *ProxImaL: Efficient Image Optimization using Proximal Algorithms*. ACM Transactions on Graphics (TOG), 2016.
[ "Wrap", "op", "as", "a", "proximal", ".", "BlackBox", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/oputils.py#L382-L429
231,518
odlgroup/odl
odl/tomo/backends/skimage_radon.py
skimage_sinogram_space
def skimage_sinogram_space(geometry, volume_space, sinogram_space): """Create a range adapted to the skimage radon geometry.""" padded_size = int(np.ceil(volume_space.shape[0] * np.sqrt(2))) det_width = volume_space.domain.extent[0] * np.sqrt(2) skimage_detector_part = uniform_partition(-det_width / 2.0, det_width / 2.0, padded_size) skimage_range_part = geometry.motion_partition.insert( 1, skimage_detector_part) skimage_range = uniform_discr_frompartition(skimage_range_part, interp=sinogram_space.interp, dtype=sinogram_space.dtype) return skimage_range
python
def skimage_sinogram_space(geometry, volume_space, sinogram_space): padded_size = int(np.ceil(volume_space.shape[0] * np.sqrt(2))) det_width = volume_space.domain.extent[0] * np.sqrt(2) skimage_detector_part = uniform_partition(-det_width / 2.0, det_width / 2.0, padded_size) skimage_range_part = geometry.motion_partition.insert( 1, skimage_detector_part) skimage_range = uniform_discr_frompartition(skimage_range_part, interp=sinogram_space.interp, dtype=sinogram_space.dtype) return skimage_range
[ "def", "skimage_sinogram_space", "(", "geometry", ",", "volume_space", ",", "sinogram_space", ")", ":", "padded_size", "=", "int", "(", "np", ".", "ceil", "(", "volume_space", ".", "shape", "[", "0", "]", "*", "np", ".", "sqrt", "(", "2", ")", ")", ")"...
Create a range adapted to the skimage radon geometry.
[ "Create", "a", "range", "adapted", "to", "the", "skimage", "radon", "geometry", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/backends/skimage_radon.py#L30-L45
231,519
odlgroup/odl
odl/tomo/backends/skimage_radon.py
clamped_interpolation
def clamped_interpolation(skimage_range, sinogram): """Interpolate in a possibly smaller space. Sets all points that would be outside the domain to match the boundary values. """ min_x = skimage_range.domain.min()[1] max_x = skimage_range.domain.max()[1] def interpolation_wrapper(x): x = (x[0], np.maximum(min_x, np.minimum(max_x, x[1]))) return sinogram.interpolation(x) return interpolation_wrapper
python
def clamped_interpolation(skimage_range, sinogram): min_x = skimage_range.domain.min()[1] max_x = skimage_range.domain.max()[1] def interpolation_wrapper(x): x = (x[0], np.maximum(min_x, np.minimum(max_x, x[1]))) return sinogram.interpolation(x) return interpolation_wrapper
[ "def", "clamped_interpolation", "(", "skimage_range", ",", "sinogram", ")", ":", "min_x", "=", "skimage_range", ".", "domain", ".", "min", "(", ")", "[", "1", "]", "max_x", "=", "skimage_range", ".", "domain", ".", "max", "(", ")", "[", "1", "]", "def"...
Interpolate in a possibly smaller space. Sets all points that would be outside the domain to match the boundary values.
[ "Interpolate", "in", "a", "possibly", "smaller", "space", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/backends/skimage_radon.py#L48-L61
231,520
odlgroup/odl
odl/operator/default_ops.py
ScalingOperator._call
def _call(self, x, out=None): """Scale ``x`` and write to ``out`` if given.""" if out is None: out = self.scalar * x else: out.lincomb(self.scalar, x) return out
python
def _call(self, x, out=None): if out is None: out = self.scalar * x else: out.lincomb(self.scalar, x) return out
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "self", ".", "scalar", "*", "x", "else", ":", "out", ".", "lincomb", "(", "self", ".", "scalar", ",", "x", ")", "return", "o...
Scale ``x`` and write to ``out`` if given.
[ "Scale", "x", "and", "write", "to", "out", "if", "given", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L74-L80
231,521
odlgroup/odl
odl/operator/default_ops.py
ScalingOperator.inverse
def inverse(self): """Return the inverse operator. Examples -------- >>> r3 = odl.rn(3) >>> vec = r3.element([1, 2, 3]) >>> op = ScalingOperator(r3, 2.0) >>> inv = op.inverse >>> inv(op(vec)) == vec True >>> op(inv(vec)) == vec True """ if self.scalar == 0.0: raise ZeroDivisionError('scaling operator not invertible for ' 'scalar==0') return ScalingOperator(self.domain, 1.0 / self.scalar)
python
def inverse(self): if self.scalar == 0.0: raise ZeroDivisionError('scaling operator not invertible for ' 'scalar==0') return ScalingOperator(self.domain, 1.0 / self.scalar)
[ "def", "inverse", "(", "self", ")", ":", "if", "self", ".", "scalar", "==", "0.0", ":", "raise", "ZeroDivisionError", "(", "'scaling operator not invertible for '", "'scalar==0'", ")", "return", "ScalingOperator", "(", "self", ".", "domain", ",", "1.0", "/", "...
Return the inverse operator. Examples -------- >>> r3 = odl.rn(3) >>> vec = r3.element([1, 2, 3]) >>> op = ScalingOperator(r3, 2.0) >>> inv = op.inverse >>> inv(op(vec)) == vec True >>> op(inv(vec)) == vec True
[ "Return", "the", "inverse", "operator", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L83-L100
231,522
odlgroup/odl
odl/operator/default_ops.py
ScalingOperator.adjoint
def adjoint(self): """Adjoint, given as scaling with the conjugate of the scalar. Examples -------- In the real case, the adjoint is the same as the operator: >>> r3 = odl.rn(3) >>> x = r3.element([1, 2, 3]) >>> op = ScalingOperator(r3, 2) >>> op(x) rn(3).element([ 2., 4., 6.]) >>> op.adjoint(x) # The same rn(3).element([ 2., 4., 6.]) In the complex case, the scalar is conjugated: >>> c3 = odl.cn(3) >>> x_complex = c3.element([1, 1j, 1-1j]) >>> op = ScalingOperator(c3, 1+1j) >>> expected_op = ScalingOperator(c3, 1-1j) >>> op.adjoint(x_complex) cn(3).element([ 1.-1.j, 1.+1.j, 0.-2.j]) >>> expected_op(x_complex) # The same cn(3).element([ 1.-1.j, 1.+1.j, 0.-2.j]) Returns ------- adjoint : `ScalingOperator` ``self`` if `scalar` is real, else `scalar` is conjugated. """ if complex(self.scalar).imag == 0.0: return self else: return ScalingOperator(self.domain, self.scalar.conjugate())
python
def adjoint(self): if complex(self.scalar).imag == 0.0: return self else: return ScalingOperator(self.domain, self.scalar.conjugate())
[ "def", "adjoint", "(", "self", ")", ":", "if", "complex", "(", "self", ".", "scalar", ")", ".", "imag", "==", "0.0", ":", "return", "self", "else", ":", "return", "ScalingOperator", "(", "self", ".", "domain", ",", "self", ".", "scalar", ".", "conjug...
Adjoint, given as scaling with the conjugate of the scalar. Examples -------- In the real case, the adjoint is the same as the operator: >>> r3 = odl.rn(3) >>> x = r3.element([1, 2, 3]) >>> op = ScalingOperator(r3, 2) >>> op(x) rn(3).element([ 2., 4., 6.]) >>> op.adjoint(x) # The same rn(3).element([ 2., 4., 6.]) In the complex case, the scalar is conjugated: >>> c3 = odl.cn(3) >>> x_complex = c3.element([1, 1j, 1-1j]) >>> op = ScalingOperator(c3, 1+1j) >>> expected_op = ScalingOperator(c3, 1-1j) >>> op.adjoint(x_complex) cn(3).element([ 1.-1.j, 1.+1.j, 0.-2.j]) >>> expected_op(x_complex) # The same cn(3).element([ 1.-1.j, 1.+1.j, 0.-2.j]) Returns ------- adjoint : `ScalingOperator` ``self`` if `scalar` is real, else `scalar` is conjugated.
[ "Adjoint", "given", "as", "scaling", "with", "the", "conjugate", "of", "the", "scalar", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L103-L137
231,523
odlgroup/odl
odl/operator/default_ops.py
LinCombOperator._call
def _call(self, x, out=None): """Linearly combine ``x`` and write to ``out`` if given.""" if out is None: out = self.range.element() out.lincomb(self.a, x[0], self.b, x[1]) return out
python
def _call(self, x, out=None): if out is None: out = self.range.element() out.lincomb(self.a, x[0], self.b, x[1]) return out
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "self", ".", "range", ".", "element", "(", ")", "out", ".", "lincomb", "(", "self", ".", "a", ",", "x", "[", "0", "]", ","...
Linearly combine ``x`` and write to ``out`` if given.
[ "Linearly", "combine", "x", "and", "write", "to", "out", "if", "given", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L235-L240
231,524
odlgroup/odl
odl/operator/default_ops.py
MultiplyOperator._call
def _call(self, x, out=None): """Multiply ``x`` and write to ``out`` if given.""" if out is None: return x * self.multiplicand elif not self.__range_is_field: if self.__domain_is_field: out.lincomb(x, self.multiplicand) else: out.assign(self.multiplicand * x) else: raise ValueError('can only use `out` with `LinearSpace` range')
python
def _call(self, x, out=None): if out is None: return x * self.multiplicand elif not self.__range_is_field: if self.__domain_is_field: out.lincomb(x, self.multiplicand) else: out.assign(self.multiplicand * x) else: raise ValueError('can only use `out` with `LinearSpace` range')
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "return", "x", "*", "self", ".", "multiplicand", "elif", "not", "self", ".", "__range_is_field", ":", "if", "self", ".", "__domain_is_field", ":...
Multiply ``x`` and write to ``out`` if given.
[ "Multiply", "x", "and", "write", "to", "out", "if", "given", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L320-L330
231,525
odlgroup/odl
odl/operator/default_ops.py
PowerOperator._call
def _call(self, x, out=None): """Take the power of ``x`` and write to ``out`` if given.""" if out is None: return x ** self.exponent elif self.__domain_is_field: raise ValueError('cannot use `out` with field') else: out.assign(x) out **= self.exponent
python
def _call(self, x, out=None): if out is None: return x ** self.exponent elif self.__domain_is_field: raise ValueError('cannot use `out` with field') else: out.assign(x) out **= self.exponent
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "return", "x", "**", "self", ".", "exponent", "elif", "self", ".", "__domain_is_field", ":", "raise", "ValueError", "(", "'cannot use `out` with fie...
Take the power of ``x`` and write to ``out`` if given.
[ "Take", "the", "power", "of", "x", "and", "write", "to", "out", "if", "given", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L447-L455
231,526
odlgroup/odl
odl/operator/default_ops.py
NormOperator.derivative
def derivative(self, point): r"""Derivative of this operator in ``point``. ``NormOperator().derivative(y)(x) == (y / y.norm()).inner(x)`` This is only applicable in inner product spaces. Parameters ---------- point : `domain` `element-like` Point in which to take the derivative. Returns ------- derivative : `InnerProductOperator` Raises ------ ValueError If ``point.norm() == 0``, in which case the derivative is not well defined in the Frechet sense. Notes ----- The derivative cannot be written in a general sense except in Hilbert spaces, in which case it is given by .. math:: (D \|\cdot\|)(y)(x) = \langle y / \|y\|, x \rangle Examples -------- >>> r3 = odl.rn(3) >>> op = NormOperator(r3) >>> derivative = op.derivative([1, 0, 0]) >>> derivative([1, 0, 0]) 1.0 """ point = self.domain.element(point) norm = point.norm() if norm == 0: raise ValueError('not differentiable in 0') return InnerProductOperator(point / norm)
python
def derivative(self, point): r"""Derivative of this operator in ``point``. ``NormOperator().derivative(y)(x) == (y / y.norm()).inner(x)`` This is only applicable in inner product spaces. Parameters ---------- point : `domain` `element-like` Point in which to take the derivative. Returns ------- derivative : `InnerProductOperator` Raises ------ ValueError If ``point.norm() == 0``, in which case the derivative is not well defined in the Frechet sense. Notes ----- The derivative cannot be written in a general sense except in Hilbert spaces, in which case it is given by .. math:: (D \|\cdot\|)(y)(x) = \langle y / \|y\|, x \rangle Examples -------- >>> r3 = odl.rn(3) >>> op = NormOperator(r3) >>> derivative = op.derivative([1, 0, 0]) >>> derivative([1, 0, 0]) 1.0 """ point = self.domain.element(point) norm = point.norm() if norm == 0: raise ValueError('not differentiable in 0') return InnerProductOperator(point / norm)
[ "def", "derivative", "(", "self", ",", "point", ")", ":", "point", "=", "self", ".", "domain", ".", "element", "(", "point", ")", "norm", "=", "point", ".", "norm", "(", ")", "if", "norm", "==", "0", ":", "raise", "ValueError", "(", "'not differentia...
r"""Derivative of this operator in ``point``. ``NormOperator().derivative(y)(x) == (y / y.norm()).inner(x)`` This is only applicable in inner product spaces. Parameters ---------- point : `domain` `element-like` Point in which to take the derivative. Returns ------- derivative : `InnerProductOperator` Raises ------ ValueError If ``point.norm() == 0``, in which case the derivative is not well defined in the Frechet sense. Notes ----- The derivative cannot be written in a general sense except in Hilbert spaces, in which case it is given by .. math:: (D \|\cdot\|)(y)(x) = \langle y / \|y\|, x \rangle Examples -------- >>> r3 = odl.rn(3) >>> op = NormOperator(r3) >>> derivative = op.derivative([1, 0, 0]) >>> derivative([1, 0, 0]) 1.0
[ "r", "Derivative", "of", "this", "operator", "in", "point", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L632-L675
231,527
odlgroup/odl
odl/operator/default_ops.py
DistOperator.derivative
def derivative(self, point): r"""The derivative operator. ``DistOperator(y).derivative(z)(x) == ((y - z) / y.dist(z)).inner(x)`` This is only applicable in inner product spaces. Parameters ---------- x : `domain` `element-like` Point in which to take the derivative. Returns ------- derivative : `InnerProductOperator` Raises ------ ValueError If ``point == self.vector``, in which case the derivative is not well defined in the Frechet sense. Notes ----- The derivative cannot be written in a general sense except in Hilbert spaces, in which case it is given by .. math:: (D d(\cdot, y))(z)(x) = \langle (y-z) / d(y, z), x \rangle Examples -------- >>> r2 = odl.rn(2) >>> x = r2.element([1, 1]) >>> op = DistOperator(x) >>> derivative = op.derivative([2, 1]) >>> derivative([1, 0]) 1.0 """ point = self.domain.element(point) diff = point - self.vector dist = self.vector.dist(point) if dist == 0: raise ValueError('not differentiable at the reference vector {!r}' ''.format(self.vector)) return InnerProductOperator(diff / dist)
python
def derivative(self, point): r"""The derivative operator. ``DistOperator(y).derivative(z)(x) == ((y - z) / y.dist(z)).inner(x)`` This is only applicable in inner product spaces. Parameters ---------- x : `domain` `element-like` Point in which to take the derivative. Returns ------- derivative : `InnerProductOperator` Raises ------ ValueError If ``point == self.vector``, in which case the derivative is not well defined in the Frechet sense. Notes ----- The derivative cannot be written in a general sense except in Hilbert spaces, in which case it is given by .. math:: (D d(\cdot, y))(z)(x) = \langle (y-z) / d(y, z), x \rangle Examples -------- >>> r2 = odl.rn(2) >>> x = r2.element([1, 1]) >>> op = DistOperator(x) >>> derivative = op.derivative([2, 1]) >>> derivative([1, 0]) 1.0 """ point = self.domain.element(point) diff = point - self.vector dist = self.vector.dist(point) if dist == 0: raise ValueError('not differentiable at the reference vector {!r}' ''.format(self.vector)) return InnerProductOperator(diff / dist)
[ "def", "derivative", "(", "self", ",", "point", ")", ":", "point", "=", "self", ".", "domain", ".", "element", "(", "point", ")", "diff", "=", "point", "-", "self", ".", "vector", "dist", "=", "self", ".", "vector", ".", "dist", "(", "point", ")", ...
r"""The derivative operator. ``DistOperator(y).derivative(z)(x) == ((y - z) / y.dist(z)).inner(x)`` This is only applicable in inner product spaces. Parameters ---------- x : `domain` `element-like` Point in which to take the derivative. Returns ------- derivative : `InnerProductOperator` Raises ------ ValueError If ``point == self.vector``, in which case the derivative is not well defined in the Frechet sense. Notes ----- The derivative cannot be written in a general sense except in Hilbert spaces, in which case it is given by .. math:: (D d(\cdot, y))(z)(x) = \langle (y-z) / d(y, z), x \rangle Examples -------- >>> r2 = odl.rn(2) >>> x = r2.element([1, 1]) >>> op = DistOperator(x) >>> derivative = op.derivative([2, 1]) >>> derivative([1, 0]) 1.0
[ "r", "The", "derivative", "operator", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L732-L779
231,528
odlgroup/odl
odl/operator/default_ops.py
ConstantOperator._call
def _call(self, x, out=None): """Return the constant vector or assign it to ``out``.""" if out is None: return self.range.element(copy(self.constant)) else: out.assign(self.constant)
python
def _call(self, x, out=None): if out is None: return self.range.element(copy(self.constant)) else: out.assign(self.constant)
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "return", "self", ".", "range", ".", "element", "(", "copy", "(", "self", ".", "constant", ")", ")", "else", ":", "out", ".", "assign", "(...
Return the constant vector or assign it to ``out``.
[ "Return", "the", "constant", "vector", "or", "assign", "it", "to", "out", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L842-L847
231,529
odlgroup/odl
odl/operator/default_ops.py
ConstantOperator.derivative
def derivative(self, point): """Derivative of this operator, always zero. Returns ------- derivative : `ZeroOperator` Examples -------- >>> r3 = odl.rn(3) >>> x = r3.element([1, 2, 3]) >>> op = ConstantOperator(x) >>> deriv = op.derivative([1, 1, 1]) >>> deriv([2, 2, 2]) rn(3).element([ 0., 0., 0.]) """ return ZeroOperator(domain=self.domain, range=self.range)
python
def derivative(self, point): return ZeroOperator(domain=self.domain, range=self.range)
[ "def", "derivative", "(", "self", ",", "point", ")", ":", "return", "ZeroOperator", "(", "domain", "=", "self", ".", "domain", ",", "range", "=", "self", ".", "range", ")" ]
Derivative of this operator, always zero. Returns ------- derivative : `ZeroOperator` Examples -------- >>> r3 = odl.rn(3) >>> x = r3.element([1, 2, 3]) >>> op = ConstantOperator(x) >>> deriv = op.derivative([1, 1, 1]) >>> deriv([2, 2, 2]) rn(3).element([ 0., 0., 0.])
[ "Derivative", "of", "this", "operator", "always", "zero", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L856-L872
231,530
odlgroup/odl
odl/operator/default_ops.py
ZeroOperator._call
def _call(self, x, out=None): """Return the zero vector or assign it to ``out``.""" if self.domain == self.range: if out is None: out = 0 * x else: out.lincomb(0, x) else: result = self.range.zero() if out is None: out = result else: out.assign(result) return out
python
def _call(self, x, out=None): if self.domain == self.range: if out is None: out = 0 * x else: out.lincomb(0, x) else: result = self.range.zero() if out is None: out = result else: out.assign(result) return out
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ")", ":", "if", "self", ".", "domain", "==", "self", ".", "range", ":", "if", "out", "is", "None", ":", "out", "=", "0", "*", "x", "else", ":", "out", ".", "lincomb", "(", "0", ...
Return the zero vector or assign it to ``out``.
[ "Return", "the", "zero", "vector", "or", "assign", "it", "to", "out", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L919-L932
231,531
odlgroup/odl
odl/operator/default_ops.py
ImagPart.inverse
def inverse(self): """Return the pseudoinverse. Examples -------- The inverse is the zero operator if the domain is real: >>> r3 = odl.rn(3) >>> op = ImagPart(r3) >>> op.inverse(op([1, 2, 3])) rn(3).element([ 0., 0., 0.]) This is not a true inverse, only a pseudoinverse, the real part will by necessity be lost. >>> c3 = odl.cn(3) >>> op = ImagPart(c3) >>> op.inverse(op([1 + 2j, 2, 3 - 1j])) cn(3).element([ 0.+2.j, 0.+0.j, -0.-1.j]) """ if self.space_is_real: return ZeroOperator(self.domain) else: return ComplexEmbedding(self.domain, scalar=1j)
python
def inverse(self): if self.space_is_real: return ZeroOperator(self.domain) else: return ComplexEmbedding(self.domain, scalar=1j)
[ "def", "inverse", "(", "self", ")", ":", "if", "self", ".", "space_is_real", ":", "return", "ZeroOperator", "(", "self", ".", "domain", ")", "else", ":", "return", "ComplexEmbedding", "(", "self", ".", "domain", ",", "scalar", "=", "1j", ")" ]
Return the pseudoinverse. Examples -------- The inverse is the zero operator if the domain is real: >>> r3 = odl.rn(3) >>> op = ImagPart(r3) >>> op.inverse(op([1, 2, 3])) rn(3).element([ 0., 0., 0.]) This is not a true inverse, only a pseudoinverse, the real part will by necessity be lost. >>> c3 = odl.cn(3) >>> op = ImagPart(c3) >>> op.inverse(op([1 + 2j, 2, 3 - 1j])) cn(3).element([ 0.+2.j, 0.+0.j, -0.-1.j])
[ "Return", "the", "pseudoinverse", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L1146-L1169
231,532
odlgroup/odl
odl/contrib/datasets/images/cambridge.py
convert
def convert(image, shape, gray=False, dtype='float64', normalize='max'): """Convert image to standardized format. Several properties of the input image may be changed including the shape, data type and maximal value of the image. In addition, this function may convert the image into an ODL object and/or a gray scale image. """ image = image.astype(dtype) if gray: image[..., 0] *= 0.2126 image[..., 1] *= 0.7152 image[..., 2] *= 0.0722 image = np.sum(image, axis=2) if shape is not None: image = skimage.transform.resize(image, shape, mode='constant') image = image.astype(dtype) if normalize == 'max': image /= image.max() elif normalize == 'sum': image /= image.sum() else: assert False return image
python
def convert(image, shape, gray=False, dtype='float64', normalize='max'): image = image.astype(dtype) if gray: image[..., 0] *= 0.2126 image[..., 1] *= 0.7152 image[..., 2] *= 0.0722 image = np.sum(image, axis=2) if shape is not None: image = skimage.transform.resize(image, shape, mode='constant') image = image.astype(dtype) if normalize == 'max': image /= image.max() elif normalize == 'sum': image /= image.sum() else: assert False return image
[ "def", "convert", "(", "image", ",", "shape", ",", "gray", "=", "False", ",", "dtype", "=", "'float64'", ",", "normalize", "=", "'max'", ")", ":", "image", "=", "image", ".", "astype", "(", "dtype", ")", "if", "gray", ":", "image", "[", "...", ",",...
Convert image to standardized format. Several properties of the input image may be changed including the shape, data type and maximal value of the image. In addition, this function may convert the image into an ODL object and/or a gray scale image.
[ "Convert", "image", "to", "standardized", "format", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/datasets/images/cambridge.py#L32-L59
231,533
odlgroup/odl
odl/contrib/datasets/images/cambridge.py
resolution_phantom
def resolution_phantom(shape=None): """Resolution phantom for tomographic simulations. Returns ------- An image with the following properties: image type: gray scales shape: [1024, 1024] (if not specified by `size`) scale: [0, 1] type: float64 """ # TODO: Store data in some ODL controlled url # TODO: This can be also done with ODL's ellipse_phantom name = 'phantom_resolution.mat' url = URL_CAM + name dct = get_data(name, subset=DATA_SUBSET, url=url) im = np.rot90(dct['im'], k=3) return convert(im, shape)
python
def resolution_phantom(shape=None): # TODO: Store data in some ODL controlled url # TODO: This can be also done with ODL's ellipse_phantom name = 'phantom_resolution.mat' url = URL_CAM + name dct = get_data(name, subset=DATA_SUBSET, url=url) im = np.rot90(dct['im'], k=3) return convert(im, shape)
[ "def", "resolution_phantom", "(", "shape", "=", "None", ")", ":", "# TODO: Store data in some ODL controlled url", "# TODO: This can be also done with ODL's ellipse_phantom", "name", "=", "'phantom_resolution.mat'", "url", "=", "URL_CAM", "+", "name", "dct", "=", "get_data", ...
Resolution phantom for tomographic simulations. Returns ------- An image with the following properties: image type: gray scales shape: [1024, 1024] (if not specified by `size`) scale: [0, 1] type: float64
[ "Resolution", "phantom", "for", "tomographic", "simulations", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/datasets/images/cambridge.py#L82-L100
231,534
odlgroup/odl
odl/contrib/datasets/images/cambridge.py
building
def building(shape=None, gray=False): """Photo of the Centre for Mathematical Sciences in Cambridge. Returns ------- An image with the following properties: image type: color (or gray scales if `gray=True`) size: [442, 331] (if not specified by `size`) scale: [0, 1] type: float64 """ # TODO: Store data in some ODL controlled url name = 'cms.mat' url = URL_CAM + name dct = get_data(name, subset=DATA_SUBSET, url=url) im = np.rot90(dct['im'], k=3) return convert(im, shape, gray=gray)
python
def building(shape=None, gray=False): # TODO: Store data in some ODL controlled url name = 'cms.mat' url = URL_CAM + name dct = get_data(name, subset=DATA_SUBSET, url=url) im = np.rot90(dct['im'], k=3) return convert(im, shape, gray=gray)
[ "def", "building", "(", "shape", "=", "None", ",", "gray", "=", "False", ")", ":", "# TODO: Store data in some ODL controlled url", "name", "=", "'cms.mat'", "url", "=", "URL_CAM", "+", "name", "dct", "=", "get_data", "(", "name", ",", "subset", "=", "DATA_S...
Photo of the Centre for Mathematical Sciences in Cambridge. Returns ------- An image with the following properties: image type: color (or gray scales if `gray=True`) size: [442, 331] (if not specified by `size`) scale: [0, 1] type: float64
[ "Photo", "of", "the", "Centre", "for", "Mathematical", "Sciences", "in", "Cambridge", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/datasets/images/cambridge.py#L103-L120
231,535
odlgroup/odl
odl/contrib/datasets/images/cambridge.py
blurring_kernel
def blurring_kernel(shape=None): """Blurring kernel for convolution simulations. The kernel is scaled to sum to one. Returns ------- An image with the following properties: image type: gray scales size: [100, 100] (if not specified by `size`) scale: [0, 1] type: float64 """ # TODO: Store data in some ODL controlled url name = 'motionblur.mat' url = URL_CAM + name dct = get_data(name, subset=DATA_SUBSET, url=url) return convert(255 - dct['im'], shape, normalize='sum')
python
def blurring_kernel(shape=None): # TODO: Store data in some ODL controlled url name = 'motionblur.mat' url = URL_CAM + name dct = get_data(name, subset=DATA_SUBSET, url=url) return convert(255 - dct['im'], shape, normalize='sum')
[ "def", "blurring_kernel", "(", "shape", "=", "None", ")", ":", "# TODO: Store data in some ODL controlled url", "name", "=", "'motionblur.mat'", "url", "=", "URL_CAM", "+", "name", "dct", "=", "get_data", "(", "name", ",", "subset", "=", "DATA_SUBSET", ",", "url...
Blurring kernel for convolution simulations. The kernel is scaled to sum to one. Returns ------- An image with the following properties: image type: gray scales size: [100, 100] (if not specified by `size`) scale: [0, 1] type: float64
[ "Blurring", "kernel", "for", "convolution", "simulations", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/datasets/images/cambridge.py#L143-L162
231,536
odlgroup/odl
odl/space/base_tensors.py
TensorSpace.real_space
def real_space(self): """The space corresponding to this space's `real_dtype`. Raises ------ ValueError If `dtype` is not a numeric data type. """ if not is_numeric_dtype(self.dtype): raise ValueError( '`real_space` not defined for non-numeric `dtype`') return self.astype(self.real_dtype)
python
def real_space(self): if not is_numeric_dtype(self.dtype): raise ValueError( '`real_space` not defined for non-numeric `dtype`') return self.astype(self.real_dtype)
[ "def", "real_space", "(", "self", ")", ":", "if", "not", "is_numeric_dtype", "(", "self", ".", "dtype", ")", ":", "raise", "ValueError", "(", "'`real_space` not defined for non-numeric `dtype`'", ")", "return", "self", ".", "astype", "(", "self", ".", "real_dtyp...
The space corresponding to this space's `real_dtype`. Raises ------ ValueError If `dtype` is not a numeric data type.
[ "The", "space", "corresponding", "to", "this", "space", "s", "real_dtype", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/base_tensors.py#L179-L190
231,537
odlgroup/odl
odl/space/base_tensors.py
TensorSpace.complex_space
def complex_space(self): """The space corresponding to this space's `complex_dtype`. Raises ------ ValueError If `dtype` is not a numeric data type. """ if not is_numeric_dtype(self.dtype): raise ValueError( '`complex_space` not defined for non-numeric `dtype`') return self.astype(self.complex_dtype)
python
def complex_space(self): if not is_numeric_dtype(self.dtype): raise ValueError( '`complex_space` not defined for non-numeric `dtype`') return self.astype(self.complex_dtype)
[ "def", "complex_space", "(", "self", ")", ":", "if", "not", "is_numeric_dtype", "(", "self", ".", "dtype", ")", ":", "raise", "ValueError", "(", "'`complex_space` not defined for non-numeric `dtype`'", ")", "return", "self", ".", "astype", "(", "self", ".", "com...
The space corresponding to this space's `complex_dtype`. Raises ------ ValueError If `dtype` is not a numeric data type.
[ "The", "space", "corresponding", "to", "this", "space", "s", "complex_dtype", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/base_tensors.py#L193-L204
231,538
odlgroup/odl
odl/space/base_tensors.py
TensorSpace.examples
def examples(self): """Return example random vectors.""" # Always return the same numbers rand_state = np.random.get_state() np.random.seed(1337) if is_numeric_dtype(self.dtype): yield ('Linearly spaced samples', self.element( np.linspace(0, 1, self.size).reshape(self.shape))) yield ('Normally distributed noise', self.element(np.random.standard_normal(self.shape))) if self.is_real: yield ('Uniformly distributed noise', self.element(np.random.uniform(size=self.shape))) elif self.is_complex: yield ('Uniformly distributed noise', self.element(np.random.uniform(size=self.shape) + np.random.uniform(size=self.shape) * 1j)) else: # TODO: return something that always works, like zeros or ones? raise NotImplementedError('no examples available for non-numeric' 'data type') np.random.set_state(rand_state)
python
def examples(self): # Always return the same numbers rand_state = np.random.get_state() np.random.seed(1337) if is_numeric_dtype(self.dtype): yield ('Linearly spaced samples', self.element( np.linspace(0, 1, self.size).reshape(self.shape))) yield ('Normally distributed noise', self.element(np.random.standard_normal(self.shape))) if self.is_real: yield ('Uniformly distributed noise', self.element(np.random.uniform(size=self.shape))) elif self.is_complex: yield ('Uniformly distributed noise', self.element(np.random.uniform(size=self.shape) + np.random.uniform(size=self.shape) * 1j)) else: # TODO: return something that always works, like zeros or ones? raise NotImplementedError('no examples available for non-numeric' 'data type') np.random.set_state(rand_state)
[ "def", "examples", "(", "self", ")", ":", "# Always return the same numbers", "rand_state", "=", "np", ".", "random", ".", "get_state", "(", ")", "np", ".", "random", ".", "seed", "(", "1337", ")", "if", "is_numeric_dtype", "(", "self", ".", "dtype", ")", ...
Return example random vectors.
[ "Return", "example", "random", "vectors", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/base_tensors.py#L410-L434
231,539
odlgroup/odl
odl/tomo/backends/astra_setup.py
astra_supports
def astra_supports(feature): """Return bool indicating whether current ASTRA supports ``feature``. Parameters ---------- feature : str Name of a potential feature of ASTRA. See ``ASTRA_FEATURES`` for possible values. Returns ------- supports : bool ``True`` if the currently imported version of ASTRA supports the feature in question, ``False`` otherwise. """ from odl.util.utility import pkg_supports return pkg_supports(feature, ASTRA_VERSION, ASTRA_FEATURES)
python
def astra_supports(feature): from odl.util.utility import pkg_supports return pkg_supports(feature, ASTRA_VERSION, ASTRA_FEATURES)
[ "def", "astra_supports", "(", "feature", ")", ":", "from", "odl", ".", "util", ".", "utility", "import", "pkg_supports", "return", "pkg_supports", "(", "feature", ",", "ASTRA_VERSION", ",", "ASTRA_FEATURES", ")" ]
Return bool indicating whether current ASTRA supports ``feature``. Parameters ---------- feature : str Name of a potential feature of ASTRA. See ``ASTRA_FEATURES`` for possible values. Returns ------- supports : bool ``True`` if the currently imported version of ASTRA supports the feature in question, ``False`` otherwise.
[ "Return", "bool", "indicating", "whether", "current", "ASTRA", "supports", "feature", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/backends/astra_setup.py#L117-L133
231,540
odlgroup/odl
odl/tomo/backends/astra_setup.py
astra_volume_geometry
def astra_volume_geometry(reco_space): """Create an ASTRA volume geometry from the discretized domain. From the ASTRA documentation: In all 3D geometries, the coordinate system is defined around the reconstruction volume. The center of the reconstruction volume is the origin, and the sides of the voxels in the volume have length 1. All dimensions in the projection geometries are relative to this unit length. Parameters ---------- reco_space : `DiscreteLp` Discretized space where the reconstruction (volume) lives. It must be 2- or 3-dimensional and uniformly discretized. Returns ------- astra_geom : dict Raises ------ NotImplementedError If the cell sizes are not the same in each dimension. """ if not isinstance(reco_space, DiscreteLp): raise TypeError('`reco_space` {!r} is not a DiscreteLp instance' ''.format(reco_space)) if not reco_space.is_uniform: raise ValueError('`reco_space` {} is not uniformly discretized') vol_shp = reco_space.partition.shape vol_min = reco_space.partition.min_pt vol_max = reco_space.partition.max_pt if reco_space.ndim == 2: # ASTRA does in principle support custom minimum and maximum # values for the volume extent also in earlier versions, but running # the algorithm fails if voxels are non-isotropic. if (not reco_space.partition.has_isotropic_cells and not astra_supports('anisotropic_voxels_2d')): raise NotImplementedError( 'non-isotropic pixels in 2d volumes not supported by ASTRA ' 'v{}'.format(ASTRA_VERSION)) # Given a 2D array of shape (x, y), a volume geometry is created as: # astra.create_vol_geom(x, y, y_min, y_max, x_min, x_max) # yielding a dictionary: # {'GridRowCount': x, # 'GridColCount': y, # 'WindowMinX': y_min, # 'WindowMaxX': y_max, # 'WindowMinY': x_min, # 'WindowMaxY': x_max} # # NOTE: this setting is flipped with respect to x and y. We do this # as part of a global rotation of the geometry by -90 degrees, which # avoids rotating the data. # NOTE: We need to flip the sign of the (ODL) x component since # ASTRA seems to move it in the other direction. Not quite clear # why. vol_geom = astra.create_vol_geom(vol_shp[0], vol_shp[1], vol_min[1], vol_max[1], -vol_max[0], -vol_min[0]) elif reco_space.ndim == 3: # Not supported in all versions of ASTRA if (not reco_space.partition.has_isotropic_cells and not astra_supports('anisotropic_voxels_3d')): raise NotImplementedError( 'non-isotropic voxels in 3d volumes not supported by ASTRA ' 'v{}'.format(ASTRA_VERSION)) # Given a 3D array of shape (x, y, z), a volume geometry is created as: # astra.create_vol_geom(y, z, x, z_min, z_max, y_min, y_max, # x_min, x_max), # yielding a dictionary: # {'GridColCount': z, # 'GridRowCount': y, # 'GridSliceCount': x, # 'WindowMinX': z_max, # 'WindowMaxX': z_max, # 'WindowMinY': y_min, # 'WindowMaxY': y_min, # 'WindowMinZ': x_min, # 'WindowMaxZ': x_min} vol_geom = astra.create_vol_geom(vol_shp[1], vol_shp[2], vol_shp[0], vol_min[2], vol_max[2], vol_min[1], vol_max[1], vol_min[0], vol_max[0]) else: raise ValueError('{}-dimensional volume geometries not supported ' 'by ASTRA'.format(reco_space.ndim)) return vol_geom
python
def astra_volume_geometry(reco_space): if not isinstance(reco_space, DiscreteLp): raise TypeError('`reco_space` {!r} is not a DiscreteLp instance' ''.format(reco_space)) if not reco_space.is_uniform: raise ValueError('`reco_space` {} is not uniformly discretized') vol_shp = reco_space.partition.shape vol_min = reco_space.partition.min_pt vol_max = reco_space.partition.max_pt if reco_space.ndim == 2: # ASTRA does in principle support custom minimum and maximum # values for the volume extent also in earlier versions, but running # the algorithm fails if voxels are non-isotropic. if (not reco_space.partition.has_isotropic_cells and not astra_supports('anisotropic_voxels_2d')): raise NotImplementedError( 'non-isotropic pixels in 2d volumes not supported by ASTRA ' 'v{}'.format(ASTRA_VERSION)) # Given a 2D array of shape (x, y), a volume geometry is created as: # astra.create_vol_geom(x, y, y_min, y_max, x_min, x_max) # yielding a dictionary: # {'GridRowCount': x, # 'GridColCount': y, # 'WindowMinX': y_min, # 'WindowMaxX': y_max, # 'WindowMinY': x_min, # 'WindowMaxY': x_max} # # NOTE: this setting is flipped with respect to x and y. We do this # as part of a global rotation of the geometry by -90 degrees, which # avoids rotating the data. # NOTE: We need to flip the sign of the (ODL) x component since # ASTRA seems to move it in the other direction. Not quite clear # why. vol_geom = astra.create_vol_geom(vol_shp[0], vol_shp[1], vol_min[1], vol_max[1], -vol_max[0], -vol_min[0]) elif reco_space.ndim == 3: # Not supported in all versions of ASTRA if (not reco_space.partition.has_isotropic_cells and not astra_supports('anisotropic_voxels_3d')): raise NotImplementedError( 'non-isotropic voxels in 3d volumes not supported by ASTRA ' 'v{}'.format(ASTRA_VERSION)) # Given a 3D array of shape (x, y, z), a volume geometry is created as: # astra.create_vol_geom(y, z, x, z_min, z_max, y_min, y_max, # x_min, x_max), # yielding a dictionary: # {'GridColCount': z, # 'GridRowCount': y, # 'GridSliceCount': x, # 'WindowMinX': z_max, # 'WindowMaxX': z_max, # 'WindowMinY': y_min, # 'WindowMaxY': y_min, # 'WindowMinZ': x_min, # 'WindowMaxZ': x_min} vol_geom = astra.create_vol_geom(vol_shp[1], vol_shp[2], vol_shp[0], vol_min[2], vol_max[2], vol_min[1], vol_max[1], vol_min[0], vol_max[0]) else: raise ValueError('{}-dimensional volume geometries not supported ' 'by ASTRA'.format(reco_space.ndim)) return vol_geom
[ "def", "astra_volume_geometry", "(", "reco_space", ")", ":", "if", "not", "isinstance", "(", "reco_space", ",", "DiscreteLp", ")", ":", "raise", "TypeError", "(", "'`reco_space` {!r} is not a DiscreteLp instance'", "''", ".", "format", "(", "reco_space", ")", ")", ...
Create an ASTRA volume geometry from the discretized domain. From the ASTRA documentation: In all 3D geometries, the coordinate system is defined around the reconstruction volume. The center of the reconstruction volume is the origin, and the sides of the voxels in the volume have length 1. All dimensions in the projection geometries are relative to this unit length. Parameters ---------- reco_space : `DiscreteLp` Discretized space where the reconstruction (volume) lives. It must be 2- or 3-dimensional and uniformly discretized. Returns ------- astra_geom : dict Raises ------ NotImplementedError If the cell sizes are not the same in each dimension.
[ "Create", "an", "ASTRA", "volume", "geometry", "from", "the", "discretized", "domain", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/backends/astra_setup.py#L136-L230
231,541
odlgroup/odl
odl/tomo/backends/astra_setup.py
astra_projection_geometry
def astra_projection_geometry(geometry): """Create an ASTRA projection geometry from an ODL geometry object. As of ASTRA version 1.7, the length values are not required any more to be rescaled for 3D geometries and non-unit (but isotropic) voxel sizes. Parameters ---------- geometry : `Geometry` ODL projection geometry from which to create the ASTRA geometry. Returns ------- proj_geom : dict Dictionary defining the ASTRA projection geometry. """ if not isinstance(geometry, Geometry): raise TypeError('`geometry` {!r} is not a `Geometry` instance' ''.format(geometry)) if 'astra' in geometry.implementation_cache: # Shortcut, reuse already computed value. return geometry.implementation_cache['astra'] if not geometry.det_partition.is_uniform: raise ValueError('non-uniform detector sampling is not supported') if (isinstance(geometry, ParallelBeamGeometry) and isinstance(geometry.detector, (Flat1dDetector, Flat2dDetector)) and geometry.ndim == 2): # TODO: change to parallel_vec when available det_width = geometry.det_partition.cell_sides[0] det_count = geometry.detector.size # Instead of rotating the data by 90 degrees counter-clockwise, # we subtract pi/2 from the geometry angles, thereby rotating the # geometry by 90 degrees clockwise angles = geometry.angles - np.pi / 2 proj_geom = astra.create_proj_geom('parallel', det_width, det_count, angles) elif (isinstance(geometry, DivergentBeamGeometry) and isinstance(geometry.detector, (Flat1dDetector, Flat2dDetector)) and geometry.ndim == 2): det_count = geometry.detector.size vec = astra_conebeam_2d_geom_to_vec(geometry) proj_geom = astra.create_proj_geom('fanflat_vec', det_count, vec) elif (isinstance(geometry, ParallelBeamGeometry) and isinstance(geometry.detector, (Flat1dDetector, Flat2dDetector)) and geometry.ndim == 3): # Swap detector axes (see astra_*_3d_to_vec) det_row_count = geometry.det_partition.shape[0] det_col_count = geometry.det_partition.shape[1] vec = astra_parallel_3d_geom_to_vec(geometry) proj_geom = astra.create_proj_geom('parallel3d_vec', det_row_count, det_col_count, vec) elif (isinstance(geometry, DivergentBeamGeometry) and isinstance(geometry.detector, (Flat1dDetector, Flat2dDetector)) and geometry.ndim == 3): # Swap detector axes (see astra_*_3d_to_vec) det_row_count = geometry.det_partition.shape[0] det_col_count = geometry.det_partition.shape[1] vec = astra_conebeam_3d_geom_to_vec(geometry) proj_geom = astra.create_proj_geom('cone_vec', det_row_count, det_col_count, vec) else: raise NotImplementedError('unknown ASTRA geometry type {!r}' ''.format(geometry)) if 'astra' not in geometry.implementation_cache: # Save computed value for later geometry.implementation_cache['astra'] = proj_geom return proj_geom
python
def astra_projection_geometry(geometry): if not isinstance(geometry, Geometry): raise TypeError('`geometry` {!r} is not a `Geometry` instance' ''.format(geometry)) if 'astra' in geometry.implementation_cache: # Shortcut, reuse already computed value. return geometry.implementation_cache['astra'] if not geometry.det_partition.is_uniform: raise ValueError('non-uniform detector sampling is not supported') if (isinstance(geometry, ParallelBeamGeometry) and isinstance(geometry.detector, (Flat1dDetector, Flat2dDetector)) and geometry.ndim == 2): # TODO: change to parallel_vec when available det_width = geometry.det_partition.cell_sides[0] det_count = geometry.detector.size # Instead of rotating the data by 90 degrees counter-clockwise, # we subtract pi/2 from the geometry angles, thereby rotating the # geometry by 90 degrees clockwise angles = geometry.angles - np.pi / 2 proj_geom = astra.create_proj_geom('parallel', det_width, det_count, angles) elif (isinstance(geometry, DivergentBeamGeometry) and isinstance(geometry.detector, (Flat1dDetector, Flat2dDetector)) and geometry.ndim == 2): det_count = geometry.detector.size vec = astra_conebeam_2d_geom_to_vec(geometry) proj_geom = astra.create_proj_geom('fanflat_vec', det_count, vec) elif (isinstance(geometry, ParallelBeamGeometry) and isinstance(geometry.detector, (Flat1dDetector, Flat2dDetector)) and geometry.ndim == 3): # Swap detector axes (see astra_*_3d_to_vec) det_row_count = geometry.det_partition.shape[0] det_col_count = geometry.det_partition.shape[1] vec = astra_parallel_3d_geom_to_vec(geometry) proj_geom = astra.create_proj_geom('parallel3d_vec', det_row_count, det_col_count, vec) elif (isinstance(geometry, DivergentBeamGeometry) and isinstance(geometry.detector, (Flat1dDetector, Flat2dDetector)) and geometry.ndim == 3): # Swap detector axes (see astra_*_3d_to_vec) det_row_count = geometry.det_partition.shape[0] det_col_count = geometry.det_partition.shape[1] vec = astra_conebeam_3d_geom_to_vec(geometry) proj_geom = astra.create_proj_geom('cone_vec', det_row_count, det_col_count, vec) else: raise NotImplementedError('unknown ASTRA geometry type {!r}' ''.format(geometry)) if 'astra' not in geometry.implementation_cache: # Save computed value for later geometry.implementation_cache['astra'] = proj_geom return proj_geom
[ "def", "astra_projection_geometry", "(", "geometry", ")", ":", "if", "not", "isinstance", "(", "geometry", ",", "Geometry", ")", ":", "raise", "TypeError", "(", "'`geometry` {!r} is not a `Geometry` instance'", "''", ".", "format", "(", "geometry", ")", ")", "if",...
Create an ASTRA projection geometry from an ODL geometry object. As of ASTRA version 1.7, the length values are not required any more to be rescaled for 3D geometries and non-unit (but isotropic) voxel sizes. Parameters ---------- geometry : `Geometry` ODL projection geometry from which to create the ASTRA geometry. Returns ------- proj_geom : dict Dictionary defining the ASTRA projection geometry.
[ "Create", "an", "ASTRA", "projection", "geometry", "from", "an", "ODL", "geometry", "object", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/backends/astra_setup.py#L428-L502
231,542
odlgroup/odl
odl/tomo/backends/astra_setup.py
astra_data
def astra_data(astra_geom, datatype, data=None, ndim=2, allow_copy=False): """Create an ASTRA data object. Parameters ---------- astra_geom : dict ASTRA geometry object for the data creator, must correspond to the given ``datatype``. datatype : {'volume', 'projection'} Type of the data container. data : `DiscreteLpElement` or `numpy.ndarray`, optional Data for the initialization of the data object. If ``None``, an ASTRA data object filled with zeros is created. ndim : {2, 3}, optional Dimension of the data. If ``data`` is provided, this parameter has no effect. allow_copy : `bool`, optional If ``True``, allow copying of ``data``. This means that anything written by ASTRA to the returned object will not be written to ``data``. Returns ------- id : int Handle for the new ASTRA internal data object. """ if data is not None: if isinstance(data, (DiscreteLpElement, np.ndarray)): ndim = data.ndim else: raise TypeError('`data` {!r} is neither DiscreteLpElement ' 'instance nor a `numpy.ndarray`'.format(data)) else: ndim = int(ndim) if datatype == 'volume': astra_dtype_str = '-vol' elif datatype == 'projection': astra_dtype_str = '-sino' else: raise ValueError('`datatype` {!r} not understood'.format(datatype)) # Get the functions from the correct module if ndim == 2: link = astra.data2d.link create = astra.data2d.create elif ndim == 3: link = astra.data3d.link create = astra.data3d.create else: raise ValueError('{}-dimensional data not supported' ''.format(ndim)) # ASTRA checks if data is c-contiguous and aligned if data is not None: if allow_copy: data_array = np.asarray(data, dtype='float32', order='C') return link(astra_dtype_str, astra_geom, data_array) else: if isinstance(data, np.ndarray): return link(astra_dtype_str, astra_geom, data) elif data.tensor.impl == 'numpy': return link(astra_dtype_str, astra_geom, data.asarray()) else: # Something else than NumPy data representation raise NotImplementedError('ASTRA supports data wrapping only ' 'for `numpy.ndarray` instances, got ' '{!r}'.format(data)) else: return create(astra_dtype_str, astra_geom)
python
def astra_data(astra_geom, datatype, data=None, ndim=2, allow_copy=False): if data is not None: if isinstance(data, (DiscreteLpElement, np.ndarray)): ndim = data.ndim else: raise TypeError('`data` {!r} is neither DiscreteLpElement ' 'instance nor a `numpy.ndarray`'.format(data)) else: ndim = int(ndim) if datatype == 'volume': astra_dtype_str = '-vol' elif datatype == 'projection': astra_dtype_str = '-sino' else: raise ValueError('`datatype` {!r} not understood'.format(datatype)) # Get the functions from the correct module if ndim == 2: link = astra.data2d.link create = astra.data2d.create elif ndim == 3: link = astra.data3d.link create = astra.data3d.create else: raise ValueError('{}-dimensional data not supported' ''.format(ndim)) # ASTRA checks if data is c-contiguous and aligned if data is not None: if allow_copy: data_array = np.asarray(data, dtype='float32', order='C') return link(astra_dtype_str, astra_geom, data_array) else: if isinstance(data, np.ndarray): return link(astra_dtype_str, astra_geom, data) elif data.tensor.impl == 'numpy': return link(astra_dtype_str, astra_geom, data.asarray()) else: # Something else than NumPy data representation raise NotImplementedError('ASTRA supports data wrapping only ' 'for `numpy.ndarray` instances, got ' '{!r}'.format(data)) else: return create(astra_dtype_str, astra_geom)
[ "def", "astra_data", "(", "astra_geom", ",", "datatype", ",", "data", "=", "None", ",", "ndim", "=", "2", ",", "allow_copy", "=", "False", ")", ":", "if", "data", "is", "not", "None", ":", "if", "isinstance", "(", "data", ",", "(", "DiscreteLpElement",...
Create an ASTRA data object. Parameters ---------- astra_geom : dict ASTRA geometry object for the data creator, must correspond to the given ``datatype``. datatype : {'volume', 'projection'} Type of the data container. data : `DiscreteLpElement` or `numpy.ndarray`, optional Data for the initialization of the data object. If ``None``, an ASTRA data object filled with zeros is created. ndim : {2, 3}, optional Dimension of the data. If ``data`` is provided, this parameter has no effect. allow_copy : `bool`, optional If ``True``, allow copying of ``data``. This means that anything written by ASTRA to the returned object will not be written to ``data``. Returns ------- id : int Handle for the new ASTRA internal data object.
[ "Create", "an", "ASTRA", "data", "object", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/backends/astra_setup.py#L505-L574
231,543
odlgroup/odl
odl/tomo/backends/astra_setup.py
astra_projector
def astra_projector(vol_interp, astra_vol_geom, astra_proj_geom, ndim, impl): """Create an ASTRA projector configuration dictionary. Parameters ---------- vol_interp : {'nearest', 'linear'} Interpolation type of the volume discretization. This determines the projection model that is chosen. astra_vol_geom : dict ASTRA volume geometry. astra_proj_geom : dict ASTRA projection geometry. ndim : {2, 3} Number of dimensions of the projector. impl : {'cpu', 'cuda'} Implementation of the projector. Returns ------- proj_id : int Handle for the created ASTRA internal projector object. """ if vol_interp not in ('nearest', 'linear'): raise ValueError("`vol_interp` '{}' not understood" ''.format(vol_interp)) impl = str(impl).lower() if impl not in ('cpu', 'cuda'): raise ValueError("`impl` '{}' not understood" ''.format(impl)) if 'type' not in astra_proj_geom: raise ValueError('invalid projection geometry dict {}' ''.format(astra_proj_geom)) if ndim == 3 and impl == 'cpu': raise ValueError('3D projectors not supported on CPU') ndim = int(ndim) proj_type = astra_proj_geom['type'] if proj_type not in ('parallel', 'fanflat', 'fanflat_vec', 'parallel3d', 'parallel3d_vec', 'cone', 'cone_vec'): raise ValueError('invalid geometry type {!r}'.format(proj_type)) # Mapping from interpolation type and geometry to ASTRA projector type. # "I" means probably mathematically inconsistent. Some projectors are # not implemented, e.g. CPU 3d projectors in general. type_map_cpu = {'parallel': {'nearest': 'line', 'linear': 'linear'}, # I 'fanflat': {'nearest': 'line_fanflat', 'linear': 'line_fanflat'}, # I 'parallel3d': {'nearest': 'linear3d', # I 'linear': 'linear3d'}, # I 'cone': {'nearest': 'linearcone', # I 'linear': 'linearcone'}} # I type_map_cpu['fanflat_vec'] = type_map_cpu['fanflat'] type_map_cpu['parallel3d_vec'] = type_map_cpu['parallel3d'] type_map_cpu['cone_vec'] = type_map_cpu['cone'] # GPU algorithms not necessarily require a projector, but will in future # releases making the interface more coherent regarding CPU and GPU type_map_cuda = {'parallel': 'cuda', # I 'parallel3d': 'cuda3d'} # I type_map_cuda['fanflat'] = type_map_cuda['parallel'] type_map_cuda['fanflat_vec'] = type_map_cuda['fanflat'] type_map_cuda['cone'] = type_map_cuda['parallel3d'] type_map_cuda['parallel3d_vec'] = type_map_cuda['parallel3d'] type_map_cuda['cone_vec'] = type_map_cuda['cone'] # create config dict proj_cfg = {} if impl == 'cpu': proj_cfg['type'] = type_map_cpu[proj_type][vol_interp] else: # impl == 'cuda' proj_cfg['type'] = type_map_cuda[proj_type] proj_cfg['VolumeGeometry'] = astra_vol_geom proj_cfg['ProjectionGeometry'] = astra_proj_geom proj_cfg['options'] = {} # Add the hacky 1/r^2 weighting exposed in intermediate versions of # ASTRA if (proj_type in ('cone', 'cone_vec') and astra_supports('cone3d_hacky_density_weighting')): proj_cfg['options']['DensityWeighting'] = True if ndim == 2: return astra.projector.create(proj_cfg) else: return astra.projector3d.create(proj_cfg)
python
def astra_projector(vol_interp, astra_vol_geom, astra_proj_geom, ndim, impl): if vol_interp not in ('nearest', 'linear'): raise ValueError("`vol_interp` '{}' not understood" ''.format(vol_interp)) impl = str(impl).lower() if impl not in ('cpu', 'cuda'): raise ValueError("`impl` '{}' not understood" ''.format(impl)) if 'type' not in astra_proj_geom: raise ValueError('invalid projection geometry dict {}' ''.format(astra_proj_geom)) if ndim == 3 and impl == 'cpu': raise ValueError('3D projectors not supported on CPU') ndim = int(ndim) proj_type = astra_proj_geom['type'] if proj_type not in ('parallel', 'fanflat', 'fanflat_vec', 'parallel3d', 'parallel3d_vec', 'cone', 'cone_vec'): raise ValueError('invalid geometry type {!r}'.format(proj_type)) # Mapping from interpolation type and geometry to ASTRA projector type. # "I" means probably mathematically inconsistent. Some projectors are # not implemented, e.g. CPU 3d projectors in general. type_map_cpu = {'parallel': {'nearest': 'line', 'linear': 'linear'}, # I 'fanflat': {'nearest': 'line_fanflat', 'linear': 'line_fanflat'}, # I 'parallel3d': {'nearest': 'linear3d', # I 'linear': 'linear3d'}, # I 'cone': {'nearest': 'linearcone', # I 'linear': 'linearcone'}} # I type_map_cpu['fanflat_vec'] = type_map_cpu['fanflat'] type_map_cpu['parallel3d_vec'] = type_map_cpu['parallel3d'] type_map_cpu['cone_vec'] = type_map_cpu['cone'] # GPU algorithms not necessarily require a projector, but will in future # releases making the interface more coherent regarding CPU and GPU type_map_cuda = {'parallel': 'cuda', # I 'parallel3d': 'cuda3d'} # I type_map_cuda['fanflat'] = type_map_cuda['parallel'] type_map_cuda['fanflat_vec'] = type_map_cuda['fanflat'] type_map_cuda['cone'] = type_map_cuda['parallel3d'] type_map_cuda['parallel3d_vec'] = type_map_cuda['parallel3d'] type_map_cuda['cone_vec'] = type_map_cuda['cone'] # create config dict proj_cfg = {} if impl == 'cpu': proj_cfg['type'] = type_map_cpu[proj_type][vol_interp] else: # impl == 'cuda' proj_cfg['type'] = type_map_cuda[proj_type] proj_cfg['VolumeGeometry'] = astra_vol_geom proj_cfg['ProjectionGeometry'] = astra_proj_geom proj_cfg['options'] = {} # Add the hacky 1/r^2 weighting exposed in intermediate versions of # ASTRA if (proj_type in ('cone', 'cone_vec') and astra_supports('cone3d_hacky_density_weighting')): proj_cfg['options']['DensityWeighting'] = True if ndim == 2: return astra.projector.create(proj_cfg) else: return astra.projector3d.create(proj_cfg)
[ "def", "astra_projector", "(", "vol_interp", ",", "astra_vol_geom", ",", "astra_proj_geom", ",", "ndim", ",", "impl", ")", ":", "if", "vol_interp", "not", "in", "(", "'nearest'", ",", "'linear'", ")", ":", "raise", "ValueError", "(", "\"`vol_interp` '{}' not und...
Create an ASTRA projector configuration dictionary. Parameters ---------- vol_interp : {'nearest', 'linear'} Interpolation type of the volume discretization. This determines the projection model that is chosen. astra_vol_geom : dict ASTRA volume geometry. astra_proj_geom : dict ASTRA projection geometry. ndim : {2, 3} Number of dimensions of the projector. impl : {'cpu', 'cuda'} Implementation of the projector. Returns ------- proj_id : int Handle for the created ASTRA internal projector object.
[ "Create", "an", "ASTRA", "projector", "configuration", "dictionary", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/backends/astra_setup.py#L577-L664
231,544
odlgroup/odl
odl/tomo/backends/astra_setup.py
astra_algorithm
def astra_algorithm(direction, ndim, vol_id, sino_id, proj_id, impl): """Create an ASTRA algorithm object to run the projector. Parameters ---------- direction : {'forward', 'backward'} For ``'forward'``, apply the forward projection, for ``'backward'`` the backprojection. ndim : {2, 3} Number of dimensions of the projector. vol_id : int Handle for the ASTRA volume data object. sino_id : int Handle for the ASTRA projection data object. proj_id : int Handle for the ASTRA projector object. impl : {'cpu', 'cuda'} Implementation of the projector. Returns ------- id : int Handle for the created ASTRA internal algorithm object. """ if direction not in ('forward', 'backward'): raise ValueError("`direction` '{}' not understood".format(direction)) if ndim not in (2, 3): raise ValueError('{}-dimensional projectors not supported' ''.format(ndim)) if impl not in ('cpu', 'cuda'): raise ValueError("`impl` type '{}' not understood" ''.format(impl)) if ndim == 3 and impl == 'cpu': raise NotImplementedError( '3d algorithms for CPU not supported by ASTRA') if proj_id is None and impl == 'cpu': raise ValueError("'cpu' implementation requires projector ID") algo_map = {'forward': {2: {'cpu': 'FP', 'cuda': 'FP_CUDA'}, 3: {'cpu': None, 'cuda': 'FP3D_CUDA'}}, 'backward': {2: {'cpu': 'BP', 'cuda': 'BP_CUDA'}, 3: {'cpu': None, 'cuda': 'BP3D_CUDA'}}} algo_cfg = {'type': algo_map[direction][ndim][impl], 'ProjectorId': proj_id, 'ProjectionDataId': sino_id} if direction is 'forward': algo_cfg['VolumeDataId'] = vol_id else: algo_cfg['ReconstructionDataId'] = vol_id # Create ASTRA algorithm object return astra.algorithm.create(algo_cfg)
python
def astra_algorithm(direction, ndim, vol_id, sino_id, proj_id, impl): if direction not in ('forward', 'backward'): raise ValueError("`direction` '{}' not understood".format(direction)) if ndim not in (2, 3): raise ValueError('{}-dimensional projectors not supported' ''.format(ndim)) if impl not in ('cpu', 'cuda'): raise ValueError("`impl` type '{}' not understood" ''.format(impl)) if ndim == 3 and impl == 'cpu': raise NotImplementedError( '3d algorithms for CPU not supported by ASTRA') if proj_id is None and impl == 'cpu': raise ValueError("'cpu' implementation requires projector ID") algo_map = {'forward': {2: {'cpu': 'FP', 'cuda': 'FP_CUDA'}, 3: {'cpu': None, 'cuda': 'FP3D_CUDA'}}, 'backward': {2: {'cpu': 'BP', 'cuda': 'BP_CUDA'}, 3: {'cpu': None, 'cuda': 'BP3D_CUDA'}}} algo_cfg = {'type': algo_map[direction][ndim][impl], 'ProjectorId': proj_id, 'ProjectionDataId': sino_id} if direction is 'forward': algo_cfg['VolumeDataId'] = vol_id else: algo_cfg['ReconstructionDataId'] = vol_id # Create ASTRA algorithm object return astra.algorithm.create(algo_cfg)
[ "def", "astra_algorithm", "(", "direction", ",", "ndim", ",", "vol_id", ",", "sino_id", ",", "proj_id", ",", "impl", ")", ":", "if", "direction", "not", "in", "(", "'forward'", ",", "'backward'", ")", ":", "raise", "ValueError", "(", "\"`direction` '{}' not ...
Create an ASTRA algorithm object to run the projector. Parameters ---------- direction : {'forward', 'backward'} For ``'forward'``, apply the forward projection, for ``'backward'`` the backprojection. ndim : {2, 3} Number of dimensions of the projector. vol_id : int Handle for the ASTRA volume data object. sino_id : int Handle for the ASTRA projection data object. proj_id : int Handle for the ASTRA projector object. impl : {'cpu', 'cuda'} Implementation of the projector. Returns ------- id : int Handle for the created ASTRA internal algorithm object.
[ "Create", "an", "ASTRA", "algorithm", "object", "to", "run", "the", "projector", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/backends/astra_setup.py#L667-L719
231,545
odlgroup/odl
odl/contrib/tensorflow/layer.py
space_shape
def space_shape(space): """Return ``space.shape``, including power space base shape. If ``space`` is a power space, return ``(len(space),) + space[0].shape``, otherwise return ``space.shape``. """ if isinstance(space, odl.ProductSpace) and space.is_power_space: return (len(space),) + space[0].shape else: return space.shape
python
def space_shape(space): if isinstance(space, odl.ProductSpace) and space.is_power_space: return (len(space),) + space[0].shape else: return space.shape
[ "def", "space_shape", "(", "space", ")", ":", "if", "isinstance", "(", "space", ",", "odl", ".", "ProductSpace", ")", "and", "space", ".", "is_power_space", ":", "return", "(", "len", "(", "space", ")", ",", ")", "+", "space", "[", "0", "]", ".", "...
Return ``space.shape``, including power space base shape. If ``space`` is a power space, return ``(len(space),) + space[0].shape``, otherwise return ``space.shape``.
[ "Return", "space", ".", "shape", "including", "power", "space", "base", "shape", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/tensorflow/layer.py#L385-L394
231,546
odlgroup/odl
doc/source/getting_started/code/getting_started_convolution.py
Convolution._call
def _call(self, x): """Implement calling the operator by calling scipy.""" return scipy.signal.fftconvolve(self.kernel, x, mode='same')
python
def _call(self, x): return scipy.signal.fftconvolve(self.kernel, x, mode='same')
[ "def", "_call", "(", "self", ",", "x", ")", ":", "return", "scipy", ".", "signal", ".", "fftconvolve", "(", "self", ".", "kernel", ",", "x", ",", "mode", "=", "'same'", ")" ]
Implement calling the operator by calling scipy.
[ "Implement", "calling", "the", "operator", "by", "calling", "scipy", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/doc/source/getting_started/code/getting_started_convolution.py#L25-L27
231,547
odlgroup/odl
odl/util/numerics.py
apply_on_boundary
def apply_on_boundary(array, func, only_once=True, which_boundaries=None, axis_order=None, out=None): """Apply a function of the boundary of an n-dimensional array. All other values are preserved as-is. Parameters ---------- array : `array-like` Modify the boundary of this array func : callable or sequence of callables If a single function is given, assign ``array[slice] = func(array[slice])`` on the boundary slices, e.g. use ``lamda x: x / 2`` to divide values by 2. A sequence of functions is applied per axis separately. It must have length ``array.ndim`` and may consist of one function or a 2-tuple of functions per axis. ``None`` entries in a sequence cause the axis (side) to be skipped. only_once : bool, optional If ``True``, ensure that each boundary point appears in exactly one slice. If ``func`` is a list of functions, the ``axis_order`` determines which functions are applied to nodes which appear in multiple slices, according to the principle "first-come, first-served". which_boundaries : sequence, optional If provided, this sequence determines per axis whether to apply the function at the boundaries in each axis. The entry in each axis may consist in a single bool or a 2-tuple of bool. In the latter case, the first tuple entry decides for the left, the second for the right boundary. The length of the sequence must be ``array.ndim``. ``None`` is interpreted as "all boundaries". axis_order : sequence of ints, optional Permutation of ``range(array.ndim)`` defining the order in which to process the axes. If combined with ``only_once`` and a function list, this determines which function is evaluated in the points that are potentially processed multiple times. out : `numpy.ndarray`, optional Location in which to store the result, can be the same as ``array``. Default: copy of ``array`` Examples -------- >>> arr = np.ones((3, 3)) >>> apply_on_boundary(arr, lambda x: x / 2) array([[ 0.5, 0.5, 0.5], [ 0.5, 1. , 0.5], [ 0.5, 0.5, 0.5]]) If called with ``only_once=False``, the function is applied repeatedly: >>> apply_on_boundary(arr, lambda x: x / 2, only_once=False) array([[ 0.25, 0.5 , 0.25], [ 0.5 , 1. , 0.5 ], [ 0.25, 0.5 , 0.25]]) >>> apply_on_boundary(arr, lambda x: x / 2, only_once=True, ... which_boundaries=((True, False), True)) array([[ 0.5, 0.5, 0.5], [ 0.5, 1. , 0.5], [ 0.5, 1. , 0.5]]) Use the ``out`` parameter to store the result in an existing array: >>> out = np.empty_like(arr) >>> result = apply_on_boundary(arr, lambda x: x / 2, out=out) >>> result array([[ 0.5, 0.5, 0.5], [ 0.5, 1. , 0.5], [ 0.5, 0.5, 0.5]]) >>> result is out True """ array = np.asarray(array) if callable(func): func = [func] * array.ndim elif len(func) != array.ndim: raise ValueError('sequence of functions has length {}, expected {}' ''.format(len(func), array.ndim)) if which_boundaries is None: which_boundaries = ([(True, True)] * array.ndim) elif len(which_boundaries) != array.ndim: raise ValueError('`which_boundaries` has length {}, expected {}' ''.format(len(which_boundaries), array.ndim)) if axis_order is None: axis_order = list(range(array.ndim)) elif len(axis_order) != array.ndim: raise ValueError('`axis_order` has length {}, expected {}' ''.format(len(axis_order), array.ndim)) if out is None: out = array.copy() else: out[:] = array # Self assignment is free, in case out is array # The 'only_once' functionality is implemented by storing for each axis # if the left and right boundaries have been processed. This information # is stored in a list of slices which is reused for the next axis in the # list. slices = [slice(None)] * array.ndim for ax, function, which in zip(axis_order, func, which_boundaries): if only_once: slc_l = list(slices) # Make a copy; copy() exists in Py3 only slc_r = list(slices) else: slc_l = [slice(None)] * array.ndim slc_r = [slice(None)] * array.ndim # slc_l and slc_r select left and right boundary, resp, in this axis. slc_l[ax] = 0 slc_r[ax] = -1 slc_l, slc_r = tuple(slc_l), tuple(slc_r) try: # Tuple of functions in this axis func_l, func_r = function except TypeError: # Single function func_l = func_r = function try: # Tuple of bool mod_left, mod_right = which except TypeError: # Single bool mod_left = mod_right = which if mod_left and func_l is not None: out[slc_l] = func_l(out[slc_l]) start = 1 else: start = None if mod_right and func_r is not None: out[slc_r] = func_r(out[slc_r]) end = -1 else: end = None # Write the information for the processed axis into the slice list. # Start and end include the boundary if it was processed. slices[ax] = slice(start, end) return out
python
def apply_on_boundary(array, func, only_once=True, which_boundaries=None, axis_order=None, out=None): array = np.asarray(array) if callable(func): func = [func] * array.ndim elif len(func) != array.ndim: raise ValueError('sequence of functions has length {}, expected {}' ''.format(len(func), array.ndim)) if which_boundaries is None: which_boundaries = ([(True, True)] * array.ndim) elif len(which_boundaries) != array.ndim: raise ValueError('`which_boundaries` has length {}, expected {}' ''.format(len(which_boundaries), array.ndim)) if axis_order is None: axis_order = list(range(array.ndim)) elif len(axis_order) != array.ndim: raise ValueError('`axis_order` has length {}, expected {}' ''.format(len(axis_order), array.ndim)) if out is None: out = array.copy() else: out[:] = array # Self assignment is free, in case out is array # The 'only_once' functionality is implemented by storing for each axis # if the left and right boundaries have been processed. This information # is stored in a list of slices which is reused for the next axis in the # list. slices = [slice(None)] * array.ndim for ax, function, which in zip(axis_order, func, which_boundaries): if only_once: slc_l = list(slices) # Make a copy; copy() exists in Py3 only slc_r = list(slices) else: slc_l = [slice(None)] * array.ndim slc_r = [slice(None)] * array.ndim # slc_l and slc_r select left and right boundary, resp, in this axis. slc_l[ax] = 0 slc_r[ax] = -1 slc_l, slc_r = tuple(slc_l), tuple(slc_r) try: # Tuple of functions in this axis func_l, func_r = function except TypeError: # Single function func_l = func_r = function try: # Tuple of bool mod_left, mod_right = which except TypeError: # Single bool mod_left = mod_right = which if mod_left and func_l is not None: out[slc_l] = func_l(out[slc_l]) start = 1 else: start = None if mod_right and func_r is not None: out[slc_r] = func_r(out[slc_r]) end = -1 else: end = None # Write the information for the processed axis into the slice list. # Start and end include the boundary if it was processed. slices[ax] = slice(start, end) return out
[ "def", "apply_on_boundary", "(", "array", ",", "func", ",", "only_once", "=", "True", ",", "which_boundaries", "=", "None", ",", "axis_order", "=", "None", ",", "out", "=", "None", ")", ":", "array", "=", "np", ".", "asarray", "(", "array", ")", "if", ...
Apply a function of the boundary of an n-dimensional array. All other values are preserved as-is. Parameters ---------- array : `array-like` Modify the boundary of this array func : callable or sequence of callables If a single function is given, assign ``array[slice] = func(array[slice])`` on the boundary slices, e.g. use ``lamda x: x / 2`` to divide values by 2. A sequence of functions is applied per axis separately. It must have length ``array.ndim`` and may consist of one function or a 2-tuple of functions per axis. ``None`` entries in a sequence cause the axis (side) to be skipped. only_once : bool, optional If ``True``, ensure that each boundary point appears in exactly one slice. If ``func`` is a list of functions, the ``axis_order`` determines which functions are applied to nodes which appear in multiple slices, according to the principle "first-come, first-served". which_boundaries : sequence, optional If provided, this sequence determines per axis whether to apply the function at the boundaries in each axis. The entry in each axis may consist in a single bool or a 2-tuple of bool. In the latter case, the first tuple entry decides for the left, the second for the right boundary. The length of the sequence must be ``array.ndim``. ``None`` is interpreted as "all boundaries". axis_order : sequence of ints, optional Permutation of ``range(array.ndim)`` defining the order in which to process the axes. If combined with ``only_once`` and a function list, this determines which function is evaluated in the points that are potentially processed multiple times. out : `numpy.ndarray`, optional Location in which to store the result, can be the same as ``array``. Default: copy of ``array`` Examples -------- >>> arr = np.ones((3, 3)) >>> apply_on_boundary(arr, lambda x: x / 2) array([[ 0.5, 0.5, 0.5], [ 0.5, 1. , 0.5], [ 0.5, 0.5, 0.5]]) If called with ``only_once=False``, the function is applied repeatedly: >>> apply_on_boundary(arr, lambda x: x / 2, only_once=False) array([[ 0.25, 0.5 , 0.25], [ 0.5 , 1. , 0.5 ], [ 0.25, 0.5 , 0.25]]) >>> apply_on_boundary(arr, lambda x: x / 2, only_once=True, ... which_boundaries=((True, False), True)) array([[ 0.5, 0.5, 0.5], [ 0.5, 1. , 0.5], [ 0.5, 1. , 0.5]]) Use the ``out`` parameter to store the result in an existing array: >>> out = np.empty_like(arr) >>> result = apply_on_boundary(arr, lambda x: x / 2, out=out) >>> result array([[ 0.5, 0.5, 0.5], [ 0.5, 1. , 0.5], [ 0.5, 0.5, 0.5]]) >>> result is out True
[ "Apply", "a", "function", "of", "the", "boundary", "of", "an", "n", "-", "dimensional", "array", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/numerics.py#L25-L173
231,548
odlgroup/odl
odl/util/numerics.py
fast_1d_tensor_mult
def fast_1d_tensor_mult(ndarr, onedim_arrs, axes=None, out=None): """Fast multiplication of an n-dim array with an outer product. This method implements the multiplication of an n-dimensional array with an outer product of one-dimensional arrays, e.g.:: a = np.ones((10, 10, 10)) x = np.random.rand(10) a *= x[:, None, None] * x[None, :, None] * x[None, None, :] Basically, there are two ways to do such an operation: 1. First calculate the factor on the right-hand side and do one "big" multiplication; or 2. Multiply by one factor at a time. The procedure of building up the large factor in the first method is relatively cheap if the number of 1d arrays is smaller than the number of dimensions. For exactly n vectors, the second method is faster, although it loops of the array ``a`` n times. This implementation combines the two ideas into a hybrid scheme: - If there are less 1d arrays than dimensions, choose 1. - Otherwise, calculate the factor array for n-1 arrays and multiply it to the large array. Finally, multiply with the last 1d array. The advantage of this approach is that it is memory-friendly and loops over the big array only twice. Parameters ---------- ndarr : `array-like` Array to multiply to onedim_arrs : sequence of `array-like`'s One-dimensional arrays to be multiplied with ``ndarr``. The sequence may not be longer than ``ndarr.ndim``. axes : sequence of ints, optional Take the 1d transform along these axes. ``None`` corresponds to the last ``len(onedim_arrs)`` axes, in ascending order. out : `numpy.ndarray`, optional Array in which the result is stored Returns ------- out : `numpy.ndarray` Result of the modification. If ``out`` was given, the returned object is a reference to it. """ if out is None: out = np.array(ndarr, copy=True) else: out[:] = ndarr # Self-assignment is free if out is ndarr if not onedim_arrs: raise ValueError('no 1d arrays given') if axes is None: axes = list(range(out.ndim - len(onedim_arrs), out.ndim)) axes_in = None elif len(axes) != len(onedim_arrs): raise ValueError('there are {} 1d arrays, but {} axes entries' ''.format(len(onedim_arrs), len(axes))) else: # Make axes positive axes, axes_in = np.array(axes, dtype=int), axes axes[axes < 0] += out.ndim axes = list(axes) if not all(0 <= ai < out.ndim for ai in axes): raise ValueError('`axes` {} out of bounds for {} dimensions' ''.format(axes_in, out.ndim)) # Make scalars 1d arrays and squeezable arrays 1d alist = [np.atleast_1d(np.asarray(a).squeeze()) for a in onedim_arrs] if any(a.ndim != 1 for a in alist): raise ValueError('only 1d arrays allowed') if len(axes) < out.ndim: # Make big factor array (start with 0d) factor = np.array(1.0) for ax, arr in zip(axes, alist): # Meshgrid-style slice slc = [None] * out.ndim slc[ax] = slice(None) factor = factor * arr[tuple(slc)] out *= factor else: # Hybrid approach # Get the axis to spare for the final multiplication, the one # with the largest stride. last_ax = np.argmax(out.strides) last_arr = alist[axes.index(last_ax)] # Build the semi-big array and multiply factor = np.array(1.0) for ax, arr in zip(axes, alist): if ax == last_ax: continue slc = [None] * out.ndim slc[ax] = slice(None) factor = factor * arr[tuple(slc)] out *= factor # Finally multiply by the remaining 1d array slc = [None] * out.ndim slc[last_ax] = slice(None) out *= last_arr[tuple(slc)] return out
python
def fast_1d_tensor_mult(ndarr, onedim_arrs, axes=None, out=None): if out is None: out = np.array(ndarr, copy=True) else: out[:] = ndarr # Self-assignment is free if out is ndarr if not onedim_arrs: raise ValueError('no 1d arrays given') if axes is None: axes = list(range(out.ndim - len(onedim_arrs), out.ndim)) axes_in = None elif len(axes) != len(onedim_arrs): raise ValueError('there are {} 1d arrays, but {} axes entries' ''.format(len(onedim_arrs), len(axes))) else: # Make axes positive axes, axes_in = np.array(axes, dtype=int), axes axes[axes < 0] += out.ndim axes = list(axes) if not all(0 <= ai < out.ndim for ai in axes): raise ValueError('`axes` {} out of bounds for {} dimensions' ''.format(axes_in, out.ndim)) # Make scalars 1d arrays and squeezable arrays 1d alist = [np.atleast_1d(np.asarray(a).squeeze()) for a in onedim_arrs] if any(a.ndim != 1 for a in alist): raise ValueError('only 1d arrays allowed') if len(axes) < out.ndim: # Make big factor array (start with 0d) factor = np.array(1.0) for ax, arr in zip(axes, alist): # Meshgrid-style slice slc = [None] * out.ndim slc[ax] = slice(None) factor = factor * arr[tuple(slc)] out *= factor else: # Hybrid approach # Get the axis to spare for the final multiplication, the one # with the largest stride. last_ax = np.argmax(out.strides) last_arr = alist[axes.index(last_ax)] # Build the semi-big array and multiply factor = np.array(1.0) for ax, arr in zip(axes, alist): if ax == last_ax: continue slc = [None] * out.ndim slc[ax] = slice(None) factor = factor * arr[tuple(slc)] out *= factor # Finally multiply by the remaining 1d array slc = [None] * out.ndim slc[last_ax] = slice(None) out *= last_arr[tuple(slc)] return out
[ "def", "fast_1d_tensor_mult", "(", "ndarr", ",", "onedim_arrs", ",", "axes", "=", "None", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "np", ".", "array", "(", "ndarr", ",", "copy", "=", "True", ")", "else", ":", ...
Fast multiplication of an n-dim array with an outer product. This method implements the multiplication of an n-dimensional array with an outer product of one-dimensional arrays, e.g.:: a = np.ones((10, 10, 10)) x = np.random.rand(10) a *= x[:, None, None] * x[None, :, None] * x[None, None, :] Basically, there are two ways to do such an operation: 1. First calculate the factor on the right-hand side and do one "big" multiplication; or 2. Multiply by one factor at a time. The procedure of building up the large factor in the first method is relatively cheap if the number of 1d arrays is smaller than the number of dimensions. For exactly n vectors, the second method is faster, although it loops of the array ``a`` n times. This implementation combines the two ideas into a hybrid scheme: - If there are less 1d arrays than dimensions, choose 1. - Otherwise, calculate the factor array for n-1 arrays and multiply it to the large array. Finally, multiply with the last 1d array. The advantage of this approach is that it is memory-friendly and loops over the big array only twice. Parameters ---------- ndarr : `array-like` Array to multiply to onedim_arrs : sequence of `array-like`'s One-dimensional arrays to be multiplied with ``ndarr``. The sequence may not be longer than ``ndarr.ndim``. axes : sequence of ints, optional Take the 1d transform along these axes. ``None`` corresponds to the last ``len(onedim_arrs)`` axes, in ascending order. out : `numpy.ndarray`, optional Array in which the result is stored Returns ------- out : `numpy.ndarray` Result of the modification. If ``out`` was given, the returned object is a reference to it.
[ "Fast", "multiplication", "of", "an", "n", "-", "dim", "array", "with", "an", "outer", "product", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/numerics.py#L176-L291
231,549
odlgroup/odl
odl/util/numerics.py
_intersection_slice_tuples
def _intersection_slice_tuples(lhs_arr, rhs_arr, offset): """Return tuples to yield the intersecting part of both given arrays. The returned slices ``lhs_slc`` and ``rhs_slc`` are such that ``lhs_arr[lhs_slc]`` and ``rhs_arr[rhs_slc]`` have the same shape. The ``offset`` parameter determines how much is skipped/added on the "left" side (small indices). """ lhs_slc, rhs_slc = [], [] for istart, n_lhs, n_rhs in zip(offset, lhs_arr.shape, rhs_arr.shape): # Slice for the inner part in the larger array corresponding to the # small one, offset by the given amount istop = istart + min(n_lhs, n_rhs) inner_slc = slice(istart, istop) if n_lhs > n_rhs: # Extension lhs_slc.append(inner_slc) rhs_slc.append(slice(None)) elif n_lhs < n_rhs: # Restriction lhs_slc.append(slice(None)) rhs_slc.append(inner_slc) else: # Same size, so full slices for both lhs_slc.append(slice(None)) rhs_slc.append(slice(None)) return tuple(lhs_slc), tuple(rhs_slc)
python
def _intersection_slice_tuples(lhs_arr, rhs_arr, offset): lhs_slc, rhs_slc = [], [] for istart, n_lhs, n_rhs in zip(offset, lhs_arr.shape, rhs_arr.shape): # Slice for the inner part in the larger array corresponding to the # small one, offset by the given amount istop = istart + min(n_lhs, n_rhs) inner_slc = slice(istart, istop) if n_lhs > n_rhs: # Extension lhs_slc.append(inner_slc) rhs_slc.append(slice(None)) elif n_lhs < n_rhs: # Restriction lhs_slc.append(slice(None)) rhs_slc.append(inner_slc) else: # Same size, so full slices for both lhs_slc.append(slice(None)) rhs_slc.append(slice(None)) return tuple(lhs_slc), tuple(rhs_slc)
[ "def", "_intersection_slice_tuples", "(", "lhs_arr", ",", "rhs_arr", ",", "offset", ")", ":", "lhs_slc", ",", "rhs_slc", "=", "[", "]", ",", "[", "]", "for", "istart", ",", "n_lhs", ",", "n_rhs", "in", "zip", "(", "offset", ",", "lhs_arr", ".", "shape"...
Return tuples to yield the intersecting part of both given arrays. The returned slices ``lhs_slc`` and ``rhs_slc`` are such that ``lhs_arr[lhs_slc]`` and ``rhs_arr[rhs_slc]`` have the same shape. The ``offset`` parameter determines how much is skipped/added on the "left" side (small indices).
[ "Return", "tuples", "to", "yield", "the", "intersecting", "part", "of", "both", "given", "arrays", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/numerics.py#L500-L529
231,550
odlgroup/odl
odl/util/numerics.py
_assign_intersection
def _assign_intersection(lhs_arr, rhs_arr, offset): """Assign the intersecting region from ``rhs_arr`` to ``lhs_arr``.""" lhs_slc, rhs_slc = _intersection_slice_tuples(lhs_arr, rhs_arr, offset) lhs_arr[lhs_slc] = rhs_arr[rhs_slc]
python
def _assign_intersection(lhs_arr, rhs_arr, offset): lhs_slc, rhs_slc = _intersection_slice_tuples(lhs_arr, rhs_arr, offset) lhs_arr[lhs_slc] = rhs_arr[rhs_slc]
[ "def", "_assign_intersection", "(", "lhs_arr", ",", "rhs_arr", ",", "offset", ")", ":", "lhs_slc", ",", "rhs_slc", "=", "_intersection_slice_tuples", "(", "lhs_arr", ",", "rhs_arr", ",", "offset", ")", "lhs_arr", "[", "lhs_slc", "]", "=", "rhs_arr", "[", "rh...
Assign the intersecting region from ``rhs_arr`` to ``lhs_arr``.
[ "Assign", "the", "intersecting", "region", "from", "rhs_arr", "to", "lhs_arr", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/numerics.py#L532-L535
231,551
odlgroup/odl
odl/util/numerics.py
_padding_slices_outer
def _padding_slices_outer(lhs_arr, rhs_arr, axis, offset): """Return slices into the outer array part where padding is applied. When padding is performed, these slices yield the outer (excess) part of the larger array that is to be filled with values. Slices for both sides of the arrays in a given ``axis`` are returned. The same slices are used also in the adjoint padding correction, however in a different way. See `the online documentation <https://odlgroup.github.io/odl/math/resizing_ops.html>`_ on resizing operators for details. """ istart_inner = offset[axis] istop_inner = istart_inner + min(lhs_arr.shape[axis], rhs_arr.shape[axis]) return slice(istart_inner), slice(istop_inner, None)
python
def _padding_slices_outer(lhs_arr, rhs_arr, axis, offset): istart_inner = offset[axis] istop_inner = istart_inner + min(lhs_arr.shape[axis], rhs_arr.shape[axis]) return slice(istart_inner), slice(istop_inner, None)
[ "def", "_padding_slices_outer", "(", "lhs_arr", ",", "rhs_arr", ",", "axis", ",", "offset", ")", ":", "istart_inner", "=", "offset", "[", "axis", "]", "istop_inner", "=", "istart_inner", "+", "min", "(", "lhs_arr", ".", "shape", "[", "axis", "]", ",", "r...
Return slices into the outer array part where padding is applied. When padding is performed, these slices yield the outer (excess) part of the larger array that is to be filled with values. Slices for both sides of the arrays in a given ``axis`` are returned. The same slices are used also in the adjoint padding correction, however in a different way. See `the online documentation <https://odlgroup.github.io/odl/math/resizing_ops.html>`_ on resizing operators for details.
[ "Return", "slices", "into", "the", "outer", "array", "part", "where", "padding", "is", "applied", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/numerics.py#L538-L554
231,552
odlgroup/odl
odl/util/numerics.py
_padding_slices_inner
def _padding_slices_inner(lhs_arr, rhs_arr, axis, offset, pad_mode): """Return slices into the inner array part for a given ``pad_mode``. When performing padding, these slices yield the values from the inner part of a larger array that are to be assigned to the excess part of the same array. Slices for both sides ("left", "right") of the arrays in a given ``axis`` are returned. """ # Calculate the start and stop indices for the inner part istart_inner = offset[axis] n_large = max(lhs_arr.shape[axis], rhs_arr.shape[axis]) n_small = min(lhs_arr.shape[axis], rhs_arr.shape[axis]) istop_inner = istart_inner + n_small # Number of values padded to left and right n_pad_l = istart_inner n_pad_r = n_large - istop_inner if pad_mode == 'periodic': # left: n_pad_l forward, ending at istop_inner - 1 pad_slc_l = slice(istop_inner - n_pad_l, istop_inner) # right: n_pad_r forward, starting at istart_inner pad_slc_r = slice(istart_inner, istart_inner + n_pad_r) elif pad_mode == 'symmetric': # left: n_pad_l backward, ending at istart_inner + 1 pad_slc_l = slice(istart_inner + n_pad_l, istart_inner, -1) # right: n_pad_r backward, starting at istop_inner - 2 # For the corner case that the stopping index is -1, we need to # replace it with None, since -1 as stopping index is equivalent # to the last index, which is not what we want (0 as last index). istop_r = istop_inner - 2 - n_pad_r if istop_r == -1: istop_r = None pad_slc_r = slice(istop_inner - 2, istop_r, -1) elif pad_mode in ('order0', 'order1'): # left: only the first entry, using a slice to avoid squeezing pad_slc_l = slice(istart_inner, istart_inner + 1) # right: only last entry pad_slc_r = slice(istop_inner - 1, istop_inner) else: # Slices are not used, returning trivial ones. The function should not # be used for other modes anyway. pad_slc_l, pad_slc_r = slice(0), slice(0) return pad_slc_l, pad_slc_r
python
def _padding_slices_inner(lhs_arr, rhs_arr, axis, offset, pad_mode): # Calculate the start and stop indices for the inner part istart_inner = offset[axis] n_large = max(lhs_arr.shape[axis], rhs_arr.shape[axis]) n_small = min(lhs_arr.shape[axis], rhs_arr.shape[axis]) istop_inner = istart_inner + n_small # Number of values padded to left and right n_pad_l = istart_inner n_pad_r = n_large - istop_inner if pad_mode == 'periodic': # left: n_pad_l forward, ending at istop_inner - 1 pad_slc_l = slice(istop_inner - n_pad_l, istop_inner) # right: n_pad_r forward, starting at istart_inner pad_slc_r = slice(istart_inner, istart_inner + n_pad_r) elif pad_mode == 'symmetric': # left: n_pad_l backward, ending at istart_inner + 1 pad_slc_l = slice(istart_inner + n_pad_l, istart_inner, -1) # right: n_pad_r backward, starting at istop_inner - 2 # For the corner case that the stopping index is -1, we need to # replace it with None, since -1 as stopping index is equivalent # to the last index, which is not what we want (0 as last index). istop_r = istop_inner - 2 - n_pad_r if istop_r == -1: istop_r = None pad_slc_r = slice(istop_inner - 2, istop_r, -1) elif pad_mode in ('order0', 'order1'): # left: only the first entry, using a slice to avoid squeezing pad_slc_l = slice(istart_inner, istart_inner + 1) # right: only last entry pad_slc_r = slice(istop_inner - 1, istop_inner) else: # Slices are not used, returning trivial ones. The function should not # be used for other modes anyway. pad_slc_l, pad_slc_r = slice(0), slice(0) return pad_slc_l, pad_slc_r
[ "def", "_padding_slices_inner", "(", "lhs_arr", ",", "rhs_arr", ",", "axis", ",", "offset", ",", "pad_mode", ")", ":", "# Calculate the start and stop indices for the inner part", "istart_inner", "=", "offset", "[", "axis", "]", "n_large", "=", "max", "(", "lhs_arr"...
Return slices into the inner array part for a given ``pad_mode``. When performing padding, these slices yield the values from the inner part of a larger array that are to be assigned to the excess part of the same array. Slices for both sides ("left", "right") of the arrays in a given ``axis`` are returned.
[ "Return", "slices", "into", "the", "inner", "array", "part", "for", "a", "given", "pad_mode", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/numerics.py#L557-L603
231,553
odlgroup/odl
odl/util/numerics.py
zscore
def zscore(arr): """Return arr normalized with mean 0 and unit variance. If the input has 0 variance, the result will also have 0 variance. Parameters ---------- arr : array-like Returns ------- zscore : array-like Examples -------- Compute the z score for a small array: >>> result = zscore([1, 0]) >>> result array([ 1., -1.]) >>> np.mean(result) 0.0 >>> np.std(result) 1.0 Does not re-scale in case the input is constant (has 0 variance): >>> zscore([1, 1]) array([ 0., 0.]) """ arr = arr - np.mean(arr) std = np.std(arr) if std != 0: arr /= std return arr
python
def zscore(arr): arr = arr - np.mean(arr) std = np.std(arr) if std != 0: arr /= std return arr
[ "def", "zscore", "(", "arr", ")", ":", "arr", "=", "arr", "-", "np", ".", "mean", "(", "arr", ")", "std", "=", "np", ".", "std", "(", "arr", ")", "if", "std", "!=", "0", ":", "arr", "/=", "std", "return", "arr" ]
Return arr normalized with mean 0 and unit variance. If the input has 0 variance, the result will also have 0 variance. Parameters ---------- arr : array-like Returns ------- zscore : array-like Examples -------- Compute the z score for a small array: >>> result = zscore([1, 0]) >>> result array([ 1., -1.]) >>> np.mean(result) 0.0 >>> np.std(result) 1.0 Does not re-scale in case the input is constant (has 0 variance): >>> zscore([1, 1]) array([ 0., 0.])
[ "Return", "arr", "normalized", "with", "mean", "0", "and", "unit", "variance", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/numerics.py#L813-L847
231,554
odlgroup/odl
odl/space/fspace.py
FunctionSpace.real_out_dtype
def real_out_dtype(self): """The real dtype corresponding to this space's `out_dtype`.""" if self.__real_out_dtype is None: raise AttributeError( 'no real variant of output dtype {} defined' ''.format(dtype_repr(self.scalar_out_dtype))) else: return self.__real_out_dtype
python
def real_out_dtype(self): if self.__real_out_dtype is None: raise AttributeError( 'no real variant of output dtype {} defined' ''.format(dtype_repr(self.scalar_out_dtype))) else: return self.__real_out_dtype
[ "def", "real_out_dtype", "(", "self", ")", ":", "if", "self", ".", "__real_out_dtype", "is", "None", ":", "raise", "AttributeError", "(", "'no real variant of output dtype {} defined'", "''", ".", "format", "(", "dtype_repr", "(", "self", ".", "scalar_out_dtype", ...
The real dtype corresponding to this space's `out_dtype`.
[ "The", "real", "dtype", "corresponding", "to", "this", "space", "s", "out_dtype", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L278-L285
231,555
odlgroup/odl
odl/space/fspace.py
FunctionSpace.complex_out_dtype
def complex_out_dtype(self): """The complex dtype corresponding to this space's `out_dtype`.""" if self.__complex_out_dtype is None: raise AttributeError( 'no complex variant of output dtype {} defined' ''.format(dtype_repr(self.scalar_out_dtype))) else: return self.__complex_out_dtype
python
def complex_out_dtype(self): if self.__complex_out_dtype is None: raise AttributeError( 'no complex variant of output dtype {} defined' ''.format(dtype_repr(self.scalar_out_dtype))) else: return self.__complex_out_dtype
[ "def", "complex_out_dtype", "(", "self", ")", ":", "if", "self", ".", "__complex_out_dtype", "is", "None", ":", "raise", "AttributeError", "(", "'no complex variant of output dtype {} defined'", "''", ".", "format", "(", "dtype_repr", "(", "self", ".", "scalar_out_d...
The complex dtype corresponding to this space's `out_dtype`.
[ "The", "complex", "dtype", "corresponding", "to", "this", "space", "s", "out_dtype", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L288-L295
231,556
odlgroup/odl
odl/space/fspace.py
FunctionSpace.zero
def zero(self): """Function mapping anything to zero.""" # Since `FunctionSpace.lincomb` may be slow, we implement this # function directly. # The unused **kwargs are needed to support combination with # functions that take parameters. def zero_vec(x, out=None, **kwargs): """Zero function, vectorized.""" if is_valid_input_meshgrid(x, self.domain.ndim): scalar_out_shape = out_shape_from_meshgrid(x) elif is_valid_input_array(x, self.domain.ndim): scalar_out_shape = out_shape_from_array(x) else: raise TypeError('invalid input type') # For tensor-valued functions out_shape = self.out_shape + scalar_out_shape if out is None: return np.zeros(out_shape, dtype=self.scalar_out_dtype) else: # Need to go through an array to fill with the correct # zero value for all dtypes fill_value = np.zeros(1, dtype=self.scalar_out_dtype)[0] out.fill(fill_value) return self.element_type(self, zero_vec)
python
def zero(self): # Since `FunctionSpace.lincomb` may be slow, we implement this # function directly. # The unused **kwargs are needed to support combination with # functions that take parameters. def zero_vec(x, out=None, **kwargs): """Zero function, vectorized.""" if is_valid_input_meshgrid(x, self.domain.ndim): scalar_out_shape = out_shape_from_meshgrid(x) elif is_valid_input_array(x, self.domain.ndim): scalar_out_shape = out_shape_from_array(x) else: raise TypeError('invalid input type') # For tensor-valued functions out_shape = self.out_shape + scalar_out_shape if out is None: return np.zeros(out_shape, dtype=self.scalar_out_dtype) else: # Need to go through an array to fill with the correct # zero value for all dtypes fill_value = np.zeros(1, dtype=self.scalar_out_dtype)[0] out.fill(fill_value) return self.element_type(self, zero_vec)
[ "def", "zero", "(", "self", ")", ":", "# Since `FunctionSpace.lincomb` may be slow, we implement this", "# function directly.", "# The unused **kwargs are needed to support combination with", "# functions that take parameters.", "def", "zero_vec", "(", "x", ",", "out", "=", "None",...
Function mapping anything to zero.
[ "Function", "mapping", "anything", "to", "zero", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L610-L636
231,557
odlgroup/odl
odl/space/fspace.py
FunctionSpace.one
def one(self): """Function mapping anything to one.""" # See zero() for remarks def one_vec(x, out=None, **kwargs): """One function, vectorized.""" if is_valid_input_meshgrid(x, self.domain.ndim): scalar_out_shape = out_shape_from_meshgrid(x) elif is_valid_input_array(x, self.domain.ndim): scalar_out_shape = out_shape_from_array(x) else: raise TypeError('invalid input type') out_shape = self.out_shape + scalar_out_shape if out is None: return np.ones(out_shape, dtype=self.scalar_out_dtype) else: fill_value = np.ones(1, dtype=self.scalar_out_dtype)[0] out.fill(fill_value) return self.element_type(self, one_vec)
python
def one(self): # See zero() for remarks def one_vec(x, out=None, **kwargs): """One function, vectorized.""" if is_valid_input_meshgrid(x, self.domain.ndim): scalar_out_shape = out_shape_from_meshgrid(x) elif is_valid_input_array(x, self.domain.ndim): scalar_out_shape = out_shape_from_array(x) else: raise TypeError('invalid input type') out_shape = self.out_shape + scalar_out_shape if out is None: return np.ones(out_shape, dtype=self.scalar_out_dtype) else: fill_value = np.ones(1, dtype=self.scalar_out_dtype)[0] out.fill(fill_value) return self.element_type(self, one_vec)
[ "def", "one", "(", "self", ")", ":", "# See zero() for remarks", "def", "one_vec", "(", "x", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "\"\"\"One function, vectorized.\"\"\"", "if", "is_valid_input_meshgrid", "(", "x", ",", "self", ".", "do...
Function mapping anything to one.
[ "Function", "mapping", "anything", "to", "one", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L638-L658
231,558
odlgroup/odl
odl/space/fspace.py
FunctionSpace.astype
def astype(self, out_dtype): """Return a copy of this space with new ``out_dtype``. Parameters ---------- out_dtype : Output data type of the returned space. Can be given in any way `numpy.dtype` understands, e.g. as string (``'complex64'``) or built-in type (``complex``). ``None`` is interpreted as ``'float64'``. Returns ------- newspace : `FunctionSpace` The version of this space with given data type """ out_dtype = np.dtype(out_dtype) if out_dtype == self.out_dtype: return self # Try to use caching for real and complex versions (exact dtype # mappings). This may fail for certain dtype, in which case we # just go to `_astype` directly. real_dtype = getattr(self, 'real_out_dtype', None) if real_dtype is None: return self._astype(out_dtype) else: if out_dtype == real_dtype: if self.__real_space is None: self.__real_space = self._astype(out_dtype) return self.__real_space elif out_dtype == self.complex_out_dtype: if self.__complex_space is None: self.__complex_space = self._astype(out_dtype) return self.__complex_space else: return self._astype(out_dtype)
python
def astype(self, out_dtype): out_dtype = np.dtype(out_dtype) if out_dtype == self.out_dtype: return self # Try to use caching for real and complex versions (exact dtype # mappings). This may fail for certain dtype, in which case we # just go to `_astype` directly. real_dtype = getattr(self, 'real_out_dtype', None) if real_dtype is None: return self._astype(out_dtype) else: if out_dtype == real_dtype: if self.__real_space is None: self.__real_space = self._astype(out_dtype) return self.__real_space elif out_dtype == self.complex_out_dtype: if self.__complex_space is None: self.__complex_space = self._astype(out_dtype) return self.__complex_space else: return self._astype(out_dtype)
[ "def", "astype", "(", "self", ",", "out_dtype", ")", ":", "out_dtype", "=", "np", ".", "dtype", "(", "out_dtype", ")", "if", "out_dtype", "==", "self", ".", "out_dtype", ":", "return", "self", "# Try to use caching for real and complex versions (exact dtype", "# m...
Return a copy of this space with new ``out_dtype``. Parameters ---------- out_dtype : Output data type of the returned space. Can be given in any way `numpy.dtype` understands, e.g. as string (``'complex64'``) or built-in type (``complex``). ``None`` is interpreted as ``'float64'``. Returns ------- newspace : `FunctionSpace` The version of this space with given data type
[ "Return", "a", "copy", "of", "this", "space", "with", "new", "out_dtype", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L698-L734
231,559
odlgroup/odl
odl/space/fspace.py
FunctionSpace._lincomb
def _lincomb(self, a, f1, b, f2, out): """Linear combination of ``f1`` and ``f2``. Notes ----- The additions and multiplications are implemented via simple Python functions, so non-vectorized versions are slow. """ # Avoid infinite recursions by making a copy of the functions f1_copy = f1.copy() f2_copy = f2.copy() def lincomb_oop(x, **kwargs): """Linear combination, out-of-place version.""" # Not optimized since that raises issues with alignment # of input and partial results out = a * np.asarray(f1_copy(x, **kwargs), dtype=self.scalar_out_dtype) tmp = b * np.asarray(f2_copy(x, **kwargs), dtype=self.scalar_out_dtype) out += tmp return out out._call_out_of_place = lincomb_oop decorator = preload_first_arg(out, 'in-place') out._call_in_place = decorator(_default_in_place) out._call_has_out = out._call_out_optional = False return out
python
def _lincomb(self, a, f1, b, f2, out): # Avoid infinite recursions by making a copy of the functions f1_copy = f1.copy() f2_copy = f2.copy() def lincomb_oop(x, **kwargs): """Linear combination, out-of-place version.""" # Not optimized since that raises issues with alignment # of input and partial results out = a * np.asarray(f1_copy(x, **kwargs), dtype=self.scalar_out_dtype) tmp = b * np.asarray(f2_copy(x, **kwargs), dtype=self.scalar_out_dtype) out += tmp return out out._call_out_of_place = lincomb_oop decorator = preload_first_arg(out, 'in-place') out._call_in_place = decorator(_default_in_place) out._call_has_out = out._call_out_optional = False return out
[ "def", "_lincomb", "(", "self", ",", "a", ",", "f1", ",", "b", ",", "f2", ",", "out", ")", ":", "# Avoid infinite recursions by making a copy of the functions", "f1_copy", "=", "f1", ".", "copy", "(", ")", "f2_copy", "=", "f2", ".", "copy", "(", ")", "de...
Linear combination of ``f1`` and ``f2``. Notes ----- The additions and multiplications are implemented via simple Python functions, so non-vectorized versions are slow.
[ "Linear", "combination", "of", "f1", "and", "f2", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L736-L763
231,560
odlgroup/odl
odl/space/fspace.py
FunctionSpace._multiply
def _multiply(self, f1, f2, out): """Pointwise multiplication of ``f1`` and ``f2``. Notes ----- The multiplication is implemented with a simple Python function, so the non-vectorized versions are slow. """ # Avoid infinite recursions by making a copy of the functions f1_copy = f1.copy() f2_copy = f2.copy() def product_oop(x, **kwargs): """Product out-of-place evaluation function.""" return np.asarray(f1_copy(x, **kwargs) * f2_copy(x, **kwargs), dtype=self.scalar_out_dtype) out._call_out_of_place = product_oop decorator = preload_first_arg(out, 'in-place') out._call_in_place = decorator(_default_in_place) out._call_has_out = out._call_out_optional = False return out
python
def _multiply(self, f1, f2, out): # Avoid infinite recursions by making a copy of the functions f1_copy = f1.copy() f2_copy = f2.copy() def product_oop(x, **kwargs): """Product out-of-place evaluation function.""" return np.asarray(f1_copy(x, **kwargs) * f2_copy(x, **kwargs), dtype=self.scalar_out_dtype) out._call_out_of_place = product_oop decorator = preload_first_arg(out, 'in-place') out._call_in_place = decorator(_default_in_place) out._call_has_out = out._call_out_optional = False return out
[ "def", "_multiply", "(", "self", ",", "f1", ",", "f2", ",", "out", ")", ":", "# Avoid infinite recursions by making a copy of the functions", "f1_copy", "=", "f1", ".", "copy", "(", ")", "f2_copy", "=", "f2", ".", "copy", "(", ")", "def", "product_oop", "(",...
Pointwise multiplication of ``f1`` and ``f2``. Notes ----- The multiplication is implemented with a simple Python function, so the non-vectorized versions are slow.
[ "Pointwise", "multiplication", "of", "f1", "and", "f2", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L765-L786
231,561
odlgroup/odl
odl/space/fspace.py
FunctionSpace._scalar_power
def _scalar_power(self, f, p, out): """Compute ``p``-th power of ``f`` for ``p`` scalar.""" # Avoid infinite recursions by making a copy of the function f_copy = f.copy() def pow_posint(x, n): """Power function for positive integer ``n``, out-of-place.""" if isinstance(x, np.ndarray): y = x.copy() return ipow_posint(y, n) else: return x ** n def ipow_posint(x, n): """Power function for positive integer ``n``, in-place.""" if n == 1: return x elif n % 2 == 0: x *= x return ipow_posint(x, n // 2) else: tmp = x.copy() x *= x ipow_posint(x, n // 2) x *= tmp return x def power_oop(x, **kwargs): """Power out-of-place evaluation function.""" if p == 0: return self.one() elif p == int(p) and p >= 1: return np.asarray(pow_posint(f_copy(x, **kwargs), int(p)), dtype=self.scalar_out_dtype) else: result = np.power(f_copy(x, **kwargs), p) return result.astype(self.scalar_out_dtype) out._call_out_of_place = power_oop decorator = preload_first_arg(out, 'in-place') out._call_in_place = decorator(_default_in_place) out._call_has_out = out._call_out_optional = False return out
python
def _scalar_power(self, f, p, out): # Avoid infinite recursions by making a copy of the function f_copy = f.copy() def pow_posint(x, n): """Power function for positive integer ``n``, out-of-place.""" if isinstance(x, np.ndarray): y = x.copy() return ipow_posint(y, n) else: return x ** n def ipow_posint(x, n): """Power function for positive integer ``n``, in-place.""" if n == 1: return x elif n % 2 == 0: x *= x return ipow_posint(x, n // 2) else: tmp = x.copy() x *= x ipow_posint(x, n // 2) x *= tmp return x def power_oop(x, **kwargs): """Power out-of-place evaluation function.""" if p == 0: return self.one() elif p == int(p) and p >= 1: return np.asarray(pow_posint(f_copy(x, **kwargs), int(p)), dtype=self.scalar_out_dtype) else: result = np.power(f_copy(x, **kwargs), p) return result.astype(self.scalar_out_dtype) out._call_out_of_place = power_oop decorator = preload_first_arg(out, 'in-place') out._call_in_place = decorator(_default_in_place) out._call_has_out = out._call_out_optional = False return out
[ "def", "_scalar_power", "(", "self", ",", "f", ",", "p", ",", "out", ")", ":", "# Avoid infinite recursions by making a copy of the function", "f_copy", "=", "f", ".", "copy", "(", ")", "def", "pow_posint", "(", "x", ",", "n", ")", ":", "\"\"\"Power function f...
Compute ``p``-th power of ``f`` for ``p`` scalar.
[ "Compute", "p", "-", "th", "power", "of", "f", "for", "p", "scalar", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L811-L853
231,562
odlgroup/odl
odl/space/fspace.py
FunctionSpace._realpart
def _realpart(self, f): """Function returning the real part of the result from ``f``.""" def f_re(x, **kwargs): result = np.asarray(f(x, **kwargs), dtype=self.scalar_out_dtype) return result.real if is_real_dtype(self.out_dtype): return f else: return self.real_space.element(f_re)
python
def _realpart(self, f): def f_re(x, **kwargs): result = np.asarray(f(x, **kwargs), dtype=self.scalar_out_dtype) return result.real if is_real_dtype(self.out_dtype): return f else: return self.real_space.element(f_re)
[ "def", "_realpart", "(", "self", ",", "f", ")", ":", "def", "f_re", "(", "x", ",", "*", "*", "kwargs", ")", ":", "result", "=", "np", ".", "asarray", "(", "f", "(", "x", ",", "*", "*", "kwargs", ")", ",", "dtype", "=", "self", ".", "scalar_ou...
Function returning the real part of the result from ``f``.
[ "Function", "returning", "the", "real", "part", "of", "the", "result", "from", "f", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L855-L865
231,563
odlgroup/odl
odl/space/fspace.py
FunctionSpace._imagpart
def _imagpart(self, f): """Function returning the imaginary part of the result from ``f``.""" def f_im(x, **kwargs): result = np.asarray(f(x, **kwargs), dtype=self.scalar_out_dtype) return result.imag if is_real_dtype(self.out_dtype): return self.zero() else: return self.real_space.element(f_im)
python
def _imagpart(self, f): def f_im(x, **kwargs): result = np.asarray(f(x, **kwargs), dtype=self.scalar_out_dtype) return result.imag if is_real_dtype(self.out_dtype): return self.zero() else: return self.real_space.element(f_im)
[ "def", "_imagpart", "(", "self", ",", "f", ")", ":", "def", "f_im", "(", "x", ",", "*", "*", "kwargs", ")", ":", "result", "=", "np", ".", "asarray", "(", "f", "(", "x", ",", "*", "*", "kwargs", ")", ",", "dtype", "=", "self", ".", "scalar_ou...
Function returning the imaginary part of the result from ``f``.
[ "Function", "returning", "the", "imaginary", "part", "of", "the", "result", "from", "f", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L867-L877
231,564
odlgroup/odl
odl/space/fspace.py
FunctionSpace._conj
def _conj(self, f): """Function returning the complex conjugate of a result.""" def f_conj(x, **kwargs): result = np.asarray(f(x, **kwargs), dtype=self.scalar_out_dtype) return result.conj() if is_real_dtype(self.out_dtype): return f else: return self.element(f_conj)
python
def _conj(self, f): def f_conj(x, **kwargs): result = np.asarray(f(x, **kwargs), dtype=self.scalar_out_dtype) return result.conj() if is_real_dtype(self.out_dtype): return f else: return self.element(f_conj)
[ "def", "_conj", "(", "self", ",", "f", ")", ":", "def", "f_conj", "(", "x", ",", "*", "*", "kwargs", ")", ":", "result", "=", "np", ".", "asarray", "(", "f", "(", "x", ",", "*", "*", "kwargs", ")", ",", "dtype", "=", "self", ".", "scalar_out_...
Function returning the complex conjugate of a result.
[ "Function", "returning", "the", "complex", "conjugate", "of", "a", "result", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L879-L889
231,565
odlgroup/odl
odl/space/fspace.py
FunctionSpace.byaxis_out
def byaxis_out(self): """Object to index along output dimensions. This is only valid for non-trivial `out_shape`. Examples -------- Indexing with integers or slices: >>> domain = odl.IntervalProd(0, 1) >>> fspace = odl.FunctionSpace(domain, out_dtype=(float, (2, 3, 4))) >>> fspace.byaxis_out[0] FunctionSpace(IntervalProd(0.0, 1.0), out_dtype=('float64', (2,))) >>> fspace.byaxis_out[1] FunctionSpace(IntervalProd(0.0, 1.0), out_dtype=('float64', (3,))) >>> fspace.byaxis_out[1:] FunctionSpace(IntervalProd(0.0, 1.0), out_dtype=('float64', (3, 4))) Lists can be used to stack spaces arbitrarily: >>> fspace.byaxis_out[[2, 1, 2]] FunctionSpace(IntervalProd(0.0, 1.0), out_dtype=('float64', (4, 3, 4))) """ space = self class FspaceByaxisOut(object): """Helper class for indexing by output axes.""" def __getitem__(self, indices): """Return ``self[indices]``. Parameters ---------- indices : index expression Object used to index the output components. Returns ------- space : `FunctionSpace` The resulting space with same domain and scalar output data type, but indexed output components. Raises ------ IndexError If this is a space of scalar-valued functions. """ try: iter(indices) except TypeError: newshape = space.out_shape[indices] else: newshape = tuple(space.out_shape[int(i)] for i in indices) dtype = (space.scalar_out_dtype, newshape) return FunctionSpace(space.domain, out_dtype=dtype) def __repr__(self): """Return ``repr(self)``.""" return repr(space) + '.byaxis_out' return FspaceByaxisOut()
python
def byaxis_out(self): space = self class FspaceByaxisOut(object): """Helper class for indexing by output axes.""" def __getitem__(self, indices): """Return ``self[indices]``. Parameters ---------- indices : index expression Object used to index the output components. Returns ------- space : `FunctionSpace` The resulting space with same domain and scalar output data type, but indexed output components. Raises ------ IndexError If this is a space of scalar-valued functions. """ try: iter(indices) except TypeError: newshape = space.out_shape[indices] else: newshape = tuple(space.out_shape[int(i)] for i in indices) dtype = (space.scalar_out_dtype, newshape) return FunctionSpace(space.domain, out_dtype=dtype) def __repr__(self): """Return ``repr(self)``.""" return repr(space) + '.byaxis_out' return FspaceByaxisOut()
[ "def", "byaxis_out", "(", "self", ")", ":", "space", "=", "self", "class", "FspaceByaxisOut", "(", "object", ")", ":", "\"\"\"Helper class for indexing by output axes.\"\"\"", "def", "__getitem__", "(", "self", ",", "indices", ")", ":", "\"\"\"Return ``self[indices]``...
Object to index along output dimensions. This is only valid for non-trivial `out_shape`. Examples -------- Indexing with integers or slices: >>> domain = odl.IntervalProd(0, 1) >>> fspace = odl.FunctionSpace(domain, out_dtype=(float, (2, 3, 4))) >>> fspace.byaxis_out[0] FunctionSpace(IntervalProd(0.0, 1.0), out_dtype=('float64', (2,))) >>> fspace.byaxis_out[1] FunctionSpace(IntervalProd(0.0, 1.0), out_dtype=('float64', (3,))) >>> fspace.byaxis_out[1:] FunctionSpace(IntervalProd(0.0, 1.0), out_dtype=('float64', (3, 4))) Lists can be used to stack spaces arbitrarily: >>> fspace.byaxis_out[[2, 1, 2]] FunctionSpace(IntervalProd(0.0, 1.0), out_dtype=('float64', (4, 3, 4)))
[ "Object", "to", "index", "along", "output", "dimensions", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L892-L954
231,566
odlgroup/odl
odl/space/fspace.py
FunctionSpace.byaxis_in
def byaxis_in(self): """Object to index ``self`` along input dimensions. Examples -------- Indexing with integers or slices: >>> domain = odl.IntervalProd([0, 0, 0], [1, 2, 3]) >>> fspace = odl.FunctionSpace(domain) >>> fspace.byaxis_in[0] FunctionSpace(IntervalProd(0.0, 1.0)) >>> fspace.byaxis_in[1] FunctionSpace(IntervalProd(0.0, 2.0)) >>> fspace.byaxis_in[1:] FunctionSpace(IntervalProd([ 0., 0.], [ 2., 3.])) Lists can be used to stack spaces arbitrarily: >>> fspace.byaxis_in[[2, 1, 2]] FunctionSpace(IntervalProd([ 0., 0., 0.], [ 3., 2., 3.])) """ space = self class FspaceByaxisIn(object): """Helper class for indexing by input axes.""" def __getitem__(self, indices): """Return ``self[indices]``. Parameters ---------- indices : index expression Object used to index the space domain. Returns ------- space : `FunctionSpace` The resulting space with same output data type, but indexed domain. """ domain = space.domain[indices] return FunctionSpace(domain, out_dtype=space.out_dtype) def __repr__(self): """Return ``repr(self)``.""" return repr(space) + '.byaxis_in' return FspaceByaxisIn()
python
def byaxis_in(self): space = self class FspaceByaxisIn(object): """Helper class for indexing by input axes.""" def __getitem__(self, indices): """Return ``self[indices]``. Parameters ---------- indices : index expression Object used to index the space domain. Returns ------- space : `FunctionSpace` The resulting space with same output data type, but indexed domain. """ domain = space.domain[indices] return FunctionSpace(domain, out_dtype=space.out_dtype) def __repr__(self): """Return ``repr(self)``.""" return repr(space) + '.byaxis_in' return FspaceByaxisIn()
[ "def", "byaxis_in", "(", "self", ")", ":", "space", "=", "self", "class", "FspaceByaxisIn", "(", "object", ")", ":", "\"\"\"Helper class for indexing by input axes.\"\"\"", "def", "__getitem__", "(", "self", ",", "indices", ")", ":", "\"\"\"Return ``self[indices]``.\n...
Object to index ``self`` along input dimensions. Examples -------- Indexing with integers or slices: >>> domain = odl.IntervalProd([0, 0, 0], [1, 2, 3]) >>> fspace = odl.FunctionSpace(domain) >>> fspace.byaxis_in[0] FunctionSpace(IntervalProd(0.0, 1.0)) >>> fspace.byaxis_in[1] FunctionSpace(IntervalProd(0.0, 2.0)) >>> fspace.byaxis_in[1:] FunctionSpace(IntervalProd([ 0., 0.], [ 2., 3.])) Lists can be used to stack spaces arbitrarily: >>> fspace.byaxis_in[[2, 1, 2]] FunctionSpace(IntervalProd([ 0., 0., 0.], [ 3., 2., 3.]))
[ "Object", "to", "index", "self", "along", "input", "dimensions", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L957-L1005
231,567
odlgroup/odl
odl/space/fspace.py
FunctionSpaceElement._call
def _call(self, x, out=None, **kwargs): """Raw evaluation method.""" if out is None: return self._call_out_of_place(x, **kwargs) else: self._call_in_place(x, out=out, **kwargs)
python
def _call(self, x, out=None, **kwargs): if out is None: return self._call_out_of_place(x, **kwargs) else: self._call_in_place(x, out=out, **kwargs)
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "out", "is", "None", ":", "return", "self", ".", "_call_out_of_place", "(", "x", ",", "*", "*", "kwargs", ")", "else", ":", "self", ".", "_...
Raw evaluation method.
[ "Raw", "evaluation", "method", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L1167-L1172
231,568
odlgroup/odl
odl/space/fspace.py
FunctionSpaceElement.assign
def assign(self, other): """Assign ``other`` to ``self``. This is implemented without `FunctionSpace.lincomb` to ensure that ``self == other`` evaluates to True after ``self.assign(other)``. """ if other not in self.space: raise TypeError('`other` {!r} is not an element of the space ' '{} of this function' ''.format(other, self.space)) self._call_in_place = other._call_in_place self._call_out_of_place = other._call_out_of_place self._call_has_out = other._call_has_out self._call_out_optional = other._call_out_optional
python
def assign(self, other): if other not in self.space: raise TypeError('`other` {!r} is not an element of the space ' '{} of this function' ''.format(other, self.space)) self._call_in_place = other._call_in_place self._call_out_of_place = other._call_out_of_place self._call_has_out = other._call_has_out self._call_out_optional = other._call_out_optional
[ "def", "assign", "(", "self", ",", "other", ")", ":", "if", "other", "not", "in", "self", ".", "space", ":", "raise", "TypeError", "(", "'`other` {!r} is not an element of the space '", "'{} of this function'", "''", ".", "format", "(", "other", ",", "self", "...
Assign ``other`` to ``self``. This is implemented without `FunctionSpace.lincomb` to ensure that ``self == other`` evaluates to True after ``self.assign(other)``.
[ "Assign", "other", "to", "self", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L1424-L1437
231,569
odlgroup/odl
odl/contrib/param_opt/param_opt.py
optimal_parameters
def optimal_parameters(reconstruction, fom, phantoms, data, initial=None, univariate=False): r"""Find the optimal parameters for a reconstruction method. Notes ----- For a forward operator :math:`A : X \to Y`, a reconstruction operator parametrized by :math:`\theta` is some operator :math:`R_\theta : Y \to X` such that .. math:: R_\theta(A(x)) \approx x. The optimal choice of :math:`\theta` is given by .. math:: \theta = \arg\min_\theta fom(R(A(x) + noise), x) where :math:`fom : X \times X \to \mathbb{R}` is a figure of merit. Parameters ---------- reconstruction : callable Function that takes two parameters: * data : The data to be reconstructed * parameters : Parameters of the reconstruction method The function should return the reconstructed image. fom : callable Function that takes two parameters: * reconstructed_image * true_image and returns a scalar figure of merit. phantoms : sequence True images. data : sequence The data to reconstruct from. initial : array-like or pair Initial guess for the parameters. It is - a required array in the multivariate case - an optional pair in the univariate case. univariate : bool, optional Whether to use a univariate solver Returns ------- parameters : 'numpy.ndarray' The optimal parameters for the reconstruction problem. """ def func(lam): # Function to be minimized by scipy return sum(fom(reconstruction(datai, lam), phantomi) for phantomi, datai in zip(phantoms, data)) # Pick resolution to fit the one used by the space tol = np.finfo(phantoms[0].space.dtype).resolution * 10 if univariate: # We use a faster optimizer for the one parameter case result = scipy.optimize.minimize_scalar( func, bracket=initial, tol=tol, bounds=None, options={'disp': False}) return result.x else: # Use a gradient free method to find the best parameters initial = np.asarray(initial) parameters = scipy.optimize.fmin_powell( func, initial, xtol=tol, ftol=tol, disp=False) return parameters
python
def optimal_parameters(reconstruction, fom, phantoms, data, initial=None, univariate=False): r"""Find the optimal parameters for a reconstruction method. Notes ----- For a forward operator :math:`A : X \to Y`, a reconstruction operator parametrized by :math:`\theta` is some operator :math:`R_\theta : Y \to X` such that .. math:: R_\theta(A(x)) \approx x. The optimal choice of :math:`\theta` is given by .. math:: \theta = \arg\min_\theta fom(R(A(x) + noise), x) where :math:`fom : X \times X \to \mathbb{R}` is a figure of merit. Parameters ---------- reconstruction : callable Function that takes two parameters: * data : The data to be reconstructed * parameters : Parameters of the reconstruction method The function should return the reconstructed image. fom : callable Function that takes two parameters: * reconstructed_image * true_image and returns a scalar figure of merit. phantoms : sequence True images. data : sequence The data to reconstruct from. initial : array-like or pair Initial guess for the parameters. It is - a required array in the multivariate case - an optional pair in the univariate case. univariate : bool, optional Whether to use a univariate solver Returns ------- parameters : 'numpy.ndarray' The optimal parameters for the reconstruction problem. """ def func(lam): # Function to be minimized by scipy return sum(fom(reconstruction(datai, lam), phantomi) for phantomi, datai in zip(phantoms, data)) # Pick resolution to fit the one used by the space tol = np.finfo(phantoms[0].space.dtype).resolution * 10 if univariate: # We use a faster optimizer for the one parameter case result = scipy.optimize.minimize_scalar( func, bracket=initial, tol=tol, bounds=None, options={'disp': False}) return result.x else: # Use a gradient free method to find the best parameters initial = np.asarray(initial) parameters = scipy.optimize.fmin_powell( func, initial, xtol=tol, ftol=tol, disp=False) return parameters
[ "def", "optimal_parameters", "(", "reconstruction", ",", "fom", ",", "phantoms", ",", "data", ",", "initial", "=", "None", ",", "univariate", "=", "False", ")", ":", "def", "func", "(", "lam", ")", ":", "# Function to be minimized by scipy", "return", "sum", ...
r"""Find the optimal parameters for a reconstruction method. Notes ----- For a forward operator :math:`A : X \to Y`, a reconstruction operator parametrized by :math:`\theta` is some operator :math:`R_\theta : Y \to X` such that .. math:: R_\theta(A(x)) \approx x. The optimal choice of :math:`\theta` is given by .. math:: \theta = \arg\min_\theta fom(R(A(x) + noise), x) where :math:`fom : X \times X \to \mathbb{R}` is a figure of merit. Parameters ---------- reconstruction : callable Function that takes two parameters: * data : The data to be reconstructed * parameters : Parameters of the reconstruction method The function should return the reconstructed image. fom : callable Function that takes two parameters: * reconstructed_image * true_image and returns a scalar figure of merit. phantoms : sequence True images. data : sequence The data to reconstruct from. initial : array-like or pair Initial guess for the parameters. It is - a required array in the multivariate case - an optional pair in the univariate case. univariate : bool, optional Whether to use a univariate solver Returns ------- parameters : 'numpy.ndarray' The optimal parameters for the reconstruction problem.
[ "r", "Find", "the", "optimal", "parameters", "for", "a", "reconstruction", "method", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/param_opt/param_opt.py#L17-L90
231,570
odlgroup/odl
odl/contrib/torch/operator.py
OperatorAsAutogradFunction.forward
def forward(self, input): """Evaluate forward pass on the input. Parameters ---------- input : `torch.tensor._TensorBase` Point at which to evaluate the operator. Returns ------- result : `torch.autograd.variable.Variable` Variable holding the result of the evaluation. Examples -------- Perform a matrix multiplication: >>> matrix = np.array([[1, 0, 1], ... [0, 1, 1]], dtype='float32') >>> odl_op = odl.MatrixOperator(matrix) >>> torch_op = OperatorAsAutogradFunction(odl_op) >>> x = torch.Tensor([1, 2, 3]) >>> x_var = torch.autograd.Variable(x) >>> torch_op(x_var) Variable containing: 4 5 [torch.FloatTensor of size 2] Evaluate a functional, i.e., an operator with scalar output: >>> odl_func = odl.solvers.L2NormSquared(odl.rn(3, dtype='float32')) >>> torch_func = OperatorAsAutogradFunction(odl_func) >>> x = torch.Tensor([1, 2, 3]) >>> x_var = torch.autograd.Variable(x) >>> torch_func(x_var) Variable containing: 14 [torch.FloatTensor of size 1] """ # TODO: batched evaluation if not self.operator.is_linear: # Only needed for nonlinear operators self.save_for_backward(input) # TODO: use GPU memory directly if possible input_arr = input.cpu().detach().numpy() if any(s == 0 for s in input_arr.strides): # TODO: remove when Numpy issue #9165 is fixed # https://github.com/numpy/numpy/pull/9177 input_arr = input_arr.copy() op_result = self.operator(input_arr) if np.isscalar(op_result): # For functionals, the result is funnelled through `float`, # so we wrap it into a Numpy array with the same dtype as # `operator.domain` op_result = np.array(op_result, ndmin=1, dtype=self.operator.domain.dtype) tensor = torch.from_numpy(np.array(op_result, copy=False, ndmin=1)) tensor = tensor.to(input.device) return tensor
python
def forward(self, input): # TODO: batched evaluation if not self.operator.is_linear: # Only needed for nonlinear operators self.save_for_backward(input) # TODO: use GPU memory directly if possible input_arr = input.cpu().detach().numpy() if any(s == 0 for s in input_arr.strides): # TODO: remove when Numpy issue #9165 is fixed # https://github.com/numpy/numpy/pull/9177 input_arr = input_arr.copy() op_result = self.operator(input_arr) if np.isscalar(op_result): # For functionals, the result is funnelled through `float`, # so we wrap it into a Numpy array with the same dtype as # `operator.domain` op_result = np.array(op_result, ndmin=1, dtype=self.operator.domain.dtype) tensor = torch.from_numpy(np.array(op_result, copy=False, ndmin=1)) tensor = tensor.to(input.device) return tensor
[ "def", "forward", "(", "self", ",", "input", ")", ":", "# TODO: batched evaluation", "if", "not", "self", ".", "operator", ".", "is_linear", ":", "# Only needed for nonlinear operators", "self", ".", "save_for_backward", "(", "input", ")", "# TODO: use GPU memory dire...
Evaluate forward pass on the input. Parameters ---------- input : `torch.tensor._TensorBase` Point at which to evaluate the operator. Returns ------- result : `torch.autograd.variable.Variable` Variable holding the result of the evaluation. Examples -------- Perform a matrix multiplication: >>> matrix = np.array([[1, 0, 1], ... [0, 1, 1]], dtype='float32') >>> odl_op = odl.MatrixOperator(matrix) >>> torch_op = OperatorAsAutogradFunction(odl_op) >>> x = torch.Tensor([1, 2, 3]) >>> x_var = torch.autograd.Variable(x) >>> torch_op(x_var) Variable containing: 4 5 [torch.FloatTensor of size 2] Evaluate a functional, i.e., an operator with scalar output: >>> odl_func = odl.solvers.L2NormSquared(odl.rn(3, dtype='float32')) >>> torch_func = OperatorAsAutogradFunction(odl_func) >>> x = torch.Tensor([1, 2, 3]) >>> x_var = torch.autograd.Variable(x) >>> torch_func(x_var) Variable containing: 14 [torch.FloatTensor of size 1]
[ "Evaluate", "forward", "pass", "on", "the", "input", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/torch/operator.py#L66-L127
231,571
odlgroup/odl
odl/contrib/torch/operator.py
OperatorAsAutogradFunction.backward
def backward(self, grad_output): r"""Apply the adjoint of the derivative at ``grad_output``. This method is usually not called explicitly but as a part of the ``cost.backward()`` pass of a backpropagation step. Parameters ---------- grad_output : `torch.tensor._TensorBase` Tensor to which the Jacobian should be applied. See Notes for details. Returns ------- result : `torch.autograd.variable.Variable` Variable holding the result of applying the Jacobian to ``grad_output``. See Notes for details. Examples -------- Compute the Jacobian adjoint of the matrix operator, which is the operator of the transposed matrix. We compose with the ``sum`` functional to be able to evaluate ``grad``: >>> matrix = np.array([[1, 0, 1], ... [0, 1, 1]], dtype='float32') >>> odl_op = odl.MatrixOperator(matrix) >>> torch_op = OperatorAsAutogradFunction(odl_op) >>> x = torch.Tensor([1, 2, 3]) >>> x_var = torch.autograd.Variable(x, requires_grad=True) >>> op_x_var = torch_op(x_var) >>> cost = op_x_var.sum() >>> cost.backward() >>> x_var.grad # should be matrix.T.dot([1, 1]) Variable containing: 1 1 2 [torch.FloatTensor of size 3] Compute the gradient of a custom functional: >>> odl_func = odl.solvers.L2NormSquared(odl.rn(3, dtype='float32')) >>> torch_func = OperatorAsAutogradFunction(odl_func) >>> x = torch.Tensor([1, 2, 3]) >>> x_var = torch.autograd.Variable(x, requires_grad=True) >>> func_x_var = torch_func(x_var) >>> func_x_var Variable containing: 14 [torch.FloatTensor of size 1] >>> func_x_var.backward() >>> x_var.grad # Should be 2 * x Variable containing: 2 4 6 [torch.FloatTensor of size 3] Notes ----- This method applies the contribution of this node, i.e., the transpose of the Jacobian of its outputs with respect to its inputs, to the gradients of some cost function with respect to the outputs of this node. Example: Assume that this node computes :math:`x \mapsto C(f(x))`, where :math:`x` is a tensor variable and :math:`C` is a scalar-valued function. In ODL language, what ``backward`` should compute is .. math:: \nabla(C \circ f)(x) = f'(x)^*\big(\nabla C (f(x))\big) according to the chain rule. In ODL code, this corresponds to :: f.derivative(x).adjoint(C.gradient(f(x))). Hence, the parameter ``grad_output`` is a tensor variable containing :math:`y = \nabla C(f(x))`. Then, ``backward`` boils down to computing ``[f'(x)^*(y)]`` using the input ``x`` stored during the previous `forward` pass. """ # TODO: implement directly for GPU data if not self.operator.is_linear: input_arr = self.saved_variables[0].data.cpu().numpy() if any(s == 0 for s in input_arr.strides): # TODO: remove when Numpy issue #9165 is fixed # https://github.com/numpy/numpy/pull/9177 input_arr = input_arr.copy() grad = None # ODL weights spaces, pytorch doesn't, so we need to handle this try: dom_weight = self.operator.domain.weighting.const except AttributeError: dom_weight = 1.0 try: ran_weight = self.operator.range.weighting.const except AttributeError: ran_weight = 1.0 scaling = dom_weight / ran_weight if self.needs_input_grad[0]: grad_output_arr = grad_output.cpu().numpy() if any(s == 0 for s in grad_output_arr.strides): # TODO: remove when Numpy issue #9165 is fixed # https://github.com/numpy/numpy/pull/9177 grad_output_arr = grad_output_arr.copy() if self.operator.is_linear: adjoint = self.operator.adjoint else: adjoint = self.operator.derivative(input_arr).adjoint grad_odl = adjoint(grad_output_arr) if scaling != 1.0: grad_odl *= scaling grad = torch.from_numpy(np.array(grad_odl, copy=False, ndmin=1)) grad = grad.to(grad_output.device) return grad
python
def backward(self, grad_output): r"""Apply the adjoint of the derivative at ``grad_output``. This method is usually not called explicitly but as a part of the ``cost.backward()`` pass of a backpropagation step. Parameters ---------- grad_output : `torch.tensor._TensorBase` Tensor to which the Jacobian should be applied. See Notes for details. Returns ------- result : `torch.autograd.variable.Variable` Variable holding the result of applying the Jacobian to ``grad_output``. See Notes for details. Examples -------- Compute the Jacobian adjoint of the matrix operator, which is the operator of the transposed matrix. We compose with the ``sum`` functional to be able to evaluate ``grad``: >>> matrix = np.array([[1, 0, 1], ... [0, 1, 1]], dtype='float32') >>> odl_op = odl.MatrixOperator(matrix) >>> torch_op = OperatorAsAutogradFunction(odl_op) >>> x = torch.Tensor([1, 2, 3]) >>> x_var = torch.autograd.Variable(x, requires_grad=True) >>> op_x_var = torch_op(x_var) >>> cost = op_x_var.sum() >>> cost.backward() >>> x_var.grad # should be matrix.T.dot([1, 1]) Variable containing: 1 1 2 [torch.FloatTensor of size 3] Compute the gradient of a custom functional: >>> odl_func = odl.solvers.L2NormSquared(odl.rn(3, dtype='float32')) >>> torch_func = OperatorAsAutogradFunction(odl_func) >>> x = torch.Tensor([1, 2, 3]) >>> x_var = torch.autograd.Variable(x, requires_grad=True) >>> func_x_var = torch_func(x_var) >>> func_x_var Variable containing: 14 [torch.FloatTensor of size 1] >>> func_x_var.backward() >>> x_var.grad # Should be 2 * x Variable containing: 2 4 6 [torch.FloatTensor of size 3] Notes ----- This method applies the contribution of this node, i.e., the transpose of the Jacobian of its outputs with respect to its inputs, to the gradients of some cost function with respect to the outputs of this node. Example: Assume that this node computes :math:`x \mapsto C(f(x))`, where :math:`x` is a tensor variable and :math:`C` is a scalar-valued function. In ODL language, what ``backward`` should compute is .. math:: \nabla(C \circ f)(x) = f'(x)^*\big(\nabla C (f(x))\big) according to the chain rule. In ODL code, this corresponds to :: f.derivative(x).adjoint(C.gradient(f(x))). Hence, the parameter ``grad_output`` is a tensor variable containing :math:`y = \nabla C(f(x))`. Then, ``backward`` boils down to computing ``[f'(x)^*(y)]`` using the input ``x`` stored during the previous `forward` pass. """ # TODO: implement directly for GPU data if not self.operator.is_linear: input_arr = self.saved_variables[0].data.cpu().numpy() if any(s == 0 for s in input_arr.strides): # TODO: remove when Numpy issue #9165 is fixed # https://github.com/numpy/numpy/pull/9177 input_arr = input_arr.copy() grad = None # ODL weights spaces, pytorch doesn't, so we need to handle this try: dom_weight = self.operator.domain.weighting.const except AttributeError: dom_weight = 1.0 try: ran_weight = self.operator.range.weighting.const except AttributeError: ran_weight = 1.0 scaling = dom_weight / ran_weight if self.needs_input_grad[0]: grad_output_arr = grad_output.cpu().numpy() if any(s == 0 for s in grad_output_arr.strides): # TODO: remove when Numpy issue #9165 is fixed # https://github.com/numpy/numpy/pull/9177 grad_output_arr = grad_output_arr.copy() if self.operator.is_linear: adjoint = self.operator.adjoint else: adjoint = self.operator.derivative(input_arr).adjoint grad_odl = adjoint(grad_output_arr) if scaling != 1.0: grad_odl *= scaling grad = torch.from_numpy(np.array(grad_odl, copy=False, ndmin=1)) grad = grad.to(grad_output.device) return grad
[ "def", "backward", "(", "self", ",", "grad_output", ")", ":", "# TODO: implement directly for GPU data", "if", "not", "self", ".", "operator", ".", "is_linear", ":", "input_arr", "=", "self", ".", "saved_variables", "[", "0", "]", ".", "data", ".", "cpu", "(...
r"""Apply the adjoint of the derivative at ``grad_output``. This method is usually not called explicitly but as a part of the ``cost.backward()`` pass of a backpropagation step. Parameters ---------- grad_output : `torch.tensor._TensorBase` Tensor to which the Jacobian should be applied. See Notes for details. Returns ------- result : `torch.autograd.variable.Variable` Variable holding the result of applying the Jacobian to ``grad_output``. See Notes for details. Examples -------- Compute the Jacobian adjoint of the matrix operator, which is the operator of the transposed matrix. We compose with the ``sum`` functional to be able to evaluate ``grad``: >>> matrix = np.array([[1, 0, 1], ... [0, 1, 1]], dtype='float32') >>> odl_op = odl.MatrixOperator(matrix) >>> torch_op = OperatorAsAutogradFunction(odl_op) >>> x = torch.Tensor([1, 2, 3]) >>> x_var = torch.autograd.Variable(x, requires_grad=True) >>> op_x_var = torch_op(x_var) >>> cost = op_x_var.sum() >>> cost.backward() >>> x_var.grad # should be matrix.T.dot([1, 1]) Variable containing: 1 1 2 [torch.FloatTensor of size 3] Compute the gradient of a custom functional: >>> odl_func = odl.solvers.L2NormSquared(odl.rn(3, dtype='float32')) >>> torch_func = OperatorAsAutogradFunction(odl_func) >>> x = torch.Tensor([1, 2, 3]) >>> x_var = torch.autograd.Variable(x, requires_grad=True) >>> func_x_var = torch_func(x_var) >>> func_x_var Variable containing: 14 [torch.FloatTensor of size 1] >>> func_x_var.backward() >>> x_var.grad # Should be 2 * x Variable containing: 2 4 6 [torch.FloatTensor of size 3] Notes ----- This method applies the contribution of this node, i.e., the transpose of the Jacobian of its outputs with respect to its inputs, to the gradients of some cost function with respect to the outputs of this node. Example: Assume that this node computes :math:`x \mapsto C(f(x))`, where :math:`x` is a tensor variable and :math:`C` is a scalar-valued function. In ODL language, what ``backward`` should compute is .. math:: \nabla(C \circ f)(x) = f'(x)^*\big(\nabla C (f(x))\big) according to the chain rule. In ODL code, this corresponds to :: f.derivative(x).adjoint(C.gradient(f(x))). Hence, the parameter ``grad_output`` is a tensor variable containing :math:`y = \nabla C(f(x))`. Then, ``backward`` boils down to computing ``[f'(x)^*(y)]`` using the input ``x`` stored during the previous `forward` pass.
[ "r", "Apply", "the", "adjoint", "of", "the", "derivative", "at", "grad_output", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/torch/operator.py#L129-L255
231,572
odlgroup/odl
odl/contrib/torch/operator.py
OperatorAsModule.forward
def forward(self, x): """Compute forward-pass of this module on ``x``. Parameters ---------- x : `torch.autograd.variable.Variable` Input of this layer. The contained tensor must have shape ``extra_shape + operator.domain.shape``, and ``len(extra_shape)`` must be at least 1 (batch axis). Returns ------- out : `torch.autograd.variable.Variable` The computed output. Its tensor will have shape ``extra_shape + operator.range.shape``, where ``extra_shape`` are the extra axes of ``x``. Examples -------- Evaluating on a 2D tensor, where the operator expects a 1D input, i.e., with extra batch axis only: >>> matrix = np.array([[1, 0, 0], ... [0, 1, 1]], dtype='float32') >>> odl_op = odl.MatrixOperator(matrix) >>> odl_op.domain.shape (3,) >>> odl_op.range.shape (2,) >>> op_mod = OperatorAsModule(odl_op) >>> t = torch.ones(3) >>> x = autograd.Variable(t[None, :]) # "fake" batch axis >>> op_mod(x) Variable containing: 1 2 [torch.FloatTensor of size 1x2] >>> t = torch.ones(3) >>> x_tensor = torch.stack([0 * t, 1 * t]) >>> x = autograd.Variable(x_tensor) # batch of 2 inputs >>> op_mod(x) Variable containing: 0 0 1 2 [torch.FloatTensor of size 2x2] An arbitrary number of axes is supported: >>> x = autograd.Variable(t[None, None, :]) # "fake" batch and channel >>> op_mod(x) Variable containing: (0 ,.,.) = 1 2 [torch.FloatTensor of size 1x1x2] >>> x_tensor = torch.stack([torch.stack([0 * t, 1 * t]), ... torch.stack([2 * t, 3 * t]), ... torch.stack([4 * t, 5 * t])]) >>> x = autograd.Variable(x_tensor) # batch of 3x2 inputs >>> op_mod(x) Variable containing: (0 ,.,.) = 0 0 1 2 <BLANKLINE> (1 ,.,.) = 2 4 3 6 <BLANKLINE> (2 ,.,.) = 4 8 5 10 [torch.FloatTensor of size 3x2x2] """ in_shape = x.data.shape op_in_shape = self.op_func.operator.domain.shape op_out_shape = self.op_func.operator.range.shape extra_shape = in_shape[:-len(op_in_shape)] if in_shape[-len(op_in_shape):] != op_in_shape or not extra_shape: shp_str = str(op_in_shape).strip('()') raise ValueError('expected input of shape (N, *, {}), got input ' 'with shape {}'.format(shp_str, in_shape)) # Flatten extra axes, then do one entry at a time newshape = (int(np.prod(extra_shape)),) + op_in_shape x_flat_xtra = x.reshape(*newshape) results = [] for i in range(x_flat_xtra.data.shape[0]): results.append(self.op_func(x_flat_xtra[i])) # Reshape the resulting stack to the expected output shape stack_flat_xtra = torch.stack(results) return stack_flat_xtra.view(extra_shape + op_out_shape)
python
def forward(self, x): in_shape = x.data.shape op_in_shape = self.op_func.operator.domain.shape op_out_shape = self.op_func.operator.range.shape extra_shape = in_shape[:-len(op_in_shape)] if in_shape[-len(op_in_shape):] != op_in_shape or not extra_shape: shp_str = str(op_in_shape).strip('()') raise ValueError('expected input of shape (N, *, {}), got input ' 'with shape {}'.format(shp_str, in_shape)) # Flatten extra axes, then do one entry at a time newshape = (int(np.prod(extra_shape)),) + op_in_shape x_flat_xtra = x.reshape(*newshape) results = [] for i in range(x_flat_xtra.data.shape[0]): results.append(self.op_func(x_flat_xtra[i])) # Reshape the resulting stack to the expected output shape stack_flat_xtra = torch.stack(results) return stack_flat_xtra.view(extra_shape + op_out_shape)
[ "def", "forward", "(", "self", ",", "x", ")", ":", "in_shape", "=", "x", ".", "data", ".", "shape", "op_in_shape", "=", "self", ".", "op_func", ".", "operator", ".", "domain", ".", "shape", "op_out_shape", "=", "self", ".", "op_func", ".", "operator", ...
Compute forward-pass of this module on ``x``. Parameters ---------- x : `torch.autograd.variable.Variable` Input of this layer. The contained tensor must have shape ``extra_shape + operator.domain.shape``, and ``len(extra_shape)`` must be at least 1 (batch axis). Returns ------- out : `torch.autograd.variable.Variable` The computed output. Its tensor will have shape ``extra_shape + operator.range.shape``, where ``extra_shape`` are the extra axes of ``x``. Examples -------- Evaluating on a 2D tensor, where the operator expects a 1D input, i.e., with extra batch axis only: >>> matrix = np.array([[1, 0, 0], ... [0, 1, 1]], dtype='float32') >>> odl_op = odl.MatrixOperator(matrix) >>> odl_op.domain.shape (3,) >>> odl_op.range.shape (2,) >>> op_mod = OperatorAsModule(odl_op) >>> t = torch.ones(3) >>> x = autograd.Variable(t[None, :]) # "fake" batch axis >>> op_mod(x) Variable containing: 1 2 [torch.FloatTensor of size 1x2] >>> t = torch.ones(3) >>> x_tensor = torch.stack([0 * t, 1 * t]) >>> x = autograd.Variable(x_tensor) # batch of 2 inputs >>> op_mod(x) Variable containing: 0 0 1 2 [torch.FloatTensor of size 2x2] An arbitrary number of axes is supported: >>> x = autograd.Variable(t[None, None, :]) # "fake" batch and channel >>> op_mod(x) Variable containing: (0 ,.,.) = 1 2 [torch.FloatTensor of size 1x1x2] >>> x_tensor = torch.stack([torch.stack([0 * t, 1 * t]), ... torch.stack([2 * t, 3 * t]), ... torch.stack([4 * t, 5 * t])]) >>> x = autograd.Variable(x_tensor) # batch of 3x2 inputs >>> op_mod(x) Variable containing: (0 ,.,.) = 0 0 1 2 <BLANKLINE> (1 ,.,.) = 2 4 3 6 <BLANKLINE> (2 ,.,.) = 4 8 5 10 [torch.FloatTensor of size 3x2x2]
[ "Compute", "forward", "-", "pass", "of", "this", "module", "on", "x", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/torch/operator.py#L302-L394
231,573
odlgroup/odl
odl/contrib/fom/supervised.py
mean_squared_error
def mean_squared_error(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r"""Return mean squared L2 distance between ``data`` and ``ground_truth``. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Mean_squared_error>`_. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional If ``True``, the output values are mapped to the interval :math:`[0, 1]` (see `Notes` for details). force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the mean squared error, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- mse : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{MSE}(f, g) = \frac{\| f - g \|_2^2}{\| 1 \|_2^2}, where :math:`\| 1 \|^2_2` is the volume of the domain of definition of the functions. For :math:`\mathbb{R}^n` type spaces, this is equal to the number of elements :math:`n`. The normalized form is .. math:: \mathrm{MSE_N} = \frac{\| f - g \|_2^2}{(\| f \|_2 + \| g \|_2)^2}. The normalized variant takes values in :math:`[0, 1]`. """ if not hasattr(data, 'space'): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) l2norm = odl.solvers.L2Norm(space) if mask is not None: data = data * mask ground_truth = ground_truth * mask diff = data - ground_truth fom = l2norm(diff) ** 2 if normalized: fom /= (l2norm(data) + l2norm(ground_truth)) ** 2 else: fom /= l2norm(space.one()) ** 2 # Ignore `force_lower_is_better` since that's already the case return fom
python
def mean_squared_error(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r"""Return mean squared L2 distance between ``data`` and ``ground_truth``. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Mean_squared_error>`_. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional If ``True``, the output values are mapped to the interval :math:`[0, 1]` (see `Notes` for details). force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the mean squared error, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- mse : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{MSE}(f, g) = \frac{\| f - g \|_2^2}{\| 1 \|_2^2}, where :math:`\| 1 \|^2_2` is the volume of the domain of definition of the functions. For :math:`\mathbb{R}^n` type spaces, this is equal to the number of elements :math:`n`. The normalized form is .. math:: \mathrm{MSE_N} = \frac{\| f - g \|_2^2}{(\| f \|_2 + \| g \|_2)^2}. The normalized variant takes values in :math:`[0, 1]`. """ if not hasattr(data, 'space'): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) l2norm = odl.solvers.L2Norm(space) if mask is not None: data = data * mask ground_truth = ground_truth * mask diff = data - ground_truth fom = l2norm(diff) ** 2 if normalized: fom /= (l2norm(data) + l2norm(ground_truth)) ** 2 else: fom /= l2norm(space.one()) ** 2 # Ignore `force_lower_is_better` since that's already the case return fom
[ "def", "mean_squared_error", "(", "data", ",", "ground_truth", ",", "mask", "=", "None", ",", "normalized", "=", "False", ",", "force_lower_is_better", "=", "True", ")", ":", "if", "not", "hasattr", "(", "data", ",", "'space'", ")", ":", "data", "=", "od...
r"""Return mean squared L2 distance between ``data`` and ``ground_truth``. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Mean_squared_error>`_. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional If ``True``, the output values are mapped to the interval :math:`[0, 1]` (see `Notes` for details). force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the mean squared error, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- mse : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{MSE}(f, g) = \frac{\| f - g \|_2^2}{\| 1 \|_2^2}, where :math:`\| 1 \|^2_2` is the volume of the domain of definition of the functions. For :math:`\mathbb{R}^n` type spaces, this is equal to the number of elements :math:`n`. The normalized form is .. math:: \mathrm{MSE_N} = \frac{\| f - g \|_2^2}{(\| f \|_2 + \| g \|_2)^2}. The normalized variant takes values in :math:`[0, 1]`.
[ "r", "Return", "mean", "squared", "L2", "distance", "between", "data", "and", "ground_truth", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/fom/supervised.py#L25-L94
231,574
odlgroup/odl
odl/contrib/fom/supervised.py
mean_absolute_error
def mean_absolute_error(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r"""Return L1-distance between ``data`` and ``ground_truth``. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Mean_absolute_error>`_. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional If ``True``, the output values are mapped to the interval :math:`[0, 1]` (see `Notes` for details), otherwise return the original mean absolute error. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the mean absolute error, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- mae : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{MAE}(f, g) = \frac{\| f - g \|_1}{\| 1 \|_1}, where :math:`\| 1 \|_1` is the volume of the domain of definition of the functions. For :math:`\mathbb{R}^n` type spaces, this is equal to the number of elements :math:`n`. The normalized form is .. math:: \mathrm{MAE_N}(f, g) = \frac{\| f - g \|_1}{\| f \|_1 + \| g \|_1}. The normalized variant takes values in :math:`[0, 1]`. """ if not hasattr(data, 'space'): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) l1_norm = odl.solvers.L1Norm(space) if mask is not None: data = data * mask ground_truth = ground_truth * mask diff = data - ground_truth fom = l1_norm(diff) if normalized: fom /= (l1_norm(data) + l1_norm(ground_truth)) else: fom /= l1_norm(space.one()) # Ignore `force_lower_is_better` since that's already the case return fom
python
def mean_absolute_error(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r"""Return L1-distance between ``data`` and ``ground_truth``. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Mean_absolute_error>`_. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional If ``True``, the output values are mapped to the interval :math:`[0, 1]` (see `Notes` for details), otherwise return the original mean absolute error. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the mean absolute error, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- mae : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{MAE}(f, g) = \frac{\| f - g \|_1}{\| 1 \|_1}, where :math:`\| 1 \|_1` is the volume of the domain of definition of the functions. For :math:`\mathbb{R}^n` type spaces, this is equal to the number of elements :math:`n`. The normalized form is .. math:: \mathrm{MAE_N}(f, g) = \frac{\| f - g \|_1}{\| f \|_1 + \| g \|_1}. The normalized variant takes values in :math:`[0, 1]`. """ if not hasattr(data, 'space'): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) l1_norm = odl.solvers.L1Norm(space) if mask is not None: data = data * mask ground_truth = ground_truth * mask diff = data - ground_truth fom = l1_norm(diff) if normalized: fom /= (l1_norm(data) + l1_norm(ground_truth)) else: fom /= l1_norm(space.one()) # Ignore `force_lower_is_better` since that's already the case return fom
[ "def", "mean_absolute_error", "(", "data", ",", "ground_truth", ",", "mask", "=", "None", ",", "normalized", "=", "False", ",", "force_lower_is_better", "=", "True", ")", ":", "if", "not", "hasattr", "(", "data", ",", "'space'", ")", ":", "data", "=", "o...
r"""Return L1-distance between ``data`` and ``ground_truth``. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Mean_absolute_error>`_. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional If ``True``, the output values are mapped to the interval :math:`[0, 1]` (see `Notes` for details), otherwise return the original mean absolute error. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the mean absolute error, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- mae : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{MAE}(f, g) = \frac{\| f - g \|_1}{\| 1 \|_1}, where :math:`\| 1 \|_1` is the volume of the domain of definition of the functions. For :math:`\mathbb{R}^n` type spaces, this is equal to the number of elements :math:`n`. The normalized form is .. math:: \mathrm{MAE_N}(f, g) = \frac{\| f - g \|_1}{\| f \|_1 + \| g \|_1}. The normalized variant takes values in :math:`[0, 1]`.
[ "r", "Return", "L1", "-", "distance", "between", "data", "and", "ground_truth", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/fom/supervised.py#L97-L166
231,575
odlgroup/odl
odl/contrib/fom/supervised.py
mean_value_difference
def mean_value_difference(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r"""Return difference in mean value between ``data`` and ``ground_truth``. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional Boolean flag to switch between unormalized and normalized FOM. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the mean value difference, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- mvd : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{MVD}(f, g) = \Big| \overline{f} - \overline{g} \Big|, or, in normalized form .. math:: \mathrm{MVD_N}(f, g) = \frac{\Big| \overline{f} - \overline{g} \Big|} {|\overline{f}| + |\overline{g}|} where :math:`\overline{f}` is the mean value of :math:`f`, .. math:: \overline{f} = \frac{\langle f, 1\rangle}{\|1|_1}. The normalized variant takes values in :math:`[0, 1]`. """ if not hasattr(data, 'space'): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) l1_norm = odl.solvers.L1Norm(space) if mask is not None: data = data * mask ground_truth = ground_truth * mask # Volume of space vol = l1_norm(space.one()) data_mean = data.inner(space.one()) / vol ground_truth_mean = ground_truth.inner(space.one()) / vol fom = np.abs(data_mean - ground_truth_mean) if normalized: fom /= (np.abs(data_mean) + np.abs(ground_truth_mean)) # Ignore `force_lower_is_better` since that's already the case return fom
python
def mean_value_difference(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r"""Return difference in mean value between ``data`` and ``ground_truth``. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional Boolean flag to switch between unormalized and normalized FOM. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the mean value difference, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- mvd : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{MVD}(f, g) = \Big| \overline{f} - \overline{g} \Big|, or, in normalized form .. math:: \mathrm{MVD_N}(f, g) = \frac{\Big| \overline{f} - \overline{g} \Big|} {|\overline{f}| + |\overline{g}|} where :math:`\overline{f}` is the mean value of :math:`f`, .. math:: \overline{f} = \frac{\langle f, 1\rangle}{\|1|_1}. The normalized variant takes values in :math:`[0, 1]`. """ if not hasattr(data, 'space'): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) l1_norm = odl.solvers.L1Norm(space) if mask is not None: data = data * mask ground_truth = ground_truth * mask # Volume of space vol = l1_norm(space.one()) data_mean = data.inner(space.one()) / vol ground_truth_mean = ground_truth.inner(space.one()) / vol fom = np.abs(data_mean - ground_truth_mean) if normalized: fom /= (np.abs(data_mean) + np.abs(ground_truth_mean)) # Ignore `force_lower_is_better` since that's already the case return fom
[ "def", "mean_value_difference", "(", "data", ",", "ground_truth", ",", "mask", "=", "None", ",", "normalized", "=", "False", ",", "force_lower_is_better", "=", "True", ")", ":", "if", "not", "hasattr", "(", "data", ",", "'space'", ")", ":", "data", "=", ...
r"""Return difference in mean value between ``data`` and ``ground_truth``. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional Boolean flag to switch between unormalized and normalized FOM. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the mean value difference, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- mvd : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{MVD}(f, g) = \Big| \overline{f} - \overline{g} \Big|, or, in normalized form .. math:: \mathrm{MVD_N}(f, g) = \frac{\Big| \overline{f} - \overline{g} \Big|} {|\overline{f}| + |\overline{g}|} where :math:`\overline{f}` is the mean value of :math:`f`, .. math:: \overline{f} = \frac{\langle f, 1\rangle}{\|1|_1}. The normalized variant takes values in :math:`[0, 1]`.
[ "r", "Return", "difference", "in", "mean", "value", "between", "data", "and", "ground_truth", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/fom/supervised.py#L169-L240
231,576
odlgroup/odl
odl/contrib/fom/supervised.py
standard_deviation_difference
def standard_deviation_difference(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r"""Return absolute diff in std between ``data`` and ``ground_truth``. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional Boolean flag to switch between unormalized and normalized FOM. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the standard deviation difference, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- sdd : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{SDD}(f, g) = \Big| \| f - \overline{f} \|_2 - \| g - \overline{g} \|_2 \Big|, or, in normalized form .. math:: \mathrm{SDD_N}(f, g) = \frac{\Big| \| f - \overline{f} \|_2 - \| g - \overline{g} \|_2 \Big|} {\| f - \overline{f} \|_2 + \| g - \overline{g} \|_2}, where :math:`\overline{f}` is the mean value of :math:`f`, .. math:: \overline{f} = \frac{\langle f, 1\rangle}{\|1|_1}. The normalized variant takes values in :math:`[0, 1]`. """ if not hasattr(data, 'space'): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) l1_norm = odl.solvers.L1Norm(space) l2_norm = odl.solvers.L2Norm(space) if mask is not None: data = data * mask ground_truth = ground_truth * mask # Volume of space vol = l1_norm(space.one()) data_mean = data.inner(space.one()) / vol ground_truth_mean = ground_truth.inner(space.one()) / vol deviation_data = l2_norm(data - data_mean) deviation_ground_truth = l2_norm(ground_truth - ground_truth_mean) fom = np.abs(deviation_data - deviation_ground_truth) if normalized: denom = deviation_data + deviation_ground_truth if denom == 0: fom = 0.0 else: fom /= denom return fom
python
def standard_deviation_difference(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r"""Return absolute diff in std between ``data`` and ``ground_truth``. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional Boolean flag to switch between unormalized and normalized FOM. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the standard deviation difference, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- sdd : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{SDD}(f, g) = \Big| \| f - \overline{f} \|_2 - \| g - \overline{g} \|_2 \Big|, or, in normalized form .. math:: \mathrm{SDD_N}(f, g) = \frac{\Big| \| f - \overline{f} \|_2 - \| g - \overline{g} \|_2 \Big|} {\| f - \overline{f} \|_2 + \| g - \overline{g} \|_2}, where :math:`\overline{f}` is the mean value of :math:`f`, .. math:: \overline{f} = \frac{\langle f, 1\rangle}{\|1|_1}. The normalized variant takes values in :math:`[0, 1]`. """ if not hasattr(data, 'space'): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) l1_norm = odl.solvers.L1Norm(space) l2_norm = odl.solvers.L2Norm(space) if mask is not None: data = data * mask ground_truth = ground_truth * mask # Volume of space vol = l1_norm(space.one()) data_mean = data.inner(space.one()) / vol ground_truth_mean = ground_truth.inner(space.one()) / vol deviation_data = l2_norm(data - data_mean) deviation_ground_truth = l2_norm(ground_truth - ground_truth_mean) fom = np.abs(deviation_data - deviation_ground_truth) if normalized: denom = deviation_data + deviation_ground_truth if denom == 0: fom = 0.0 else: fom /= denom return fom
[ "def", "standard_deviation_difference", "(", "data", ",", "ground_truth", ",", "mask", "=", "None", ",", "normalized", "=", "False", ",", "force_lower_is_better", "=", "True", ")", ":", "if", "not", "hasattr", "(", "data", ",", "'space'", ")", ":", "data", ...
r"""Return absolute diff in std between ``data`` and ``ground_truth``. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional If given, ``data * mask`` is compared to ``ground_truth * mask``. normalized : bool, optional Boolean flag to switch between unormalized and normalized FOM. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the standard deviation difference, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- sdd : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{SDD}(f, g) = \Big| \| f - \overline{f} \|_2 - \| g - \overline{g} \|_2 \Big|, or, in normalized form .. math:: \mathrm{SDD_N}(f, g) = \frac{\Big| \| f - \overline{f} \|_2 - \| g - \overline{g} \|_2 \Big|} {\| f - \overline{f} \|_2 + \| g - \overline{g} \|_2}, where :math:`\overline{f}` is the mean value of :math:`f`, .. math:: \overline{f} = \frac{\langle f, 1\rangle}{\|1|_1}. The normalized variant takes values in :math:`[0, 1]`.
[ "r", "Return", "absolute", "diff", "in", "std", "between", "data", "and", "ground_truth", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/fom/supervised.py#L243-L323
231,577
odlgroup/odl
odl/contrib/fom/supervised.py
range_difference
def range_difference(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r"""Return dynamic range difference between ``data`` and ``ground_truth``. Evaluates difference in range between input (``data``) and reference data (``ground_truth``). Allows for normalization (``normalized``) and a masking of the two spaces (``mask``). Parameters ---------- data : `array-like` Input data to compare to the ground truth. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional Binary mask or index array to define ROI in which FOM evaluation is performed. normalized : bool, optional If ``True``, normalize the FOM to lie in [0, 1]. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the range difference, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- rd : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{RD}(f, g) = \Big| \big(\max(f) - \min(f) \big) - \big(\max(g) - \min(g) \big) \Big| or, in normalized form .. math:: \mathrm{RD_N}(f, g) = \frac{ \Big| \big(\max(f) - \min(f) \big) - \big(\max(g) - \min(g) \big) \Big|}{ \big(\max(f) - \min(f) \big) + \big(\max(g) - \min(g) \big)} The normalized variant takes values in :math:`[0, 1]`. """ data = np.asarray(data) ground_truth = np.asarray(ground_truth) if mask is not None: mask = np.asarray(mask, dtype=bool) data = data[mask] ground_truth = ground_truth[mask] data_range = np.ptp(data) ground_truth_range = np.ptp(ground_truth) fom = np.abs(data_range - ground_truth_range) if normalized: denom = np.abs(data_range + ground_truth_range) if denom == 0: fom = 0.0 else: fom /= denom return fom
python
def range_difference(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r"""Return dynamic range difference between ``data`` and ``ground_truth``. Evaluates difference in range between input (``data``) and reference data (``ground_truth``). Allows for normalization (``normalized``) and a masking of the two spaces (``mask``). Parameters ---------- data : `array-like` Input data to compare to the ground truth. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional Binary mask or index array to define ROI in which FOM evaluation is performed. normalized : bool, optional If ``True``, normalize the FOM to lie in [0, 1]. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the range difference, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- rd : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{RD}(f, g) = \Big| \big(\max(f) - \min(f) \big) - \big(\max(g) - \min(g) \big) \Big| or, in normalized form .. math:: \mathrm{RD_N}(f, g) = \frac{ \Big| \big(\max(f) - \min(f) \big) - \big(\max(g) - \min(g) \big) \Big|}{ \big(\max(f) - \min(f) \big) + \big(\max(g) - \min(g) \big)} The normalized variant takes values in :math:`[0, 1]`. """ data = np.asarray(data) ground_truth = np.asarray(ground_truth) if mask is not None: mask = np.asarray(mask, dtype=bool) data = data[mask] ground_truth = ground_truth[mask] data_range = np.ptp(data) ground_truth_range = np.ptp(ground_truth) fom = np.abs(data_range - ground_truth_range) if normalized: denom = np.abs(data_range + ground_truth_range) if denom == 0: fom = 0.0 else: fom /= denom return fom
[ "def", "range_difference", "(", "data", ",", "ground_truth", ",", "mask", "=", "None", ",", "normalized", "=", "False", ",", "force_lower_is_better", "=", "True", ")", ":", "data", "=", "np", ".", "asarray", "(", "data", ")", "ground_truth", "=", "np", "...
r"""Return dynamic range difference between ``data`` and ``ground_truth``. Evaluates difference in range between input (``data``) and reference data (``ground_truth``). Allows for normalization (``normalized``) and a masking of the two spaces (``mask``). Parameters ---------- data : `array-like` Input data to compare to the ground truth. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional Binary mask or index array to define ROI in which FOM evaluation is performed. normalized : bool, optional If ``True``, normalize the FOM to lie in [0, 1]. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches. For the range difference, this is already the case, and the flag is only present for compatibility to other figures of merit. Returns ------- rd : float FOM value, where a lower value means a better match. Notes ----- The FOM evaluates .. math:: \mathrm{RD}(f, g) = \Big| \big(\max(f) - \min(f) \big) - \big(\max(g) - \min(g) \big) \Big| or, in normalized form .. math:: \mathrm{RD_N}(f, g) = \frac{ \Big| \big(\max(f) - \min(f) \big) - \big(\max(g) - \min(g) \big) \Big|}{ \big(\max(f) - \min(f) \big) + \big(\max(g) - \min(g) \big)} The normalized variant takes values in :math:`[0, 1]`.
[ "r", "Return", "dynamic", "range", "difference", "between", "data", "and", "ground_truth", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/fom/supervised.py#L326-L397
231,578
odlgroup/odl
odl/contrib/fom/supervised.py
blurring
def blurring(data, ground_truth, mask=None, normalized=False, smoothness_factor=None): r"""Return weighted L2 distance, emphasizing regions defined by ``mask``. .. note:: If the mask argument is omitted, this FOM is equivalent to the mean squared error. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional Binary mask to define ROI in which FOM evaluation is performed. normalized : bool, optional Boolean flag to switch between unormalized and normalized FOM. smoothness_factor : float, optional Positive real number. Higher value gives smoother weighting. Returns ------- blur : float FOM value, where a lower value means a better match. See Also -------- false_structures mean_squared_error Notes ----- The FOM evaluates .. math:: \mathrm{BLUR}(f, g) = \|\alpha (f - g) \|_2^2, or, in normalized form .. math:: \mathrm{BLUR_N}(f, g) = \frac{\|\alpha(f - g)\|^2_2} {\|\alpha f\|^2_2 + \|\alpha g\|^2_2}. The weighting function :math:`\alpha` is given as .. math:: \alpha(x) = e^{-\frac{1}{k} \beta_m(x)}, where :math:`\beta_m(x)` is the Euclidian distance transform of a given binary mask :math:`m`, and :math:`k` positive real number that controls the smoothness of the weighting function :math:`\alpha`. The weighting gives higher values to structures in the region of interest defined by the mask. The normalized variant takes values in :math:`[0, 1]`. """ from scipy.ndimage.morphology import distance_transform_edt if not hasattr(data, 'space'): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) if smoothness_factor is None: smoothness_factor = np.mean(data.shape) / 10 if mask is not None: mask = distance_transform_edt(1 - mask) mask = np.exp(-mask / smoothness_factor) return mean_squared_error(data, ground_truth, mask, normalized)
python
def blurring(data, ground_truth, mask=None, normalized=False, smoothness_factor=None): r"""Return weighted L2 distance, emphasizing regions defined by ``mask``. .. note:: If the mask argument is omitted, this FOM is equivalent to the mean squared error. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional Binary mask to define ROI in which FOM evaluation is performed. normalized : bool, optional Boolean flag to switch between unormalized and normalized FOM. smoothness_factor : float, optional Positive real number. Higher value gives smoother weighting. Returns ------- blur : float FOM value, where a lower value means a better match. See Also -------- false_structures mean_squared_error Notes ----- The FOM evaluates .. math:: \mathrm{BLUR}(f, g) = \|\alpha (f - g) \|_2^2, or, in normalized form .. math:: \mathrm{BLUR_N}(f, g) = \frac{\|\alpha(f - g)\|^2_2} {\|\alpha f\|^2_2 + \|\alpha g\|^2_2}. The weighting function :math:`\alpha` is given as .. math:: \alpha(x) = e^{-\frac{1}{k} \beta_m(x)}, where :math:`\beta_m(x)` is the Euclidian distance transform of a given binary mask :math:`m`, and :math:`k` positive real number that controls the smoothness of the weighting function :math:`\alpha`. The weighting gives higher values to structures in the region of interest defined by the mask. The normalized variant takes values in :math:`[0, 1]`. """ from scipy.ndimage.morphology import distance_transform_edt if not hasattr(data, 'space'): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) if smoothness_factor is None: smoothness_factor = np.mean(data.shape) / 10 if mask is not None: mask = distance_transform_edt(1 - mask) mask = np.exp(-mask / smoothness_factor) return mean_squared_error(data, ground_truth, mask, normalized)
[ "def", "blurring", "(", "data", ",", "ground_truth", ",", "mask", "=", "None", ",", "normalized", "=", "False", ",", "smoothness_factor", "=", "None", ")", ":", "from", "scipy", ".", "ndimage", ".", "morphology", "import", "distance_transform_edt", "if", "no...
r"""Return weighted L2 distance, emphasizing regions defined by ``mask``. .. note:: If the mask argument is omitted, this FOM is equivalent to the mean squared error. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. mask : `array-like`, optional Binary mask to define ROI in which FOM evaluation is performed. normalized : bool, optional Boolean flag to switch between unormalized and normalized FOM. smoothness_factor : float, optional Positive real number. Higher value gives smoother weighting. Returns ------- blur : float FOM value, where a lower value means a better match. See Also -------- false_structures mean_squared_error Notes ----- The FOM evaluates .. math:: \mathrm{BLUR}(f, g) = \|\alpha (f - g) \|_2^2, or, in normalized form .. math:: \mathrm{BLUR_N}(f, g) = \frac{\|\alpha(f - g)\|^2_2} {\|\alpha f\|^2_2 + \|\alpha g\|^2_2}. The weighting function :math:`\alpha` is given as .. math:: \alpha(x) = e^{-\frac{1}{k} \beta_m(x)}, where :math:`\beta_m(x)` is the Euclidian distance transform of a given binary mask :math:`m`, and :math:`k` positive real number that controls the smoothness of the weighting function :math:`\alpha`. The weighting gives higher values to structures in the region of interest defined by the mask. The normalized variant takes values in :math:`[0, 1]`.
[ "r", "Return", "weighted", "L2", "distance", "emphasizing", "regions", "defined", "by", "mask", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/fom/supervised.py#L400-L474
231,579
odlgroup/odl
odl/contrib/fom/supervised.py
false_structures_mask
def false_structures_mask(foreground, smoothness_factor=None): """Return mask emphasizing areas outside ``foreground``. Parameters ---------- foreground : `Tensor` or `array-like` The region that should be de-emphasized. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. foreground : `FnBaseVector` The region that should be de-emphasized. smoothness_factor : float, optional Positive real number. Higher value gives smoother transition between foreground and its complement. Returns ------- result : `Tensor` or `numpy.ndarray` Euclidean distances of elements in ``foreground``. The return value is a `Tensor` if ``foreground`` is one, too, otherwise a NumPy array. Examples -------- >>> space = odl.uniform_discr(0, 1, 5) >>> foreground = space.element([0, 0, 1.0, 0, 0]) >>> mask = false_structures_mask(foreground) >>> np.asarray(mask) array([ 0.4, 0.2, 0. , 0.2, 0.4]) Raises ------ ValueError If foreground is all zero or all one, or contains values not in {0, 1}. Notes ----- This helper function computes the Euclidean distance transform from each point in ``foreground.space`` to ``foreground``. The weighting gives higher values to structures outside the foreground as defined by the mask. """ try: space = foreground.space has_space = True except AttributeError: has_space = False foreground = np.asarray(foreground) space = odl.tensor_space(foreground.shape, foreground.dtype) foreground = space.element(foreground) from scipy.ndimage.morphology import distance_transform_edt unique = np.unique(foreground) if not np.array_equiv(unique, [0., 1.]): raise ValueError('`foreground` is not a binary mask or has ' 'either only true or only false values {!r}' ''.format(unique)) result = distance_transform_edt( 1.0 - foreground, sampling=getattr(space, 'cell_sides', 1.0) ) if has_space: return space.element(result) else: return result
python
def false_structures_mask(foreground, smoothness_factor=None): try: space = foreground.space has_space = True except AttributeError: has_space = False foreground = np.asarray(foreground) space = odl.tensor_space(foreground.shape, foreground.dtype) foreground = space.element(foreground) from scipy.ndimage.morphology import distance_transform_edt unique = np.unique(foreground) if not np.array_equiv(unique, [0., 1.]): raise ValueError('`foreground` is not a binary mask or has ' 'either only true or only false values {!r}' ''.format(unique)) result = distance_transform_edt( 1.0 - foreground, sampling=getattr(space, 'cell_sides', 1.0) ) if has_space: return space.element(result) else: return result
[ "def", "false_structures_mask", "(", "foreground", ",", "smoothness_factor", "=", "None", ")", ":", "try", ":", "space", "=", "foreground", ".", "space", "has_space", "=", "True", "except", "AttributeError", ":", "has_space", "=", "False", "foreground", "=", "...
Return mask emphasizing areas outside ``foreground``. Parameters ---------- foreground : `Tensor` or `array-like` The region that should be de-emphasized. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. foreground : `FnBaseVector` The region that should be de-emphasized. smoothness_factor : float, optional Positive real number. Higher value gives smoother transition between foreground and its complement. Returns ------- result : `Tensor` or `numpy.ndarray` Euclidean distances of elements in ``foreground``. The return value is a `Tensor` if ``foreground`` is one, too, otherwise a NumPy array. Examples -------- >>> space = odl.uniform_discr(0, 1, 5) >>> foreground = space.element([0, 0, 1.0, 0, 0]) >>> mask = false_structures_mask(foreground) >>> np.asarray(mask) array([ 0.4, 0.2, 0. , 0.2, 0.4]) Raises ------ ValueError If foreground is all zero or all one, or contains values not in {0, 1}. Notes ----- This helper function computes the Euclidean distance transform from each point in ``foreground.space`` to ``foreground``. The weighting gives higher values to structures outside the foreground as defined by the mask.
[ "Return", "mask", "emphasizing", "areas", "outside", "foreground", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/fom/supervised.py#L477-L543
231,580
odlgroup/odl
odl/contrib/fom/supervised.py
ssim
def ssim(data, ground_truth, size=11, sigma=1.5, K1=0.01, K2=0.03, dynamic_range=None, normalized=False, force_lower_is_better=False): r"""Structural SIMilarity between ``data`` and ``ground_truth``. The SSIM takes value -1 for maximum dissimilarity and +1 for maximum similarity. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Structural_similarity>`_. Parameters ---------- data : `array-like` Input data to compare to the ground truth. ground_truth : `array-like` Reference to which ``data`` should be compared. size : odd int, optional Size in elements per axis of the Gaussian window that is used for all smoothing operations. sigma : positive float, optional Width of the Gaussian function used for smoothing. K1, K2 : positive float, optional Small constants to stabilize the result. See [Wan+2004] for details. dynamic_range : nonnegative float, optional Difference between the maximum and minimum value that the pixels can attain. Use 255 if pixel range is :math:`[0, 255]` and 1 if it is :math:`[0, 1]`. Default: `None`, obtain maximum and minimum from the ground truth. normalized : bool, optional If ``True``, the output values are mapped to the interval :math:`[0, 1]` (see `Notes` for details), otherwise return the original SSIM. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches by returning the negative of the SSIM, otherwise the (possibly normalized) SSIM is returned. If both `normalized` and `force_lower_is_better` are ``True``, then the order is reversed before mapping the outputs, so that the latter are still in the interval :math:`[0, 1]`. Returns ------- ssim : float FOM value, where a higher value means a better match if `force_lower_is_better` is ``False``. Notes ----- The SSIM is computed on small windows and then averaged over the whole image. The SSIM between two windows :math:`x` and :math:`y` of size :math:`N \times N` .. math:: SSIM(x,y) = \frac{(2\mu_x\mu_y + c_1)(2\sigma_{xy} + c_2)} {(\mu_x^2 + \mu_y^2 + c_1)(\sigma_x^2 + \sigma_y^2 + c_2)} where: * :math:`\mu_x`, :math:`\mu_y` is the mean of :math:`x` and :math:`y`, respectively. * :math:`\sigma_x`, :math:`\sigma_y` is the standard deviation of :math:`x` and :math:`y`, respectively. * :math:`\sigma_{xy}` the covariance of :math:`x` and :math:`y` * :math:`c_1 = (k_1L)^2`, :math:`c_2 = (k_2L)^2` where :math:`L` is the dynamic range of the image. The unnormalized values are contained in the interval :math:`[-1, 1]`, where 1 corresponds to a perfect match. The normalized values are given by .. math:: SSIM_{normalized}(x, y) = \frac{SSIM(x, y) + 1}{2} References ---------- [Wan+2004] Wang, Z, Bovik, AC, Sheikh, HR, and Simoncelli, EP. *Image Quality Assessment: From Error Visibility to Structural Similarity*. IEEE Transactions on Image Processing, 13.4 (2004), pp 600--612. """ from scipy.signal import fftconvolve data = np.asarray(data) ground_truth = np.asarray(ground_truth) # Compute gaussian on a `size`-sized grid in each axis coords = np.linspace(-(size - 1) / 2, (size - 1) / 2, size) grid = sparse_meshgrid(*([coords] * data.ndim)) window = np.exp(-(sum(xi ** 2 for xi in grid) / (2.0 * sigma ** 2))) window /= np.sum(window) def smoothen(img): """Smoothes an image by convolving with a window function.""" return fftconvolve(window, img, mode='valid') if dynamic_range is None: dynamic_range = np.max(ground_truth) - np.min(ground_truth) C1 = (K1 * dynamic_range) ** 2 C2 = (K2 * dynamic_range) ** 2 mu1 = smoothen(data) mu2 = smoothen(ground_truth) mu1_sq = mu1 * mu1 mu2_sq = mu2 * mu2 mu1_mu2 = mu1 * mu2 sigma1_sq = smoothen(data * data) - mu1_sq sigma2_sq = smoothen(ground_truth * ground_truth) - mu2_sq sigma12 = smoothen(data * ground_truth) - mu1_mu2 num = (2 * mu1_mu2 + C1) * (2 * sigma12 + C2) denom = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2) pointwise_ssim = num / denom result = np.mean(pointwise_ssim) if force_lower_is_better: result = -result if normalized: result = (result + 1.0) / 2.0 return result
python
def ssim(data, ground_truth, size=11, sigma=1.5, K1=0.01, K2=0.03, dynamic_range=None, normalized=False, force_lower_is_better=False): r"""Structural SIMilarity between ``data`` and ``ground_truth``. The SSIM takes value -1 for maximum dissimilarity and +1 for maximum similarity. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Structural_similarity>`_. Parameters ---------- data : `array-like` Input data to compare to the ground truth. ground_truth : `array-like` Reference to which ``data`` should be compared. size : odd int, optional Size in elements per axis of the Gaussian window that is used for all smoothing operations. sigma : positive float, optional Width of the Gaussian function used for smoothing. K1, K2 : positive float, optional Small constants to stabilize the result. See [Wan+2004] for details. dynamic_range : nonnegative float, optional Difference between the maximum and minimum value that the pixels can attain. Use 255 if pixel range is :math:`[0, 255]` and 1 if it is :math:`[0, 1]`. Default: `None`, obtain maximum and minimum from the ground truth. normalized : bool, optional If ``True``, the output values are mapped to the interval :math:`[0, 1]` (see `Notes` for details), otherwise return the original SSIM. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches by returning the negative of the SSIM, otherwise the (possibly normalized) SSIM is returned. If both `normalized` and `force_lower_is_better` are ``True``, then the order is reversed before mapping the outputs, so that the latter are still in the interval :math:`[0, 1]`. Returns ------- ssim : float FOM value, where a higher value means a better match if `force_lower_is_better` is ``False``. Notes ----- The SSIM is computed on small windows and then averaged over the whole image. The SSIM between two windows :math:`x` and :math:`y` of size :math:`N \times N` .. math:: SSIM(x,y) = \frac{(2\mu_x\mu_y + c_1)(2\sigma_{xy} + c_2)} {(\mu_x^2 + \mu_y^2 + c_1)(\sigma_x^2 + \sigma_y^2 + c_2)} where: * :math:`\mu_x`, :math:`\mu_y` is the mean of :math:`x` and :math:`y`, respectively. * :math:`\sigma_x`, :math:`\sigma_y` is the standard deviation of :math:`x` and :math:`y`, respectively. * :math:`\sigma_{xy}` the covariance of :math:`x` and :math:`y` * :math:`c_1 = (k_1L)^2`, :math:`c_2 = (k_2L)^2` where :math:`L` is the dynamic range of the image. The unnormalized values are contained in the interval :math:`[-1, 1]`, where 1 corresponds to a perfect match. The normalized values are given by .. math:: SSIM_{normalized}(x, y) = \frac{SSIM(x, y) + 1}{2} References ---------- [Wan+2004] Wang, Z, Bovik, AC, Sheikh, HR, and Simoncelli, EP. *Image Quality Assessment: From Error Visibility to Structural Similarity*. IEEE Transactions on Image Processing, 13.4 (2004), pp 600--612. """ from scipy.signal import fftconvolve data = np.asarray(data) ground_truth = np.asarray(ground_truth) # Compute gaussian on a `size`-sized grid in each axis coords = np.linspace(-(size - 1) / 2, (size - 1) / 2, size) grid = sparse_meshgrid(*([coords] * data.ndim)) window = np.exp(-(sum(xi ** 2 for xi in grid) / (2.0 * sigma ** 2))) window /= np.sum(window) def smoothen(img): """Smoothes an image by convolving with a window function.""" return fftconvolve(window, img, mode='valid') if dynamic_range is None: dynamic_range = np.max(ground_truth) - np.min(ground_truth) C1 = (K1 * dynamic_range) ** 2 C2 = (K2 * dynamic_range) ** 2 mu1 = smoothen(data) mu2 = smoothen(ground_truth) mu1_sq = mu1 * mu1 mu2_sq = mu2 * mu2 mu1_mu2 = mu1 * mu2 sigma1_sq = smoothen(data * data) - mu1_sq sigma2_sq = smoothen(ground_truth * ground_truth) - mu2_sq sigma12 = smoothen(data * ground_truth) - mu1_mu2 num = (2 * mu1_mu2 + C1) * (2 * sigma12 + C2) denom = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2) pointwise_ssim = num / denom result = np.mean(pointwise_ssim) if force_lower_is_better: result = -result if normalized: result = (result + 1.0) / 2.0 return result
[ "def", "ssim", "(", "data", ",", "ground_truth", ",", "size", "=", "11", ",", "sigma", "=", "1.5", ",", "K1", "=", "0.01", ",", "K2", "=", "0.03", ",", "dynamic_range", "=", "None", ",", "normalized", "=", "False", ",", "force_lower_is_better", "=", ...
r"""Structural SIMilarity between ``data`` and ``ground_truth``. The SSIM takes value -1 for maximum dissimilarity and +1 for maximum similarity. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Structural_similarity>`_. Parameters ---------- data : `array-like` Input data to compare to the ground truth. ground_truth : `array-like` Reference to which ``data`` should be compared. size : odd int, optional Size in elements per axis of the Gaussian window that is used for all smoothing operations. sigma : positive float, optional Width of the Gaussian function used for smoothing. K1, K2 : positive float, optional Small constants to stabilize the result. See [Wan+2004] for details. dynamic_range : nonnegative float, optional Difference between the maximum and minimum value that the pixels can attain. Use 255 if pixel range is :math:`[0, 255]` and 1 if it is :math:`[0, 1]`. Default: `None`, obtain maximum and minimum from the ground truth. normalized : bool, optional If ``True``, the output values are mapped to the interval :math:`[0, 1]` (see `Notes` for details), otherwise return the original SSIM. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches by returning the negative of the SSIM, otherwise the (possibly normalized) SSIM is returned. If both `normalized` and `force_lower_is_better` are ``True``, then the order is reversed before mapping the outputs, so that the latter are still in the interval :math:`[0, 1]`. Returns ------- ssim : float FOM value, where a higher value means a better match if `force_lower_is_better` is ``False``. Notes ----- The SSIM is computed on small windows and then averaged over the whole image. The SSIM between two windows :math:`x` and :math:`y` of size :math:`N \times N` .. math:: SSIM(x,y) = \frac{(2\mu_x\mu_y + c_1)(2\sigma_{xy} + c_2)} {(\mu_x^2 + \mu_y^2 + c_1)(\sigma_x^2 + \sigma_y^2 + c_2)} where: * :math:`\mu_x`, :math:`\mu_y` is the mean of :math:`x` and :math:`y`, respectively. * :math:`\sigma_x`, :math:`\sigma_y` is the standard deviation of :math:`x` and :math:`y`, respectively. * :math:`\sigma_{xy}` the covariance of :math:`x` and :math:`y` * :math:`c_1 = (k_1L)^2`, :math:`c_2 = (k_2L)^2` where :math:`L` is the dynamic range of the image. The unnormalized values are contained in the interval :math:`[-1, 1]`, where 1 corresponds to a perfect match. The normalized values are given by .. math:: SSIM_{normalized}(x, y) = \frac{SSIM(x, y) + 1}{2} References ---------- [Wan+2004] Wang, Z, Bovik, AC, Sheikh, HR, and Simoncelli, EP. *Image Quality Assessment: From Error Visibility to Structural Similarity*. IEEE Transactions on Image Processing, 13.4 (2004), pp 600--612.
[ "r", "Structural", "SIMilarity", "between", "data", "and", "ground_truth", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/fom/supervised.py#L546-L668
231,581
odlgroup/odl
odl/contrib/fom/supervised.py
psnr
def psnr(data, ground_truth, use_zscore=False, force_lower_is_better=False): """Return the Peak Signal-to-Noise Ratio of ``data`` wrt ``ground_truth``. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. use_zscore : bool If ``True``, normalize ``data`` and ``ground_truth`` to have zero mean and unit variance before comparison. force_lower_is_better : bool If ``True``, then lower value indicates better fit. In this case the output is negated. Returns ------- psnr : float FOM value, where a higher value means a better match. Examples -------- Compute the PSNR for two vectors: >>> spc = odl.rn(5) >>> data = spc.element([1, 1, 1, 1, 1]) >>> ground_truth = spc.element([1, 1, 1, 1, 2]) >>> result = psnr(data, ground_truth) >>> print('{:.3f}'.format(result)) 13.010 If data == ground_truth, the result is positive infinity: >>> psnr(ground_truth, ground_truth) inf With ``use_zscore=True``, scaling differences and constant offsets are ignored: >>> (psnr(data, ground_truth, use_zscore=True) == ... psnr(data, 3 + 4 * ground_truth, use_zscore=True)) True """ if use_zscore: data = odl.util.zscore(data) ground_truth = odl.util.zscore(ground_truth) mse = mean_squared_error(data, ground_truth) max_true = np.max(np.abs(ground_truth)) if mse == 0: result = np.inf elif max_true == 0: result = -np.inf else: result = 20 * np.log10(max_true) - 10 * np.log10(mse) if force_lower_is_better: return -result else: return result
python
def psnr(data, ground_truth, use_zscore=False, force_lower_is_better=False): if use_zscore: data = odl.util.zscore(data) ground_truth = odl.util.zscore(ground_truth) mse = mean_squared_error(data, ground_truth) max_true = np.max(np.abs(ground_truth)) if mse == 0: result = np.inf elif max_true == 0: result = -np.inf else: result = 20 * np.log10(max_true) - 10 * np.log10(mse) if force_lower_is_better: return -result else: return result
[ "def", "psnr", "(", "data", ",", "ground_truth", ",", "use_zscore", "=", "False", ",", "force_lower_is_better", "=", "False", ")", ":", "if", "use_zscore", ":", "data", "=", "odl", ".", "util", ".", "zscore", "(", "data", ")", "ground_truth", "=", "odl",...
Return the Peak Signal-to-Noise Ratio of ``data`` wrt ``ground_truth``. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which ``data`` should be compared. use_zscore : bool If ``True``, normalize ``data`` and ``ground_truth`` to have zero mean and unit variance before comparison. force_lower_is_better : bool If ``True``, then lower value indicates better fit. In this case the output is negated. Returns ------- psnr : float FOM value, where a higher value means a better match. Examples -------- Compute the PSNR for two vectors: >>> spc = odl.rn(5) >>> data = spc.element([1, 1, 1, 1, 1]) >>> ground_truth = spc.element([1, 1, 1, 1, 2]) >>> result = psnr(data, ground_truth) >>> print('{:.3f}'.format(result)) 13.010 If data == ground_truth, the result is positive infinity: >>> psnr(ground_truth, ground_truth) inf With ``use_zscore=True``, scaling differences and constant offsets are ignored: >>> (psnr(data, ground_truth, use_zscore=True) == ... psnr(data, 3 + 4 * ground_truth, use_zscore=True)) True
[ "Return", "the", "Peak", "Signal", "-", "to", "-", "Noise", "Ratio", "of", "data", "wrt", "ground_truth", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/fom/supervised.py#L671-L736
231,582
odlgroup/odl
odl/contrib/fom/supervised.py
haarpsi
def haarpsi(data, ground_truth, a=4.2, c=None): r"""Haar-Wavelet based perceptual similarity index FOM. This function evaluates the structural similarity between two images based on edge features along the coordinate axes, analyzed with two wavelet filter levels. See `[Rei+2016] <https://arxiv.org/abs/1607.06140>`_ and the Notes section for further details. Parameters ---------- data : 2D array-like The image to compare to the ground truth. ground_truth : 2D array-like The true image with which to compare ``data``. It must have the same shape as ``data``. a : positive float, optional Parameter in the logistic function. Larger value leads to a steeper curve, thus lowering the threshold for an input to be mapped to an output close to 1. See Notes for details. The default value 4.2 is taken from the referenced paper. c : positive float, optional Constant determining the score of maximally dissimilar values. Smaller constant means higher penalty for dissimilarity. See `haarpsi_similarity_map` for details. For ``None``, the value is chosen as ``3 * sqrt(max(abs(ground_truth)))``. Returns ------- haarpsi : float between 0 and 1 The similarity score, where a higher score means a better match. See Notes for details. See Also -------- haarpsi_similarity_map haarpsi_weight_map Notes ----- For input images :math:`f_1, f_2`, the HaarPSI score is defined as .. math:: \mathrm{HaarPSI}_{f_1, f_2} = l_a^{-1} \left( \frac{ \sum_x \sum_{k=1}^2 \mathrm{HS}_{f_1, f_2}^{(k)}(x) \cdot \mathrm{W}_{f_1, f_2}^{(k)}(x)}{ \sum_x \sum_{k=1}^2 \mathrm{W}_{f_1, f_2}^{(k)}(x)} \right)^2 see `[Rei+2016] <https://arxiv.org/abs/1607.06140>`_ equation (12). For the definitions of the constituting functions, see - `haarpsi_similarity_map` for :math:`\mathrm{HS}_{f_1, f_2}^{(k)}`, - `haarpsi_weight_map` for :math:`\mathrm{W}_{f_1, f_2}^{(k)}`. References ---------- [Rei+2016] Reisenhofer, R, Bosse, S, Kutyniok, G, and Wiegand, T. *A Haar Wavelet-Based Perceptual Similarity Index for Image Quality Assessment*. arXiv:1607.06140 [cs], Jul. 2016. """ import scipy.special from odl.contrib.fom.util import haarpsi_similarity_map, haarpsi_weight_map if c is None: c = 3 * np.sqrt(np.max(np.abs(ground_truth))) lsim_horiz = haarpsi_similarity_map(data, ground_truth, axis=0, c=c, a=a) lsim_vert = haarpsi_similarity_map(data, ground_truth, axis=1, c=c, a=a) wmap_horiz = haarpsi_weight_map(data, ground_truth, axis=0) wmap_vert = haarpsi_weight_map(data, ground_truth, axis=1) numer = np.sum(lsim_horiz * wmap_horiz + lsim_vert * wmap_vert) denom = np.sum(wmap_horiz + wmap_vert) return (scipy.special.logit(numer / denom) / a) ** 2
python
def haarpsi(data, ground_truth, a=4.2, c=None): r"""Haar-Wavelet based perceptual similarity index FOM. This function evaluates the structural similarity between two images based on edge features along the coordinate axes, analyzed with two wavelet filter levels. See `[Rei+2016] <https://arxiv.org/abs/1607.06140>`_ and the Notes section for further details. Parameters ---------- data : 2D array-like The image to compare to the ground truth. ground_truth : 2D array-like The true image with which to compare ``data``. It must have the same shape as ``data``. a : positive float, optional Parameter in the logistic function. Larger value leads to a steeper curve, thus lowering the threshold for an input to be mapped to an output close to 1. See Notes for details. The default value 4.2 is taken from the referenced paper. c : positive float, optional Constant determining the score of maximally dissimilar values. Smaller constant means higher penalty for dissimilarity. See `haarpsi_similarity_map` for details. For ``None``, the value is chosen as ``3 * sqrt(max(abs(ground_truth)))``. Returns ------- haarpsi : float between 0 and 1 The similarity score, where a higher score means a better match. See Notes for details. See Also -------- haarpsi_similarity_map haarpsi_weight_map Notes ----- For input images :math:`f_1, f_2`, the HaarPSI score is defined as .. math:: \mathrm{HaarPSI}_{f_1, f_2} = l_a^{-1} \left( \frac{ \sum_x \sum_{k=1}^2 \mathrm{HS}_{f_1, f_2}^{(k)}(x) \cdot \mathrm{W}_{f_1, f_2}^{(k)}(x)}{ \sum_x \sum_{k=1}^2 \mathrm{W}_{f_1, f_2}^{(k)}(x)} \right)^2 see `[Rei+2016] <https://arxiv.org/abs/1607.06140>`_ equation (12). For the definitions of the constituting functions, see - `haarpsi_similarity_map` for :math:`\mathrm{HS}_{f_1, f_2}^{(k)}`, - `haarpsi_weight_map` for :math:`\mathrm{W}_{f_1, f_2}^{(k)}`. References ---------- [Rei+2016] Reisenhofer, R, Bosse, S, Kutyniok, G, and Wiegand, T. *A Haar Wavelet-Based Perceptual Similarity Index for Image Quality Assessment*. arXiv:1607.06140 [cs], Jul. 2016. """ import scipy.special from odl.contrib.fom.util import haarpsi_similarity_map, haarpsi_weight_map if c is None: c = 3 * np.sqrt(np.max(np.abs(ground_truth))) lsim_horiz = haarpsi_similarity_map(data, ground_truth, axis=0, c=c, a=a) lsim_vert = haarpsi_similarity_map(data, ground_truth, axis=1, c=c, a=a) wmap_horiz = haarpsi_weight_map(data, ground_truth, axis=0) wmap_vert = haarpsi_weight_map(data, ground_truth, axis=1) numer = np.sum(lsim_horiz * wmap_horiz + lsim_vert * wmap_vert) denom = np.sum(wmap_horiz + wmap_vert) return (scipy.special.logit(numer / denom) / a) ** 2
[ "def", "haarpsi", "(", "data", ",", "ground_truth", ",", "a", "=", "4.2", ",", "c", "=", "None", ")", ":", "import", "scipy", ".", "special", "from", "odl", ".", "contrib", ".", "fom", ".", "util", "import", "haarpsi_similarity_map", ",", "haarpsi_weight...
r"""Haar-Wavelet based perceptual similarity index FOM. This function evaluates the structural similarity between two images based on edge features along the coordinate axes, analyzed with two wavelet filter levels. See `[Rei+2016] <https://arxiv.org/abs/1607.06140>`_ and the Notes section for further details. Parameters ---------- data : 2D array-like The image to compare to the ground truth. ground_truth : 2D array-like The true image with which to compare ``data``. It must have the same shape as ``data``. a : positive float, optional Parameter in the logistic function. Larger value leads to a steeper curve, thus lowering the threshold for an input to be mapped to an output close to 1. See Notes for details. The default value 4.2 is taken from the referenced paper. c : positive float, optional Constant determining the score of maximally dissimilar values. Smaller constant means higher penalty for dissimilarity. See `haarpsi_similarity_map` for details. For ``None``, the value is chosen as ``3 * sqrt(max(abs(ground_truth)))``. Returns ------- haarpsi : float between 0 and 1 The similarity score, where a higher score means a better match. See Notes for details. See Also -------- haarpsi_similarity_map haarpsi_weight_map Notes ----- For input images :math:`f_1, f_2`, the HaarPSI score is defined as .. math:: \mathrm{HaarPSI}_{f_1, f_2} = l_a^{-1} \left( \frac{ \sum_x \sum_{k=1}^2 \mathrm{HS}_{f_1, f_2}^{(k)}(x) \cdot \mathrm{W}_{f_1, f_2}^{(k)}(x)}{ \sum_x \sum_{k=1}^2 \mathrm{W}_{f_1, f_2}^{(k)}(x)} \right)^2 see `[Rei+2016] <https://arxiv.org/abs/1607.06140>`_ equation (12). For the definitions of the constituting functions, see - `haarpsi_similarity_map` for :math:`\mathrm{HS}_{f_1, f_2}^{(k)}`, - `haarpsi_weight_map` for :math:`\mathrm{W}_{f_1, f_2}^{(k)}`. References ---------- [Rei+2016] Reisenhofer, R, Bosse, S, Kutyniok, G, and Wiegand, T. *A Haar Wavelet-Based Perceptual Similarity Index for Image Quality Assessment*. arXiv:1607.06140 [cs], Jul. 2016.
[ "r", "Haar", "-", "Wavelet", "based", "perceptual", "similarity", "index", "FOM", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/fom/supervised.py#L739-L819
231,583
odlgroup/odl
odl/tomo/geometry/detector.py
Detector.surface_normal
def surface_normal(self, param): """Unit vector perpendicular to the detector surface at ``param``. The orientation is chosen as follows: - In 2D, the system ``(normal, tangent)`` should be right-handed. - In 3D, the system ``(tangent[0], tangent[1], normal)`` should be right-handed. Here, ``tangent`` is the return value of `surface_deriv` at ``param``. Parameters ---------- param : `array-like` or sequence Parameter value(s) at which to evaluate. If ``ndim >= 2``, a sequence of length `ndim` must be provided. Returns ------- normal : `numpy.ndarray` Unit vector(s) perpendicular to the detector surface at ``param``. If ``param`` is a single parameter, an array of shape ``(space_ndim,)`` representing a single vector is returned. Otherwise the shape of the returned array is - ``param.shape + (space_ndim,)`` if `ndim` is 1, - ``param.shape[:-1] + (space_ndim,)`` otherwise. """ # Checking is done by `surface_deriv` if self.ndim == 1 and self.space_ndim == 2: return -perpendicular_vector(self.surface_deriv(param)) elif self.ndim == 2 and self.space_ndim == 3: deriv = self.surface_deriv(param) if deriv.ndim > 2: # Vectorized, need to reshape (N, 2, 3) to (2, N, 3) deriv = moveaxis(deriv, -2, 0) normal = np.cross(*deriv, axis=-1) normal /= np.linalg.norm(normal, axis=-1, keepdims=True) return normal else: raise NotImplementedError( 'no default implementation of `surface_normal` available ' 'for `ndim = {}` and `space_ndim = {}`' ''.format(self.ndim, self.space_ndim))
python
def surface_normal(self, param): # Checking is done by `surface_deriv` if self.ndim == 1 and self.space_ndim == 2: return -perpendicular_vector(self.surface_deriv(param)) elif self.ndim == 2 and self.space_ndim == 3: deriv = self.surface_deriv(param) if deriv.ndim > 2: # Vectorized, need to reshape (N, 2, 3) to (2, N, 3) deriv = moveaxis(deriv, -2, 0) normal = np.cross(*deriv, axis=-1) normal /= np.linalg.norm(normal, axis=-1, keepdims=True) return normal else: raise NotImplementedError( 'no default implementation of `surface_normal` available ' 'for `ndim = {}` and `space_ndim = {}`' ''.format(self.ndim, self.space_ndim))
[ "def", "surface_normal", "(", "self", ",", "param", ")", ":", "# Checking is done by `surface_deriv`", "if", "self", ".", "ndim", "==", "1", "and", "self", ".", "space_ndim", "==", "2", ":", "return", "-", "perpendicular_vector", "(", "self", ".", "surface_der...
Unit vector perpendicular to the detector surface at ``param``. The orientation is chosen as follows: - In 2D, the system ``(normal, tangent)`` should be right-handed. - In 3D, the system ``(tangent[0], tangent[1], normal)`` should be right-handed. Here, ``tangent`` is the return value of `surface_deriv` at ``param``. Parameters ---------- param : `array-like` or sequence Parameter value(s) at which to evaluate. If ``ndim >= 2``, a sequence of length `ndim` must be provided. Returns ------- normal : `numpy.ndarray` Unit vector(s) perpendicular to the detector surface at ``param``. If ``param`` is a single parameter, an array of shape ``(space_ndim,)`` representing a single vector is returned. Otherwise the shape of the returned array is - ``param.shape + (space_ndim,)`` if `ndim` is 1, - ``param.shape[:-1] + (space_ndim,)`` otherwise.
[ "Unit", "vector", "perpendicular", "to", "the", "detector", "surface", "at", "param", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/geometry/detector.py#L153-L199
231,584
odlgroup/odl
odl/tomo/geometry/detector.py
Detector.surface_measure
def surface_measure(self, param): """Density function of the surface measure. This is the default implementation relying on the `surface_deriv` method. For a detector with `ndim` equal to 1, the density is given by the `Arc length`_, for a surface with `ndim` 2 in a 3D space, it is the length of the cross product of the partial derivatives of the parametrization, see Wikipedia's `Surface area`_ article. Parameters ---------- param : `array-like` or sequence Parameter value(s) at which to evaluate. If ``ndim >= 2``, a sequence of length `ndim` must be provided. Returns ------- measure : float or `numpy.ndarray` The density value(s) at the given parameter(s). If a single parameter is provided, a float is returned. Otherwise, an array is returned with shape - ``param.shape`` if `ndim` is 1, - ``broadcast(*param).shape`` otherwise. References ---------- .. _Arc length: https://en.wikipedia.org/wiki/Curve#Lengths_of_curves .. _Surface area: https://en.wikipedia.org/wiki/Surface_area """ # Checking is done by `surface_deriv` if self.ndim == 1: scalar_out = (np.shape(param) == ()) measure = np.linalg.norm(self.surface_deriv(param), axis=-1) if scalar_out: measure = float(measure) return measure elif self.ndim == 2 and self.space_ndim == 3: scalar_out = (np.shape(param) == (2,)) deriv = self.surface_deriv(param) if deriv.ndim > 2: # Vectorized, need to reshape (N, 2, 3) to (2, N, 3) deriv = moveaxis(deriv, -2, 0) cross = np.cross(*deriv, axis=-1) measure = np.linalg.norm(cross, axis=-1) if scalar_out: measure = float(measure) return measure else: raise NotImplementedError( 'no default implementation of `surface_measure` available ' 'for `ndim={}` and `space_ndim={}`' ''.format(self.ndim, self.space_ndim))
python
def surface_measure(self, param): # Checking is done by `surface_deriv` if self.ndim == 1: scalar_out = (np.shape(param) == ()) measure = np.linalg.norm(self.surface_deriv(param), axis=-1) if scalar_out: measure = float(measure) return measure elif self.ndim == 2 and self.space_ndim == 3: scalar_out = (np.shape(param) == (2,)) deriv = self.surface_deriv(param) if deriv.ndim > 2: # Vectorized, need to reshape (N, 2, 3) to (2, N, 3) deriv = moveaxis(deriv, -2, 0) cross = np.cross(*deriv, axis=-1) measure = np.linalg.norm(cross, axis=-1) if scalar_out: measure = float(measure) return measure else: raise NotImplementedError( 'no default implementation of `surface_measure` available ' 'for `ndim={}` and `space_ndim={}`' ''.format(self.ndim, self.space_ndim))
[ "def", "surface_measure", "(", "self", ",", "param", ")", ":", "# Checking is done by `surface_deriv`", "if", "self", ".", "ndim", "==", "1", ":", "scalar_out", "=", "(", "np", ".", "shape", "(", "param", ")", "==", "(", ")", ")", "measure", "=", "np", ...
Density function of the surface measure. This is the default implementation relying on the `surface_deriv` method. For a detector with `ndim` equal to 1, the density is given by the `Arc length`_, for a surface with `ndim` 2 in a 3D space, it is the length of the cross product of the partial derivatives of the parametrization, see Wikipedia's `Surface area`_ article. Parameters ---------- param : `array-like` or sequence Parameter value(s) at which to evaluate. If ``ndim >= 2``, a sequence of length `ndim` must be provided. Returns ------- measure : float or `numpy.ndarray` The density value(s) at the given parameter(s). If a single parameter is provided, a float is returned. Otherwise, an array is returned with shape - ``param.shape`` if `ndim` is 1, - ``broadcast(*param).shape`` otherwise. References ---------- .. _Arc length: https://en.wikipedia.org/wiki/Curve#Lengths_of_curves .. _Surface area: https://en.wikipedia.org/wiki/Surface_area
[ "Density", "function", "of", "the", "surface", "measure", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/geometry/detector.py#L201-L259
231,585
odlgroup/odl
odl/tomo/geometry/detector.py
CircularDetector.surface_measure
def surface_measure(self, param): """Return the arc length measure at ``param``. This is a constant function evaluating to `radius` everywhere. Parameters ---------- param : float or `array-like` Parameter value(s) at which to evaluate. Returns ------- measure : float or `numpy.ndarray` Constant value(s) of the arc length measure at ``param``. If ``param`` is a single parameter, a float is returned, otherwise an array of shape ``param.shape``. See Also -------- surface surface_deriv Examples -------- The method works with a single parameter, resulting in a float: >>> part = odl.uniform_partition(-np.pi / 2, np.pi / 2, 10) >>> det = CircularDetector(part, axis=[1, 0], radius=2) >>> det.surface_measure(0) 2.0 >>> det.surface_measure(np.pi / 2) 2.0 It is also vectorized, i.e., it can be called with multiple parameters at once (or an n-dimensional array of parameters): >>> det.surface_measure([0, np.pi / 2]) array([ 2., 2.]) >>> det.surface_measure(np.zeros((4, 5))).shape (4, 5) """ scalar_out = (np.shape(param) == ()) param = np.array(param, dtype=float, copy=False, ndmin=1) if self.check_bounds and not is_inside_bounds(param, self.params): raise ValueError('`param` {} not in the valid range ' '{}'.format(param, self.params)) if scalar_out: return self.radius else: return self.radius * np.ones(param.shape)
python
def surface_measure(self, param): scalar_out = (np.shape(param) == ()) param = np.array(param, dtype=float, copy=False, ndmin=1) if self.check_bounds and not is_inside_bounds(param, self.params): raise ValueError('`param` {} not in the valid range ' '{}'.format(param, self.params)) if scalar_out: return self.radius else: return self.radius * np.ones(param.shape)
[ "def", "surface_measure", "(", "self", ",", "param", ")", ":", "scalar_out", "=", "(", "np", ".", "shape", "(", "param", ")", "==", "(", ")", ")", "param", "=", "np", ".", "array", "(", "param", ",", "dtype", "=", "float", ",", "copy", "=", "Fals...
Return the arc length measure at ``param``. This is a constant function evaluating to `radius` everywhere. Parameters ---------- param : float or `array-like` Parameter value(s) at which to evaluate. Returns ------- measure : float or `numpy.ndarray` Constant value(s) of the arc length measure at ``param``. If ``param`` is a single parameter, a float is returned, otherwise an array of shape ``param.shape``. See Also -------- surface surface_deriv Examples -------- The method works with a single parameter, resulting in a float: >>> part = odl.uniform_partition(-np.pi / 2, np.pi / 2, 10) >>> det = CircularDetector(part, axis=[1, 0], radius=2) >>> det.surface_measure(0) 2.0 >>> det.surface_measure(np.pi / 2) 2.0 It is also vectorized, i.e., it can be called with multiple parameters at once (or an n-dimensional array of parameters): >>> det.surface_measure([0, np.pi / 2]) array([ 2., 2.]) >>> det.surface_measure(np.zeros((4, 5))).shape (4, 5)
[ "Return", "the", "arc", "length", "measure", "at", "param", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/geometry/detector.py#L833-L883
231,586
odlgroup/odl
odl/solvers/nonsmooth/alternating_dual_updates.py
adupdates
def adupdates(x, g, L, stepsize, inner_stepsizes, niter, random=False, callback=None, callback_loop='outer'): r"""Alternating Dual updates method. The Alternating Dual (AD) updates method of McGaffin and Fessler `[MF2015] <http://ieeexplore.ieee.org/document/7271047/>`_ is designed to solve an optimization problem of the form :: min_x [ sum_i g_i(L_i x) ] where ``g_i`` are proper, convex and lower semicontinuous functions and ``L_i`` are linear `Operator` s. Parameters ---------- g : sequence of `Functional` s All functions need to provide a `Functional.convex_conj` with a `Functional.proximal` factory. L : sequence of `Operator` s Length of ``L`` must equal the length of ``g``. x : `LinearSpaceElement` Initial point, updated in-place. stepsize : positive float The stepsize for the outer (proximal point) iteration. The theory guarantees convergence for any positive real number, but the performance might depend on the choice of a good stepsize. inner_stepsizes : sequence of stepsizes Parameters determining the stepsizes for the inner iterations. Must be matched with the norms of ``L``, and convergence is guaranteed if the ``inner_stepsizes`` are small enough. See the Notes section for details. niter : int Number of (outer) iterations. random : bool, optional If `True`, the order of the dual upgdates is chosen randomly, otherwise the order provided by the lists ``g``, ``L`` and ``inner_stepsizes`` is used. callback : callable, optional Function called with the current iterate after each iteration. callback_loop : {'inner', 'outer'}, optional If 'inner', the ``callback`` function is called after each inner iteration, i.e., after each dual update. If 'outer', the ``callback`` function is called after each outer iteration, i.e., after each primal update. Notes ----- The algorithm as implemented here is described in the article [MF2015], where it is applied to a tomography problem. It solves the problem .. math:: \min_x \sum_{i=1}^m g_i(L_i x), where :math:`g_i` are proper, convex and lower semicontinuous functions and :math:`L_i` are linear, continuous operators for :math:`i = 1, \ldots, m`. In an outer iteration, the solution is found iteratively by an iteration .. math:: x_{n+1} = \mathrm{arg\,min}_x \sum_{i=1}^m g_i(L_i x) + \frac{\mu}{2} \|x - x_n\|^2 with some ``stepsize`` parameter :math:`\mu > 0` according to the proximal point algorithm. In the inner iteration, dual variables are introduced for each of the components of the sum. The Lagrangian of the problem is given by .. math:: S_n(x; v_1, \ldots, v_m) = \sum_{i=1}^m (\langle v_i, L_i x \rangle - g_i^*(v_i)) + \frac{\mu}{2} \|x - x_n\|^2. Given the dual variables, the new primal variable :math:`x_{n+1}` can be calculated by directly minimizing :math:`S_n` with respect to :math:`x`. This corresponds to the formula .. math:: x_{n+1} = x_n - \frac{1}{\mu} \sum_{i=1}^m L_i^* v_i. The dual updates are executed according to the following rule: .. math:: v_i^+ = \mathrm{Prox}^{\mu M_i^{-1}}_{g_i^*} (v_i + \mu M_i^{-1} L_i x_{n+1}), where :math:`x_{n+1}` is given by the formula above and :math:`M_i` is a diagonal matrix with positive diagonal entries such that :math:`M_i - L_i L_i^*` is positive semidefinite. The variable ``inner_stepsizes`` is chosen as a stepsize to the `Functional.proximal` to the `Functional.convex_conj` of each of the ``g`` s after multiplying with ``stepsize``. The ``inner_stepsizes`` contain the elements of :math:`M_i^{-1}` in one of the following ways: * Setting ``inner_stepsizes[i]`` a positive float :math:`\gamma` corresponds to the choice :math:`M_i^{-1} = \gamma \mathrm{Id}`. * Assume that ``g_i`` is a `SeparableSum`, then setting ``inner_stepsizes[i]`` a list :math:`(\gamma_1, \ldots, \gamma_k)` of positive floats corresponds to the choice of a block-diagonal matrix :math:`M_i^{-1}`, where each block corresponds to one of the space components and equals :math:`\gamma_i \mathrm{Id}`. * Assume that ``g_i`` is an `L1Norm` or an `L2NormSquared`, then setting ``inner_stepsizes[i]`` a ``g_i.domain.element`` :math:`z` corresponds to the choice :math:`M_i^{-1} = \mathrm{diag}(z)`. References ---------- [MF2015] McGaffin, M G, and Fessler, J A. *Alternating dual updates algorithm for X-ray CT reconstruction on the GPU*. IEEE Transactions on Computational Imaging, 1.3 (2015), pp 186--199. """ # Check the lenghts of the lists (= number of dual variables) length = len(g) if len(L) != length: raise ValueError('`len(L)` should equal `len(g)`, but {} != {}' ''.format(len(L), length)) if len(inner_stepsizes) != length: raise ValueError('len(`inner_stepsizes`) should equal `len(g)`, ' ' but {} != {}'.format(len(inner_stepsizes), length)) # Check if operators have a common domain # (the space of the primal variable): domain = L[0].domain if any(opi.domain != domain for opi in L): raise ValueError('domains of `L` are not all equal') # Check if range of the operators equals domain of the functionals ranges = [opi.range for opi in L] if any(L[i].range != g[i].domain for i in range(length)): raise ValueError('L[i].range` should equal `g.domain`') # Normalize string callback_loop, callback_loop_in = str(callback_loop).lower(), callback_loop if callback_loop not in ('inner', 'outer'): raise ValueError('`callback_loop` {!r} not understood' ''.format(callback_loop_in)) # Initialization of the dual variables duals = [space.zero() for space in ranges] # Reusable elements in the ranges, one per type of space unique_ranges = set(ranges) tmp_rans = {ran: ran.element() for ran in unique_ranges} # Prepare the proximal operators. Since the stepsize does not vary over # the iterations, we always use the same proximal operator. proxs = [func.convex_conj.proximal(stepsize * inner_ss if np.isscalar(inner_ss) else stepsize * np.asarray(inner_ss)) for (func, inner_ss) in zip(g, inner_stepsizes)] # Iteratively find a solution for _ in range(niter): # Update x = x - 1/stepsize * sum([ops[i].adjoint(duals[i]) # for i in range(length)]) for i in range(length): x -= (1.0 / stepsize) * L[i].adjoint(duals[i]) if random: rng = np.random.permutation(range(length)) else: rng = range(length) for j in rng: step = (stepsize * inner_stepsizes[j] if np.isscalar(inner_stepsizes[j]) else stepsize * np.asarray(inner_stepsizes[j])) arg = duals[j] + step * L[j](x) tmp_ran = tmp_rans[L[j].range] proxs[j](arg, out=tmp_ran) x -= 1.0 / stepsize * L[j].adjoint(tmp_ran - duals[j]) duals[j].assign(tmp_ran) if callback is not None and callback_loop == 'inner': callback(x) if callback is not None and callback_loop == 'outer': callback(x)
python
def adupdates(x, g, L, stepsize, inner_stepsizes, niter, random=False, callback=None, callback_loop='outer'): r"""Alternating Dual updates method. The Alternating Dual (AD) updates method of McGaffin and Fessler `[MF2015] <http://ieeexplore.ieee.org/document/7271047/>`_ is designed to solve an optimization problem of the form :: min_x [ sum_i g_i(L_i x) ] where ``g_i`` are proper, convex and lower semicontinuous functions and ``L_i`` are linear `Operator` s. Parameters ---------- g : sequence of `Functional` s All functions need to provide a `Functional.convex_conj` with a `Functional.proximal` factory. L : sequence of `Operator` s Length of ``L`` must equal the length of ``g``. x : `LinearSpaceElement` Initial point, updated in-place. stepsize : positive float The stepsize for the outer (proximal point) iteration. The theory guarantees convergence for any positive real number, but the performance might depend on the choice of a good stepsize. inner_stepsizes : sequence of stepsizes Parameters determining the stepsizes for the inner iterations. Must be matched with the norms of ``L``, and convergence is guaranteed if the ``inner_stepsizes`` are small enough. See the Notes section for details. niter : int Number of (outer) iterations. random : bool, optional If `True`, the order of the dual upgdates is chosen randomly, otherwise the order provided by the lists ``g``, ``L`` and ``inner_stepsizes`` is used. callback : callable, optional Function called with the current iterate after each iteration. callback_loop : {'inner', 'outer'}, optional If 'inner', the ``callback`` function is called after each inner iteration, i.e., after each dual update. If 'outer', the ``callback`` function is called after each outer iteration, i.e., after each primal update. Notes ----- The algorithm as implemented here is described in the article [MF2015], where it is applied to a tomography problem. It solves the problem .. math:: \min_x \sum_{i=1}^m g_i(L_i x), where :math:`g_i` are proper, convex and lower semicontinuous functions and :math:`L_i` are linear, continuous operators for :math:`i = 1, \ldots, m`. In an outer iteration, the solution is found iteratively by an iteration .. math:: x_{n+1} = \mathrm{arg\,min}_x \sum_{i=1}^m g_i(L_i x) + \frac{\mu}{2} \|x - x_n\|^2 with some ``stepsize`` parameter :math:`\mu > 0` according to the proximal point algorithm. In the inner iteration, dual variables are introduced for each of the components of the sum. The Lagrangian of the problem is given by .. math:: S_n(x; v_1, \ldots, v_m) = \sum_{i=1}^m (\langle v_i, L_i x \rangle - g_i^*(v_i)) + \frac{\mu}{2} \|x - x_n\|^2. Given the dual variables, the new primal variable :math:`x_{n+1}` can be calculated by directly minimizing :math:`S_n` with respect to :math:`x`. This corresponds to the formula .. math:: x_{n+1} = x_n - \frac{1}{\mu} \sum_{i=1}^m L_i^* v_i. The dual updates are executed according to the following rule: .. math:: v_i^+ = \mathrm{Prox}^{\mu M_i^{-1}}_{g_i^*} (v_i + \mu M_i^{-1} L_i x_{n+1}), where :math:`x_{n+1}` is given by the formula above and :math:`M_i` is a diagonal matrix with positive diagonal entries such that :math:`M_i - L_i L_i^*` is positive semidefinite. The variable ``inner_stepsizes`` is chosen as a stepsize to the `Functional.proximal` to the `Functional.convex_conj` of each of the ``g`` s after multiplying with ``stepsize``. The ``inner_stepsizes`` contain the elements of :math:`M_i^{-1}` in one of the following ways: * Setting ``inner_stepsizes[i]`` a positive float :math:`\gamma` corresponds to the choice :math:`M_i^{-1} = \gamma \mathrm{Id}`. * Assume that ``g_i`` is a `SeparableSum`, then setting ``inner_stepsizes[i]`` a list :math:`(\gamma_1, \ldots, \gamma_k)` of positive floats corresponds to the choice of a block-diagonal matrix :math:`M_i^{-1}`, where each block corresponds to one of the space components and equals :math:`\gamma_i \mathrm{Id}`. * Assume that ``g_i`` is an `L1Norm` or an `L2NormSquared`, then setting ``inner_stepsizes[i]`` a ``g_i.domain.element`` :math:`z` corresponds to the choice :math:`M_i^{-1} = \mathrm{diag}(z)`. References ---------- [MF2015] McGaffin, M G, and Fessler, J A. *Alternating dual updates algorithm for X-ray CT reconstruction on the GPU*. IEEE Transactions on Computational Imaging, 1.3 (2015), pp 186--199. """ # Check the lenghts of the lists (= number of dual variables) length = len(g) if len(L) != length: raise ValueError('`len(L)` should equal `len(g)`, but {} != {}' ''.format(len(L), length)) if len(inner_stepsizes) != length: raise ValueError('len(`inner_stepsizes`) should equal `len(g)`, ' ' but {} != {}'.format(len(inner_stepsizes), length)) # Check if operators have a common domain # (the space of the primal variable): domain = L[0].domain if any(opi.domain != domain for opi in L): raise ValueError('domains of `L` are not all equal') # Check if range of the operators equals domain of the functionals ranges = [opi.range for opi in L] if any(L[i].range != g[i].domain for i in range(length)): raise ValueError('L[i].range` should equal `g.domain`') # Normalize string callback_loop, callback_loop_in = str(callback_loop).lower(), callback_loop if callback_loop not in ('inner', 'outer'): raise ValueError('`callback_loop` {!r} not understood' ''.format(callback_loop_in)) # Initialization of the dual variables duals = [space.zero() for space in ranges] # Reusable elements in the ranges, one per type of space unique_ranges = set(ranges) tmp_rans = {ran: ran.element() for ran in unique_ranges} # Prepare the proximal operators. Since the stepsize does not vary over # the iterations, we always use the same proximal operator. proxs = [func.convex_conj.proximal(stepsize * inner_ss if np.isscalar(inner_ss) else stepsize * np.asarray(inner_ss)) for (func, inner_ss) in zip(g, inner_stepsizes)] # Iteratively find a solution for _ in range(niter): # Update x = x - 1/stepsize * sum([ops[i].adjoint(duals[i]) # for i in range(length)]) for i in range(length): x -= (1.0 / stepsize) * L[i].adjoint(duals[i]) if random: rng = np.random.permutation(range(length)) else: rng = range(length) for j in rng: step = (stepsize * inner_stepsizes[j] if np.isscalar(inner_stepsizes[j]) else stepsize * np.asarray(inner_stepsizes[j])) arg = duals[j] + step * L[j](x) tmp_ran = tmp_rans[L[j].range] proxs[j](arg, out=tmp_ran) x -= 1.0 / stepsize * L[j].adjoint(tmp_ran - duals[j]) duals[j].assign(tmp_ran) if callback is not None and callback_loop == 'inner': callback(x) if callback is not None and callback_loop == 'outer': callback(x)
[ "def", "adupdates", "(", "x", ",", "g", ",", "L", ",", "stepsize", ",", "inner_stepsizes", ",", "niter", ",", "random", "=", "False", ",", "callback", "=", "None", ",", "callback_loop", "=", "'outer'", ")", ":", "# Check the lenghts of the lists (= number of d...
r"""Alternating Dual updates method. The Alternating Dual (AD) updates method of McGaffin and Fessler `[MF2015] <http://ieeexplore.ieee.org/document/7271047/>`_ is designed to solve an optimization problem of the form :: min_x [ sum_i g_i(L_i x) ] where ``g_i`` are proper, convex and lower semicontinuous functions and ``L_i`` are linear `Operator` s. Parameters ---------- g : sequence of `Functional` s All functions need to provide a `Functional.convex_conj` with a `Functional.proximal` factory. L : sequence of `Operator` s Length of ``L`` must equal the length of ``g``. x : `LinearSpaceElement` Initial point, updated in-place. stepsize : positive float The stepsize for the outer (proximal point) iteration. The theory guarantees convergence for any positive real number, but the performance might depend on the choice of a good stepsize. inner_stepsizes : sequence of stepsizes Parameters determining the stepsizes for the inner iterations. Must be matched with the norms of ``L``, and convergence is guaranteed if the ``inner_stepsizes`` are small enough. See the Notes section for details. niter : int Number of (outer) iterations. random : bool, optional If `True`, the order of the dual upgdates is chosen randomly, otherwise the order provided by the lists ``g``, ``L`` and ``inner_stepsizes`` is used. callback : callable, optional Function called with the current iterate after each iteration. callback_loop : {'inner', 'outer'}, optional If 'inner', the ``callback`` function is called after each inner iteration, i.e., after each dual update. If 'outer', the ``callback`` function is called after each outer iteration, i.e., after each primal update. Notes ----- The algorithm as implemented here is described in the article [MF2015], where it is applied to a tomography problem. It solves the problem .. math:: \min_x \sum_{i=1}^m g_i(L_i x), where :math:`g_i` are proper, convex and lower semicontinuous functions and :math:`L_i` are linear, continuous operators for :math:`i = 1, \ldots, m`. In an outer iteration, the solution is found iteratively by an iteration .. math:: x_{n+1} = \mathrm{arg\,min}_x \sum_{i=1}^m g_i(L_i x) + \frac{\mu}{2} \|x - x_n\|^2 with some ``stepsize`` parameter :math:`\mu > 0` according to the proximal point algorithm. In the inner iteration, dual variables are introduced for each of the components of the sum. The Lagrangian of the problem is given by .. math:: S_n(x; v_1, \ldots, v_m) = \sum_{i=1}^m (\langle v_i, L_i x \rangle - g_i^*(v_i)) + \frac{\mu}{2} \|x - x_n\|^2. Given the dual variables, the new primal variable :math:`x_{n+1}` can be calculated by directly minimizing :math:`S_n` with respect to :math:`x`. This corresponds to the formula .. math:: x_{n+1} = x_n - \frac{1}{\mu} \sum_{i=1}^m L_i^* v_i. The dual updates are executed according to the following rule: .. math:: v_i^+ = \mathrm{Prox}^{\mu M_i^{-1}}_{g_i^*} (v_i + \mu M_i^{-1} L_i x_{n+1}), where :math:`x_{n+1}` is given by the formula above and :math:`M_i` is a diagonal matrix with positive diagonal entries such that :math:`M_i - L_i L_i^*` is positive semidefinite. The variable ``inner_stepsizes`` is chosen as a stepsize to the `Functional.proximal` to the `Functional.convex_conj` of each of the ``g`` s after multiplying with ``stepsize``. The ``inner_stepsizes`` contain the elements of :math:`M_i^{-1}` in one of the following ways: * Setting ``inner_stepsizes[i]`` a positive float :math:`\gamma` corresponds to the choice :math:`M_i^{-1} = \gamma \mathrm{Id}`. * Assume that ``g_i`` is a `SeparableSum`, then setting ``inner_stepsizes[i]`` a list :math:`(\gamma_1, \ldots, \gamma_k)` of positive floats corresponds to the choice of a block-diagonal matrix :math:`M_i^{-1}`, where each block corresponds to one of the space components and equals :math:`\gamma_i \mathrm{Id}`. * Assume that ``g_i`` is an `L1Norm` or an `L2NormSquared`, then setting ``inner_stepsizes[i]`` a ``g_i.domain.element`` :math:`z` corresponds to the choice :math:`M_i^{-1} = \mathrm{diag}(z)`. References ---------- [MF2015] McGaffin, M G, and Fessler, J A. *Alternating dual updates algorithm for X-ray CT reconstruction on the GPU*. IEEE Transactions on Computational Imaging, 1.3 (2015), pp 186--199.
[ "r", "Alternating", "Dual", "updates", "method", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/nonsmooth/alternating_dual_updates.py#L23-L198
231,587
odlgroup/odl
odl/solvers/nonsmooth/alternating_dual_updates.py
adupdates_simple
def adupdates_simple(x, g, L, stepsize, inner_stepsizes, niter, random=False): """Non-optimized version of ``adupdates``. This function is intended for debugging. It makes a lot of copies and performs no error checking. """ # Initializations length = len(g) ranges = [Li.range for Li in L] duals = [space.zero() for space in ranges] # Iteratively find a solution for _ in range(niter): # Update x = x - 1/stepsize * sum([ops[i].adjoint(duals[i]) # for i in range(length)]) for i in range(length): x -= (1.0 / stepsize) * L[i].adjoint(duals[i]) rng = np.random.permutation(range(length)) if random else range(length) for j in rng: dual_tmp = ranges[j].element() dual_tmp = (g[j].convex_conj.proximal (stepsize * inner_stepsizes[j] if np.isscalar(inner_stepsizes[j]) else stepsize * np.asarray(inner_stepsizes[j])) (duals[j] + stepsize * inner_stepsizes[j] * L[j](x) if np.isscalar(inner_stepsizes[j]) else duals[j] + stepsize * np.asarray(inner_stepsizes[j]) * L[j](x))) x -= 1.0 / stepsize * L[j].adjoint(dual_tmp - duals[j]) duals[j].assign(dual_tmp)
python
def adupdates_simple(x, g, L, stepsize, inner_stepsizes, niter, random=False): # Initializations length = len(g) ranges = [Li.range for Li in L] duals = [space.zero() for space in ranges] # Iteratively find a solution for _ in range(niter): # Update x = x - 1/stepsize * sum([ops[i].adjoint(duals[i]) # for i in range(length)]) for i in range(length): x -= (1.0 / stepsize) * L[i].adjoint(duals[i]) rng = np.random.permutation(range(length)) if random else range(length) for j in rng: dual_tmp = ranges[j].element() dual_tmp = (g[j].convex_conj.proximal (stepsize * inner_stepsizes[j] if np.isscalar(inner_stepsizes[j]) else stepsize * np.asarray(inner_stepsizes[j])) (duals[j] + stepsize * inner_stepsizes[j] * L[j](x) if np.isscalar(inner_stepsizes[j]) else duals[j] + stepsize * np.asarray(inner_stepsizes[j]) * L[j](x))) x -= 1.0 / stepsize * L[j].adjoint(dual_tmp - duals[j]) duals[j].assign(dual_tmp)
[ "def", "adupdates_simple", "(", "x", ",", "g", ",", "L", ",", "stepsize", ",", "inner_stepsizes", ",", "niter", ",", "random", "=", "False", ")", ":", "# Initializations", "length", "=", "len", "(", "g", ")", "ranges", "=", "[", "Li", ".", "range", "...
Non-optimized version of ``adupdates``. This function is intended for debugging. It makes a lot of copies and performs no error checking.
[ "Non", "-", "optimized", "version", "of", "adupdates", ".", "This", "function", "is", "intended", "for", "debugging", ".", "It", "makes", "a", "lot", "of", "copies", "and", "performs", "no", "error", "checking", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/nonsmooth/alternating_dual_updates.py#L201-L232
231,588
odlgroup/odl
odl/tomo/geometry/spect.py
ParallelHoleCollimatorGeometry.frommatrix
def frommatrix(cls, apart, dpart, det_radius, init_matrix, **kwargs): """Create a `ParallelHoleCollimatorGeometry` using a matrix. This alternative constructor uses a matrix to rotate and translate the default configuration. It is most useful when the transformation to be applied is already given as a matrix. Parameters ---------- apart : 1-dim. `RectPartition` Partition of the parameter interval. dpart : 2-dim. `RectPartition` Partition of the detector parameter set. det_radius : positive float Radius of the circular detector orbit. init_matrix : `array_like`, shape ``(3, 3)`` or ``(3, 4)``, optional Transformation matrix whose left ``(3, 3)`` block is multiplied with the default ``det_pos_init`` and ``det_axes_init`` to determine the new vectors. If present, the fourth column acts as a translation after the initial transformation. The resulting ``det_axes_init`` will be normalized. kwargs : Further keyword arguments passed to the class constructor. Returns ------- geometry : `ParallelHoleCollimatorGeometry` The resulting geometry. """ # Get transformation and translation parts from `init_matrix` init_matrix = np.asarray(init_matrix, dtype=float) if init_matrix.shape not in ((3, 3), (3, 4)): raise ValueError('`matrix` must have shape (3, 3) or (3, 4), ' 'got array with shape {}' ''.format(init_matrix.shape)) trafo_matrix = init_matrix[:, :3] translation = init_matrix[:, 3:].squeeze() # Transform the default vectors default_axis = cls._default_config['axis'] # Normalized version, just in case default_orig_to_det_init = ( np.array(cls._default_config['det_pos_init'], dtype=float) / np.linalg.norm(cls._default_config['det_pos_init'])) default_det_axes_init = cls._default_config['det_axes_init'] vecs_to_transform = ((default_orig_to_det_init,) + default_det_axes_init) transformed_vecs = transform_system( default_axis, None, vecs_to_transform, matrix=trafo_matrix) # Use the standard constructor with these vectors axis, orig_to_det, det_axis_0, det_axis_1 = transformed_vecs if translation.size != 0: kwargs['translation'] = translation return cls(apart, dpart, det_radius, axis, orig_to_det_init=orig_to_det, det_axes_init=[det_axis_0, det_axis_1], **kwargs)
python
def frommatrix(cls, apart, dpart, det_radius, init_matrix, **kwargs): # Get transformation and translation parts from `init_matrix` init_matrix = np.asarray(init_matrix, dtype=float) if init_matrix.shape not in ((3, 3), (3, 4)): raise ValueError('`matrix` must have shape (3, 3) or (3, 4), ' 'got array with shape {}' ''.format(init_matrix.shape)) trafo_matrix = init_matrix[:, :3] translation = init_matrix[:, 3:].squeeze() # Transform the default vectors default_axis = cls._default_config['axis'] # Normalized version, just in case default_orig_to_det_init = ( np.array(cls._default_config['det_pos_init'], dtype=float) / np.linalg.norm(cls._default_config['det_pos_init'])) default_det_axes_init = cls._default_config['det_axes_init'] vecs_to_transform = ((default_orig_to_det_init,) + default_det_axes_init) transformed_vecs = transform_system( default_axis, None, vecs_to_transform, matrix=trafo_matrix) # Use the standard constructor with these vectors axis, orig_to_det, det_axis_0, det_axis_1 = transformed_vecs if translation.size != 0: kwargs['translation'] = translation return cls(apart, dpart, det_radius, axis, orig_to_det_init=orig_to_det, det_axes_init=[det_axis_0, det_axis_1], **kwargs)
[ "def", "frommatrix", "(", "cls", ",", "apart", ",", "dpart", ",", "det_radius", ",", "init_matrix", ",", "*", "*", "kwargs", ")", ":", "# Get transformation and translation parts from `init_matrix`", "init_matrix", "=", "np", ".", "asarray", "(", "init_matrix", ",...
Create a `ParallelHoleCollimatorGeometry` using a matrix. This alternative constructor uses a matrix to rotate and translate the default configuration. It is most useful when the transformation to be applied is already given as a matrix. Parameters ---------- apart : 1-dim. `RectPartition` Partition of the parameter interval. dpart : 2-dim. `RectPartition` Partition of the detector parameter set. det_radius : positive float Radius of the circular detector orbit. init_matrix : `array_like`, shape ``(3, 3)`` or ``(3, 4)``, optional Transformation matrix whose left ``(3, 3)`` block is multiplied with the default ``det_pos_init`` and ``det_axes_init`` to determine the new vectors. If present, the fourth column acts as a translation after the initial transformation. The resulting ``det_axes_init`` will be normalized. kwargs : Further keyword arguments passed to the class constructor. Returns ------- geometry : `ParallelHoleCollimatorGeometry` The resulting geometry.
[ "Create", "a", "ParallelHoleCollimatorGeometry", "using", "a", "matrix", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/geometry/spect.py#L101-L159
231,589
odlgroup/odl
odl/discr/discr_mappings.py
_compute_nearest_weights_edge
def _compute_nearest_weights_edge(idcs, ndist, variant): """Helper for nearest interpolation mimicing the linear case.""" # Get out-of-bounds indices from the norm_distances. Negative # means "too low", larger than or equal to 1 means "too high" lo = (ndist < 0) hi = (ndist > 1) # For "too low" nodes, the lower neighbor gets weight zero; # "too high" gets 1. if variant == 'left': w_lo = np.where(ndist <= 0.5, 1.0, 0.0) else: w_lo = np.where(ndist < 0.5, 1.0, 0.0) w_lo[lo] = 0 w_lo[hi] = 1 # For "too high" nodes, the upper neighbor gets weight zero; # "too low" gets 1. if variant == 'left': w_hi = np.where(ndist <= 0.5, 0.0, 1.0) else: w_hi = np.where(ndist < 0.5, 0.0, 1.0) w_hi[lo] = 1 w_hi[hi] = 0 # For upper/lower out-of-bounds nodes, we need to set the # lower/upper neighbors to the last/first grid point edge = [idcs, idcs + 1] edge[0][hi] = -1 edge[1][lo] = 0 return w_lo, w_hi, edge
python
def _compute_nearest_weights_edge(idcs, ndist, variant): # Get out-of-bounds indices from the norm_distances. Negative # means "too low", larger than or equal to 1 means "too high" lo = (ndist < 0) hi = (ndist > 1) # For "too low" nodes, the lower neighbor gets weight zero; # "too high" gets 1. if variant == 'left': w_lo = np.where(ndist <= 0.5, 1.0, 0.0) else: w_lo = np.where(ndist < 0.5, 1.0, 0.0) w_lo[lo] = 0 w_lo[hi] = 1 # For "too high" nodes, the upper neighbor gets weight zero; # "too low" gets 1. if variant == 'left': w_hi = np.where(ndist <= 0.5, 0.0, 1.0) else: w_hi = np.where(ndist < 0.5, 0.0, 1.0) w_hi[lo] = 1 w_hi[hi] = 0 # For upper/lower out-of-bounds nodes, we need to set the # lower/upper neighbors to the last/first grid point edge = [idcs, idcs + 1] edge[0][hi] = -1 edge[1][lo] = 0 return w_lo, w_hi, edge
[ "def", "_compute_nearest_weights_edge", "(", "idcs", ",", "ndist", ",", "variant", ")", ":", "# Get out-of-bounds indices from the norm_distances. Negative", "# means \"too low\", larger than or equal to 1 means \"too high\"", "lo", "=", "(", "ndist", "<", "0", ")", "hi", "="...
Helper for nearest interpolation mimicing the linear case.
[ "Helper", "for", "nearest", "interpolation", "mimicing", "the", "linear", "case", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/discr/discr_mappings.py#L790-L823
231,590
odlgroup/odl
odl/discr/discr_mappings.py
_compute_linear_weights_edge
def _compute_linear_weights_edge(idcs, ndist): """Helper for linear interpolation.""" # Get out-of-bounds indices from the norm_distances. Negative # means "too low", larger than or equal to 1 means "too high" lo = np.where(ndist < 0) hi = np.where(ndist > 1) # For "too low" nodes, the lower neighbor gets weight zero; # "too high" gets 2 - yi (since yi >= 1) w_lo = (1 - ndist) w_lo[lo] = 0 w_lo[hi] += 1 # For "too high" nodes, the upper neighbor gets weight zero; # "too low" gets 1 + yi (since yi < 0) w_hi = np.copy(ndist) w_hi[lo] += 1 w_hi[hi] = 0 # For upper/lower out-of-bounds nodes, we need to set the # lower/upper neighbors to the last/first grid point edge = [idcs, idcs + 1] edge[0][hi] = -1 edge[1][lo] = 0 return w_lo, w_hi, edge
python
def _compute_linear_weights_edge(idcs, ndist): # Get out-of-bounds indices from the norm_distances. Negative # means "too low", larger than or equal to 1 means "too high" lo = np.where(ndist < 0) hi = np.where(ndist > 1) # For "too low" nodes, the lower neighbor gets weight zero; # "too high" gets 2 - yi (since yi >= 1) w_lo = (1 - ndist) w_lo[lo] = 0 w_lo[hi] += 1 # For "too high" nodes, the upper neighbor gets weight zero; # "too low" gets 1 + yi (since yi < 0) w_hi = np.copy(ndist) w_hi[lo] += 1 w_hi[hi] = 0 # For upper/lower out-of-bounds nodes, we need to set the # lower/upper neighbors to the last/first grid point edge = [idcs, idcs + 1] edge[0][hi] = -1 edge[1][lo] = 0 return w_lo, w_hi, edge
[ "def", "_compute_linear_weights_edge", "(", "idcs", ",", "ndist", ")", ":", "# Get out-of-bounds indices from the norm_distances. Negative", "# means \"too low\", larger than or equal to 1 means \"too high\"", "lo", "=", "np", ".", "where", "(", "ndist", "<", "0", ")", "hi", ...
Helper for linear interpolation.
[ "Helper", "for", "linear", "interpolation", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/discr/discr_mappings.py#L826-L851
231,591
odlgroup/odl
odl/discr/discr_mappings.py
PerAxisInterpolation._call
def _call(self, x, out=None): """Create an interpolator from grid values ``x``. Parameters ---------- x : `Tensor` The array of values to be interpolated out : `FunctionSpaceElement`, optional Element in which to store the interpolator Returns ------- out : `FunctionSpaceElement` Per-axis interpolator for the grid of this operator. If ``out`` was provided, the returned object is a reference to it. """ def per_axis_interp(arg, out=None): """Interpolating function with vectorization.""" if is_valid_input_meshgrid(arg, self.grid.ndim): input_type = 'meshgrid' else: input_type = 'array' interpolator = _PerAxisInterpolator( self.grid.coord_vectors, x, schemes=self.schemes, nn_variants=self.nn_variants, input_type=input_type) return interpolator(arg, out=out) return self.range.element(per_axis_interp, vectorized=True)
python
def _call(self, x, out=None): def per_axis_interp(arg, out=None): """Interpolating function with vectorization.""" if is_valid_input_meshgrid(arg, self.grid.ndim): input_type = 'meshgrid' else: input_type = 'array' interpolator = _PerAxisInterpolator( self.grid.coord_vectors, x, schemes=self.schemes, nn_variants=self.nn_variants, input_type=input_type) return interpolator(arg, out=out) return self.range.element(per_axis_interp, vectorized=True)
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ")", ":", "def", "per_axis_interp", "(", "arg", ",", "out", "=", "None", ")", ":", "\"\"\"Interpolating function with vectorization.\"\"\"", "if", "is_valid_input_meshgrid", "(", "arg", ",", "self...
Create an interpolator from grid values ``x``. Parameters ---------- x : `Tensor` The array of values to be interpolated out : `FunctionSpaceElement`, optional Element in which to store the interpolator Returns ------- out : `FunctionSpaceElement` Per-axis interpolator for the grid of this operator. If ``out`` was provided, the returned object is a reference to it.
[ "Create", "an", "interpolator", "from", "grid", "values", "x", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/discr/discr_mappings.py#L559-L590
231,592
odlgroup/odl
odl/discr/discr_mappings.py
_Interpolator._find_indices
def _find_indices(self, x): """Find indices and distances of the given nodes. Can be overridden by subclasses to improve efficiency. """ # find relevant edges between which xi are situated index_vecs = [] # compute distance to lower edge in unity units norm_distances = [] # iterate through dimensions for xi, cvec in zip(x, self.coord_vecs): idcs = np.searchsorted(cvec, xi) - 1 idcs[idcs < 0] = 0 idcs[idcs > cvec.size - 2] = cvec.size - 2 index_vecs.append(idcs) norm_distances.append((xi - cvec[idcs]) / (cvec[idcs + 1] - cvec[idcs])) return index_vecs, norm_distances
python
def _find_indices(self, x): # find relevant edges between which xi are situated index_vecs = [] # compute distance to lower edge in unity units norm_distances = [] # iterate through dimensions for xi, cvec in zip(x, self.coord_vecs): idcs = np.searchsorted(cvec, xi) - 1 idcs[idcs < 0] = 0 idcs[idcs > cvec.size - 2] = cvec.size - 2 index_vecs.append(idcs) norm_distances.append((xi - cvec[idcs]) / (cvec[idcs + 1] - cvec[idcs])) return index_vecs, norm_distances
[ "def", "_find_indices", "(", "self", ",", "x", ")", ":", "# find relevant edges between which xi are situated", "index_vecs", "=", "[", "]", "# compute distance to lower edge in unity units", "norm_distances", "=", "[", "]", "# iterate through dimensions", "for", "xi", ",",...
Find indices and distances of the given nodes. Can be overridden by subclasses to improve efficiency.
[ "Find", "indices", "and", "distances", "of", "the", "given", "nodes", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/discr/discr_mappings.py#L714-L735
231,593
odlgroup/odl
odl/discr/discr_mappings.py
_NearestInterpolator._evaluate
def _evaluate(self, indices, norm_distances, out=None): """Evaluate nearest interpolation.""" idx_res = [] for i, yi in zip(indices, norm_distances): if self.variant == 'left': idx_res.append(np.where(yi <= .5, i, i + 1)) else: idx_res.append(np.where(yi < .5, i, i + 1)) idx_res = tuple(idx_res) if out is not None: out[:] = self.values[idx_res] return out else: return self.values[idx_res]
python
def _evaluate(self, indices, norm_distances, out=None): idx_res = [] for i, yi in zip(indices, norm_distances): if self.variant == 'left': idx_res.append(np.where(yi <= .5, i, i + 1)) else: idx_res.append(np.where(yi < .5, i, i + 1)) idx_res = tuple(idx_res) if out is not None: out[:] = self.values[idx_res] return out else: return self.values[idx_res]
[ "def", "_evaluate", "(", "self", ",", "indices", ",", "norm_distances", ",", "out", "=", "None", ")", ":", "idx_res", "=", "[", "]", "for", "i", ",", "yi", "in", "zip", "(", "indices", ",", "norm_distances", ")", ":", "if", "self", ".", "variant", ...
Evaluate nearest interpolation.
[ "Evaluate", "nearest", "interpolation", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/discr/discr_mappings.py#L774-L787
231,594
odlgroup/odl
odl/discr/discr_mappings.py
_PerAxisInterpolator._evaluate
def _evaluate(self, indices, norm_distances, out=None): """Evaluate linear interpolation. Modified for in-place evaluation and treatment of out-of-bounds points by implicitly assuming 0 at the next node.""" # slice for broadcasting over trailing dimensions in self.values vslice = (slice(None),) + (None,) * (self.values.ndim - len(indices)) if out is None: out_shape = out_shape_from_meshgrid(norm_distances) out_dtype = self.values.dtype out = np.zeros(out_shape, dtype=out_dtype) else: out[:] = 0.0 # Weights and indices (per axis) low_weights, high_weights, edge_indices = _create_weight_edge_lists( indices, norm_distances, self.schemes, self.nn_variants) # Iterate over all possible combinations of [i, i+1] for each # axis, resulting in a loop of length 2**ndim for lo_hi, edge in zip(product(*([['l', 'h']] * len(indices))), product(*edge_indices)): weight = 1.0 # TODO: determine best summation order from array strides for lh, w_lo, w_hi in zip(lo_hi, low_weights, high_weights): # We don't multiply in-place to exploit the cheap operations # in the beginning: sizes grow gradually as following: # (n, 1, 1, ...) -> (n, m, 1, ...) -> ... # Hence, it is faster to build up the weight array instead # of doing full-size operations from the beginning. if lh == 'l': weight = weight * w_lo else: weight = weight * w_hi out += np.asarray(self.values[edge]) * weight[vslice] return np.array(out, copy=False, ndmin=1)
python
def _evaluate(self, indices, norm_distances, out=None): # slice for broadcasting over trailing dimensions in self.values vslice = (slice(None),) + (None,) * (self.values.ndim - len(indices)) if out is None: out_shape = out_shape_from_meshgrid(norm_distances) out_dtype = self.values.dtype out = np.zeros(out_shape, dtype=out_dtype) else: out[:] = 0.0 # Weights and indices (per axis) low_weights, high_weights, edge_indices = _create_weight_edge_lists( indices, norm_distances, self.schemes, self.nn_variants) # Iterate over all possible combinations of [i, i+1] for each # axis, resulting in a loop of length 2**ndim for lo_hi, edge in zip(product(*([['l', 'h']] * len(indices))), product(*edge_indices)): weight = 1.0 # TODO: determine best summation order from array strides for lh, w_lo, w_hi in zip(lo_hi, low_weights, high_weights): # We don't multiply in-place to exploit the cheap operations # in the beginning: sizes grow gradually as following: # (n, 1, 1, ...) -> (n, m, 1, ...) -> ... # Hence, it is faster to build up the weight array instead # of doing full-size operations from the beginning. if lh == 'l': weight = weight * w_lo else: weight = weight * w_hi out += np.asarray(self.values[edge]) * weight[vslice] return np.array(out, copy=False, ndmin=1)
[ "def", "_evaluate", "(", "self", ",", "indices", ",", "norm_distances", ",", "out", "=", "None", ")", ":", "# slice for broadcasting over trailing dimensions in self.values", "vslice", "=", "(", "slice", "(", "None", ")", ",", ")", "+", "(", "None", ",", ")", ...
Evaluate linear interpolation. Modified for in-place evaluation and treatment of out-of-bounds points by implicitly assuming 0 at the next node.
[ "Evaluate", "linear", "interpolation", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/discr/discr_mappings.py#L908-L945
231,595
odlgroup/odl
odl/solvers/nonsmooth/proximal_gradient_solvers.py
accelerated_proximal_gradient
def accelerated_proximal_gradient(x, f, g, gamma, niter, callback=None, **kwargs): r"""Accelerated proximal gradient algorithm for convex optimization. The method is known as "Fast Iterative Soft-Thresholding Algorithm" (FISTA). See `[Beck2009]`_ for more information. Solves the convex optimization problem:: min_{x in X} f(x) + g(x) where the proximal operator of ``f`` is known and ``g`` is differentiable. Parameters ---------- x : ``f.domain`` element Starting point of the iteration, updated in-place. f : `Functional` The function ``f`` in the problem definition. Needs to have ``f.proximal``. g : `Functional` The function ``g`` in the problem definition. Needs to have ``g.gradient``. gamma : positive float Step size parameter. niter : non-negative int, optional Number of iterations. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- The problem of interest is .. math:: \min_{x \in X} f(x) + g(x), where the formal conditions are that :math:`f : X \to \mathbb{R}` is proper, convex and lower-semicontinuous, and :math:`g : X \to \mathbb{R}` is differentiable and :math:`\nabla g` is :math:`1 / \beta`-Lipschitz continuous. Convergence is only guaranteed if the step length :math:`\gamma` satisfies .. math:: 0 < \gamma < 2 \beta. References ---------- .. _[Beck2009]: http://epubs.siam.org/doi/abs/10.1137/080716542 """ # Get and validate input if x not in f.domain: raise TypeError('`x` {!r} is not in the domain of `f` {!r}' ''.format(x, f.domain)) if x not in g.domain: raise TypeError('`x` {!r} is not in the domain of `g` {!r}' ''.format(x, g.domain)) gamma, gamma_in = float(gamma), gamma if gamma <= 0: raise ValueError('`gamma` must be positive, got {}'.format(gamma_in)) if int(niter) != niter: raise ValueError('`niter` {} not understood'.format(niter)) # Get the proximal f_prox = f.proximal(gamma) g_grad = g.gradient # Create temporary tmp = x.space.element() y = x.copy() t = 1 for k in range(niter): # Update t t, t_old = (1 + np.sqrt(1 + 4 * t ** 2)) / 2, t alpha = (t_old - 1) / t # x - gamma grad_g (y) tmp.lincomb(1, y, -gamma, g_grad(y)) # Store old x value in y y.assign(x) # Update x f_prox(tmp, out=x) # Update y y.lincomb(1 + alpha, x, -alpha, y) if callback is not None: callback(x)
python
def accelerated_proximal_gradient(x, f, g, gamma, niter, callback=None, **kwargs): r"""Accelerated proximal gradient algorithm for convex optimization. The method is known as "Fast Iterative Soft-Thresholding Algorithm" (FISTA). See `[Beck2009]`_ for more information. Solves the convex optimization problem:: min_{x in X} f(x) + g(x) where the proximal operator of ``f`` is known and ``g`` is differentiable. Parameters ---------- x : ``f.domain`` element Starting point of the iteration, updated in-place. f : `Functional` The function ``f`` in the problem definition. Needs to have ``f.proximal``. g : `Functional` The function ``g`` in the problem definition. Needs to have ``g.gradient``. gamma : positive float Step size parameter. niter : non-negative int, optional Number of iterations. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- The problem of interest is .. math:: \min_{x \in X} f(x) + g(x), where the formal conditions are that :math:`f : X \to \mathbb{R}` is proper, convex and lower-semicontinuous, and :math:`g : X \to \mathbb{R}` is differentiable and :math:`\nabla g` is :math:`1 / \beta`-Lipschitz continuous. Convergence is only guaranteed if the step length :math:`\gamma` satisfies .. math:: 0 < \gamma < 2 \beta. References ---------- .. _[Beck2009]: http://epubs.siam.org/doi/abs/10.1137/080716542 """ # Get and validate input if x not in f.domain: raise TypeError('`x` {!r} is not in the domain of `f` {!r}' ''.format(x, f.domain)) if x not in g.domain: raise TypeError('`x` {!r} is not in the domain of `g` {!r}' ''.format(x, g.domain)) gamma, gamma_in = float(gamma), gamma if gamma <= 0: raise ValueError('`gamma` must be positive, got {}'.format(gamma_in)) if int(niter) != niter: raise ValueError('`niter` {} not understood'.format(niter)) # Get the proximal f_prox = f.proximal(gamma) g_grad = g.gradient # Create temporary tmp = x.space.element() y = x.copy() t = 1 for k in range(niter): # Update t t, t_old = (1 + np.sqrt(1 + 4 * t ** 2)) / 2, t alpha = (t_old - 1) / t # x - gamma grad_g (y) tmp.lincomb(1, y, -gamma, g_grad(y)) # Store old x value in y y.assign(x) # Update x f_prox(tmp, out=x) # Update y y.lincomb(1 + alpha, x, -alpha, y) if callback is not None: callback(x)
[ "def", "accelerated_proximal_gradient", "(", "x", ",", "f", ",", "g", ",", "gamma", ",", "niter", ",", "callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Get and validate input", "if", "x", "not", "in", "f", ".", "domain", ":", "raise", "Ty...
r"""Accelerated proximal gradient algorithm for convex optimization. The method is known as "Fast Iterative Soft-Thresholding Algorithm" (FISTA). See `[Beck2009]`_ for more information. Solves the convex optimization problem:: min_{x in X} f(x) + g(x) where the proximal operator of ``f`` is known and ``g`` is differentiable. Parameters ---------- x : ``f.domain`` element Starting point of the iteration, updated in-place. f : `Functional` The function ``f`` in the problem definition. Needs to have ``f.proximal``. g : `Functional` The function ``g`` in the problem definition. Needs to have ``g.gradient``. gamma : positive float Step size parameter. niter : non-negative int, optional Number of iterations. callback : callable, optional Function called with the current iterate after each iteration. Notes ----- The problem of interest is .. math:: \min_{x \in X} f(x) + g(x), where the formal conditions are that :math:`f : X \to \mathbb{R}` is proper, convex and lower-semicontinuous, and :math:`g : X \to \mathbb{R}` is differentiable and :math:`\nabla g` is :math:`1 / \beta`-Lipschitz continuous. Convergence is only guaranteed if the step length :math:`\gamma` satisfies .. math:: 0 < \gamma < 2 \beta. References ---------- .. _[Beck2009]: http://epubs.siam.org/doi/abs/10.1137/080716542
[ "r", "Accelerated", "proximal", "gradient", "algorithm", "for", "convex", "optimization", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/nonsmooth/proximal_gradient_solvers.py#L120-L213
231,596
odlgroup/odl
odl/space/npy_tensors.py
_blas_is_applicable
def _blas_is_applicable(*args): """Whether BLAS routines can be applied or not. BLAS routines are available for single and double precision float or complex data only. If the arrays are non-contiguous, BLAS methods are usually slower, and array-writing routines do not work at all. Hence, only contiguous arrays are allowed. Parameters ---------- x1,...,xN : `NumpyTensor` The tensors to be tested for BLAS conformity. Returns ------- blas_is_applicable : bool ``True`` if all mentioned requirements are met, ``False`` otherwise. """ if any(x.dtype != args[0].dtype for x in args[1:]): return False elif any(x.dtype not in _BLAS_DTYPES for x in args): return False elif not (all(x.flags.f_contiguous for x in args) or all(x.flags.c_contiguous for x in args)): return False elif any(x.size > np.iinfo('int32').max for x in args): # Temporary fix for 32 bit int overflow in BLAS # TODO: use chunking instead return False else: return True
python
def _blas_is_applicable(*args): if any(x.dtype != args[0].dtype for x in args[1:]): return False elif any(x.dtype not in _BLAS_DTYPES for x in args): return False elif not (all(x.flags.f_contiguous for x in args) or all(x.flags.c_contiguous for x in args)): return False elif any(x.size > np.iinfo('int32').max for x in args): # Temporary fix for 32 bit int overflow in BLAS # TODO: use chunking instead return False else: return True
[ "def", "_blas_is_applicable", "(", "*", "args", ")", ":", "if", "any", "(", "x", ".", "dtype", "!=", "args", "[", "0", "]", ".", "dtype", "for", "x", "in", "args", "[", "1", ":", "]", ")", ":", "return", "False", "elif", "any", "(", "x", ".", ...
Whether BLAS routines can be applied or not. BLAS routines are available for single and double precision float or complex data only. If the arrays are non-contiguous, BLAS methods are usually slower, and array-writing routines do not work at all. Hence, only contiguous arrays are allowed. Parameters ---------- x1,...,xN : `NumpyTensor` The tensors to be tested for BLAS conformity. Returns ------- blas_is_applicable : bool ``True`` if all mentioned requirements are met, ``False`` otherwise.
[ "Whether", "BLAS", "routines", "can", "be", "applied", "or", "not", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/npy_tensors.py#L1769-L1799
231,597
odlgroup/odl
odl/space/npy_tensors.py
_weighting
def _weighting(weights, exponent): """Return a weighting whose type is inferred from the arguments.""" if np.isscalar(weights): weighting = NumpyTensorSpaceConstWeighting(weights, exponent) elif weights is None: weighting = NumpyTensorSpaceConstWeighting(1.0, exponent) else: # last possibility: make an array arr = np.asarray(weights) weighting = NumpyTensorSpaceArrayWeighting(arr, exponent) return weighting
python
def _weighting(weights, exponent): if np.isscalar(weights): weighting = NumpyTensorSpaceConstWeighting(weights, exponent) elif weights is None: weighting = NumpyTensorSpaceConstWeighting(1.0, exponent) else: # last possibility: make an array arr = np.asarray(weights) weighting = NumpyTensorSpaceArrayWeighting(arr, exponent) return weighting
[ "def", "_weighting", "(", "weights", ",", "exponent", ")", ":", "if", "np", ".", "isscalar", "(", "weights", ")", ":", "weighting", "=", "NumpyTensorSpaceConstWeighting", "(", "weights", ",", "exponent", ")", "elif", "weights", "is", "None", ":", "weighting"...
Return a weighting whose type is inferred from the arguments.
[ "Return", "a", "weighting", "whose", "type", "is", "inferred", "from", "the", "arguments", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/npy_tensors.py#L1904-L1913
231,598
odlgroup/odl
odl/space/npy_tensors.py
_norm_default
def _norm_default(x): """Default Euclidean norm implementation.""" # Lazy import to improve `import odl` time import scipy.linalg if _blas_is_applicable(x.data): nrm2 = scipy.linalg.blas.get_blas_funcs('nrm2', dtype=x.dtype) norm = partial(nrm2, n=native(x.size)) else: norm = np.linalg.norm return norm(x.data.ravel())
python
def _norm_default(x): # Lazy import to improve `import odl` time import scipy.linalg if _blas_is_applicable(x.data): nrm2 = scipy.linalg.blas.get_blas_funcs('nrm2', dtype=x.dtype) norm = partial(nrm2, n=native(x.size)) else: norm = np.linalg.norm return norm(x.data.ravel())
[ "def", "_norm_default", "(", "x", ")", ":", "# Lazy import to improve `import odl` time", "import", "scipy", ".", "linalg", "if", "_blas_is_applicable", "(", "x", ".", "data", ")", ":", "nrm2", "=", "scipy", ".", "linalg", ".", "blas", ".", "get_blas_funcs", "...
Default Euclidean norm implementation.
[ "Default", "Euclidean", "norm", "implementation", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/npy_tensors.py#L1992-L2002
231,599
odlgroup/odl
odl/space/npy_tensors.py
_pnorm_default
def _pnorm_default(x, p): """Default p-norm implementation.""" return np.linalg.norm(x.data.ravel(), ord=p)
python
def _pnorm_default(x, p): return np.linalg.norm(x.data.ravel(), ord=p)
[ "def", "_pnorm_default", "(", "x", ",", "p", ")", ":", "return", "np", ".", "linalg", ".", "norm", "(", "x", ".", "data", ".", "ravel", "(", ")", ",", "ord", "=", "p", ")" ]
Default p-norm implementation.
[ "Default", "p", "-", "norm", "implementation", "." ]
b8443f6aca90e191ba36c91d32253c5a36249a6c
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/npy_tensors.py#L2005-L2007