_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q35600 | SamplingOperator._call | train | def _call(self, x):
"""Return values at indices, possibly weighted."""
out = x.asarray().ravel()[self._indices_flat]
if self.variant == 'point_eval':
weights = 1.0
elif self.variant == 'integrate':
weights = getattr(self.domain, 'cell_volume', 1.0)
else:
... | python | {
"resource": ""
} |
q35601 | SamplingOperator.adjoint | train | def adjoint(self):
"""Adjoint of the sampling operator, a `WeightedSumSamplingOperator`.
If each sampling point occurs only once, the adjoint consists
in inserting the given values into the output at the sampling
points. Duplicate sampling points are weighted with their
multipli... | python | {
"resource": ""
} |
q35602 | WeightedSumSamplingOperator._call | train | def _call(self, x):
"""Sum all values if indices are given multiple times."""
y = np.bincount(self._indices_flat, weights=x,
minlength=self.range.size)
out = y.reshape(self.range.shape)
if self.variant == 'dirac':
weights = getattr(self.range, 'cell_... | python | {
"resource": ""
} |
q35603 | WeightedSumSamplingOperator.adjoint | train | def adjoint(self):
"""Adjoint of this operator, a `SamplingOperator`.
The ``'char_fun'`` variant of this operator corresponds to the
``'integrate'`` sampling operator, and ``'dirac'`` corresponds to
``'point_eval'``.
Examples
--------
>>> space = odl.uniform_dis... | python | {
"resource": ""
} |
q35604 | FlatteningOperator.inverse | train | def inverse(self):
"""Operator that reshapes to original shape.
Examples
--------
>>> space = odl.uniform_discr([-1, -1], [1, 1], shape=(2, 4))
>>> op = odl.FlatteningOperator(space)
>>> y = op.range.element([1, 2, 3, 4, 5, 6, 7, 8])
>>> op.inverse(y)
uni... | python | {
"resource": ""
} |
q35605 | MRCHeaderProperties.data_shape | train | def data_shape(self):
"""Shape tuple of the whole data block as determined from `header`.
If no header is available (i.e., before it has been initialized),
or any of the header entries ``'nx', 'ny', 'nz'`` is missing,
-1 is returned, which makes reshaping a no-op.
Otherwise, the... | python | {
"resource": ""
} |
q35606 | MRCHeaderProperties.data_storage_shape | train | def data_storage_shape(self):
"""Shape tuple of the data as stored in the file.
If no header is available (i.e., before it has been initialized),
or any of the header entries ``'nx', 'ny', 'nz'`` is missing,
-1 is returned, which makes reshaping a no-op.
Otherwise, the returned ... | python | {
"resource": ""
} |
q35607 | MRCHeaderProperties.data_dtype | train | def data_dtype(self):
"""Data type of the data block as determined from `header`.
If no header is available (i.e., before it has been initialized),
or the header entry ``'mode'`` is missing, the data type gained
from the ``dtype`` argument in the initializer is returned.
Otherwi... | python | {
"resource": ""
} |
q35608 | MRCHeaderProperties.cell_sides_angstrom | train | def cell_sides_angstrom(self):
"""Array of sizes of a unit cell in Angstroms.
The value is determined from the ``'cella'`` entry in `header`.
"""
return np.asarray(
self.header['cella']['value'], dtype=float) / self.data_shape | python | {
"resource": ""
} |
q35609 | MRCHeaderProperties.labels | train | def labels(self):
"""Return the 10-tuple of text labels from `header`.
The value is determined from the header entries ``'nlabl'`` and
``'label'``.
"""
label_array = self.header['label']['value']
labels = tuple(''.join(row.astype(str)) for row in label_array)
tr... | python | {
"resource": ""
} |
q35610 | FileReaderMRC.read_extended_header | train | def read_extended_header(self, groupby='field', force_type=''):
"""Read the extended header according to `extended_header_type`.
Currently, only the FEI extended header format is supported.
See `print_fei_ext_header_spec` or `this homepage`_ for the format
specification.
The ex... | python | {
"resource": ""
} |
q35611 | FileReaderMRC.read_data | train | def read_data(self, dstart=None, dend=None, swap_axes=True):
"""Read the data from `file` and return it as Numpy array.
Parameters
----------
dstart : int, optional
Offset in bytes of the data field. By default, it is equal
to ``header_size``. Backwards indexing ... | python | {
"resource": ""
} |
q35612 | dedent | train | def dedent(string, indent_str=' ', max_levels=None):
"""Revert the effect of indentation.
Examples
--------
Remove a simple one-level indentation:
>>> text = '''<->This is line 1.
... <->Next line.
... <->And another one.'''
>>> print(text)
<->This is line 1.
<->Next line.
... | python | {
"resource": ""
} |
q35613 | array_str | train | def array_str(a, nprint=6):
"""Stringification of an array.
Parameters
----------
a : `array-like`
The array to print.
nprint : int, optional
Maximum number of elements to print per axis in ``a``. For larger
arrays, a summary is printed, with ``nprint // 2`` elements on
... | python | {
"resource": ""
} |
q35614 | dtype_repr | train | def dtype_repr(dtype):
"""Stringify ``dtype`` for ``repr`` with default for int and float."""
dtype = np.dtype(dtype)
if dtype == np.dtype(int):
return "'int'"
elif dtype == np.dtype(float):
return "'float'"
elif dtype == np.dtype(complex):
return "'complex'"
elif dtype.s... | python | {
"resource": ""
} |
q35615 | is_numeric_dtype | train | def is_numeric_dtype(dtype):
"""Return ``True`` if ``dtype`` is a numeric type."""
dtype = np.dtype(dtype)
return np.issubsctype(getattr(dtype, 'base', None), np.number) | python | {
"resource": ""
} |
q35616 | is_int_dtype | train | def is_int_dtype(dtype):
"""Return ``True`` if ``dtype`` is an integer type."""
dtype = np.dtype(dtype)
return np.issubsctype(getattr(dtype, 'base', None), np.integer) | python | {
"resource": ""
} |
q35617 | is_real_floating_dtype | train | def is_real_floating_dtype(dtype):
"""Return ``True`` if ``dtype`` is a real floating point type."""
dtype = np.dtype(dtype)
return np.issubsctype(getattr(dtype, 'base', None), np.floating) | python | {
"resource": ""
} |
q35618 | is_complex_floating_dtype | train | def is_complex_floating_dtype(dtype):
"""Return ``True`` if ``dtype`` is a complex floating point type."""
dtype = np.dtype(dtype)
return np.issubsctype(getattr(dtype, 'base', None), np.complexfloating) | python | {
"resource": ""
} |
q35619 | real_dtype | train | def real_dtype(dtype, default=None):
"""Return the real counterpart of ``dtype`` if existing.
Parameters
----------
dtype :
Real or complex floating point data type. It can be given in any
way the `numpy.dtype` constructor understands.
default :
Object to be returned if no r... | python | {
"resource": ""
} |
q35620 | complex_dtype | train | def complex_dtype(dtype, default=None):
"""Return complex counterpart of ``dtype`` if existing, else ``default``.
Parameters
----------
dtype :
Real or complex floating point data type. It can be given in any
way the `numpy.dtype` constructor understands.
default :
Object to... | python | {
"resource": ""
} |
q35621 | preload_first_arg | train | def preload_first_arg(instance, mode):
"""Decorator to preload the first argument of a call method.
Parameters
----------
instance :
Class instance to preload the call with
mode : {'out-of-place', 'in-place'}
'out-of-place': call is out-of-place -- ``f(x, **kwargs)``
'in-p... | python | {
"resource": ""
} |
q35622 | signature_string | train | def signature_string(posargs, optargs, sep=', ', mod='!r'):
"""Return a stringified signature from given arguments.
Parameters
----------
posargs : sequence
Positional argument values, always included in the returned string.
They appear in the string as (roughly)::
sep.join... | python | {
"resource": ""
} |
q35623 | _separators | train | def _separators(strings, linewidth):
"""Return separators that keep joined strings within the line width."""
if len(strings) <= 1:
return ()
indent_len = 4
separators = []
cur_line_len = indent_len + len(strings[0]) + 1
if cur_line_len + 2 <= linewidth and '\n' not in strings[0]:
... | python | {
"resource": ""
} |
q35624 | repr_string | train | def repr_string(outer_string, inner_strings, allow_mixed_seps=True):
r"""Return a pretty string for ``repr``.
The returned string is formatted such that it does not extend
beyond the line boundary if avoidable. The line width is taken from
NumPy's printing options that can be retrieved with
`numpy.... | python | {
"resource": ""
} |
q35625 | attribute_repr_string | train | def attribute_repr_string(inst_str, attr_str):
"""Return a repr string for an attribute that respects line width.
Parameters
----------
inst_str : str
Stringification of a class instance.
attr_str : str
Name of the attribute (not including the ``'.'``).
Returns
-------
... | python | {
"resource": ""
} |
q35626 | method_repr_string | train | def method_repr_string(inst_str, meth_str, arg_strs=None,
allow_mixed_seps=True):
r"""Return a repr string for a method that respects line width.
This function is useful to generate a ``repr`` string for a derived
class that is created through a method, for instance ::
funct... | python | {
"resource": ""
} |
q35627 | pkg_supports | train | def pkg_supports(feature, pkg_version, pkg_feat_dict):
"""Return bool indicating whether a package supports ``feature``.
Parameters
----------
feature : str
Name of a potential feature of a package.
pkg_version : str
Version of the package that should be checked for presence of the
... | python | {
"resource": ""
} |
q35628 | unique | train | def unique(seq):
"""Return the unique values in a sequence.
Parameters
----------
seq : sequence
Sequence with (possibly duplicate) elements.
Returns
-------
unique : list
Unique elements of ``seq``.
Order is guaranteed to be the same as in seq.
Examples
--... | python | {
"resource": ""
} |
q35629 | vector | train | def vector(array, dtype=None, order=None, impl='numpy'):
"""Create a vector from an array-like object.
Parameters
----------
array : `array-like`
Array from which to create the vector. Scalars become
one-dimensional vectors.
dtype : optional
Set the data type of the vector m... | python | {
"resource": ""
} |
q35630 | tensor_space | train | def tensor_space(shape, dtype=None, impl='numpy', **kwargs):
"""Return a tensor space with arbitrary scalar data type.
Parameters
----------
shape : positive int or sequence of positive ints
Number of entries per axis for elements in this space. A
single integer results in a space with ... | python | {
"resource": ""
} |
q35631 | cn | train | def cn(shape, dtype=None, impl='numpy', **kwargs):
"""Return a space of complex tensors.
Parameters
----------
shape : positive int or sequence of positive ints
Number of entries per axis for elements in this space. A
single integer results in a space with 1 axis.
dtype : optional
... | python | {
"resource": ""
} |
q35632 | rn | train | def rn(shape, dtype=None, impl='numpy', **kwargs):
"""Return a space of real tensors.
Parameters
----------
shape : positive int or sequence of positive ints
Number of entries per axis for elements in this space. A
single integer results in a space with 1 axis.
dtype : optional
... | python | {
"resource": ""
} |
q35633 | WaveletTransformBase.scales | train | def scales(self):
"""Get the scales of each coefficient.
Returns
-------
scales : ``range`` element
The scale of each coefficient, given by an integer. 0 for the
lowest resolution and self.nlevels for the highest.
"""
if self.impl == 'pywt':
... | python | {
"resource": ""
} |
q35634 | WaveletTransform._call | train | def _call(self, x):
"""Return wavelet transform of ``x``."""
if self.impl == 'pywt':
coeffs = pywt.wavedecn(
x, wavelet=self.pywt_wavelet, level=self.nlevels,
mode=self.pywt_pad_mode, axes=self.axes)
return pywt.ravel_coeffs(coeffs, axes=self.axes)... | python | {
"resource": ""
} |
q35635 | WaveletTransform.adjoint | train | def adjoint(self):
"""Adjoint wavelet transform.
Returns
-------
adjoint : `WaveletTransformInverse`
If the transform is orthogonal, the adjoint is the inverse.
Raises
------
OpNotImplementedError
if `is_orthogonal` is ``False``
"... | python | {
"resource": ""
} |
q35636 | WaveletTransform.inverse | train | def inverse(self):
"""Inverse wavelet transform.
Returns
-------
inverse : `WaveletTransformInverse`
See Also
--------
adjoint
"""
return WaveletTransformInverse(
range=self.domain, wavelet=self.pywt_wavelet, nlevels=self.nlevels,
... | python | {
"resource": ""
} |
q35637 | WaveletTransformInverse._call | train | def _call(self, coeffs):
"""Return the inverse wavelet transform of ``coeffs``."""
if self.impl == 'pywt':
coeffs = pywt.unravel_coeffs(coeffs,
coeff_slices=self._coeff_slices,
coeff_shapes=self._coeff_shapes,
... | python | {
"resource": ""
} |
q35638 | pdhg | train | def pdhg(x, f, g, A, tau, sigma, niter, **kwargs):
"""Computes a saddle point with PDHG.
This algorithm is the same as "algorithm 1" in [CP2011a] but with
extrapolation on the dual variable.
Parameters
----------
x : primal variable
This variable is both input and output of the method... | python | {
"resource": ""
} |
q35639 | da_spdhg | train | def da_spdhg(x, f, g, A, tau, sigma_tilde, niter, mu, **kwargs):
r"""Computes a saddle point with a PDHG and dual acceleration.
It therefore requires the functionals f*_i to be mu[i] strongly convex.
Parameters
----------
x : primal variable
This variable is both input and output of the me... | python | {
"resource": ""
} |
q35640 | LinearSpace.dist | train | def dist(self, x1, x2):
"""Return the distance between ``x1`` and ``x2``.
Parameters
----------
x1, x2 : `LinearSpaceElement`
Elements whose distance to compute.
Returns
-------
dist : float
Distance between ``x1`` and ``x2``.
"""... | python | {
"resource": ""
} |
q35641 | LinearSpace.inner | train | def inner(self, x1, x2):
"""Return the inner product of ``x1`` and ``x2``.
Parameters
----------
x1, x2 : `LinearSpaceElement`
Elements whose inner product to compute.
Returns
-------
inner : `LinearSpace.field` element
Inner product of `... | python | {
"resource": ""
} |
q35642 | LinearSpace.multiply | train | def multiply(self, x1, x2, out=None):
"""Return the pointwise product of ``x1`` and ``x2``.
Parameters
----------
x1, x2 : `LinearSpaceElement`
Multiplicands in the product.
out : `LinearSpaceElement`, optional
Element to which the result is written.
... | python | {
"resource": ""
} |
q35643 | LinearSpace.divide | train | def divide(self, x1, x2, out=None):
"""Return the pointwise quotient of ``x1`` and ``x2``
Parameters
----------
x1 : `LinearSpaceElement`
Dividend in the quotient.
x2 : `LinearSpaceElement`
Divisor in the quotient.
out : `LinearSpaceElement`, opti... | python | {
"resource": ""
} |
q35644 | pywt_wavelet | train | def pywt_wavelet(wavelet):
"""Convert ``wavelet`` to a `pywt.Wavelet` instance."""
if isinstance(wavelet, pywt.Wavelet):
return wavelet
else:
return pywt.Wavelet(wavelet) | python | {
"resource": ""
} |
q35645 | pywt_pad_mode | train | def pywt_pad_mode(pad_mode, pad_const=0):
"""Convert ODL-style padding mode to pywt-style padding mode.
Parameters
----------
pad_mode : str
The ODL padding mode to use at the boundaries.
pad_const : float, optional
Value to use outside the signal boundaries when ``pad_mode`` is
... | python | {
"resource": ""
} |
q35646 | precompute_raveled_slices | train | def precompute_raveled_slices(coeff_shapes, axes=None):
"""Return slices and shapes for raveled multilevel wavelet coefficients.
The output is equivalent to the ``coeff_slices`` output of
`pywt.ravel_coeffs`, but this function does not require computing a
wavelet transform first.
Parameters
--... | python | {
"resource": ""
} |
q35647 | combine_proximals | train | def combine_proximals(*factory_list):
r"""Combine proximal operators into a diagonal product space operator.
This assumes the functional to be separable across variables in order to
make use of the separable sum property of proximal operators.
Parameters
----------
factory_list : sequence of c... | python | {
"resource": ""
} |
q35648 | proximal_convex_conj | train | def proximal_convex_conj(prox_factory):
r"""Calculate the proximal of the dual using Moreau decomposition.
Parameters
----------
prox_factory : callable
A factory function that, when called with a step size, returns the
proximal operator of ``F``
Returns
-------
prox_factor... | python | {
"resource": ""
} |
q35649 | proximal_composition | train | def proximal_composition(proximal, operator, mu):
r"""Proximal operator factory of functional composed with unitary operator.
For a functional ``F`` and a linear unitary `Operator` ``L`` this is the
factory for the proximal operator of ``F * L``.
Parameters
----------
proximal : callable
... | python | {
"resource": ""
} |
q35650 | proximal_convex_conj_l2_squared | train | def proximal_convex_conj_l2_squared(space, lam=1, g=None):
r"""Proximal operator factory of the convex conj of the squared l2-dist
Function for the proximal operator of the convex conjugate of the
functional F where F is the l2-norm (or distance to g, if given)::
F(x) = lam ||x - g||_2^2
wit... | python | {
"resource": ""
} |
q35651 | proximal_linfty | train | def proximal_linfty(space):
r"""Proximal operator factory of the ``l_\infty``-norm.
Function for the proximal operator of the functional ``F`` where ``F``
is the ``l_\infty``-norm::
``F(x) = \sup_i |x_i|``
Parameters
----------
space : `LinearSpace`
Domain of ``F``.
Retu... | python | {
"resource": ""
} |
q35652 | proj_l1 | train | def proj_l1(x, radius=1, out=None):
r"""Projection onto l1-ball.
Projection onto::
``{ x \in X | ||x||_1 \leq r}``
with ``r`` being the radius.
Parameters
----------
space : `LinearSpace`
Space / domain ``X``.
radius : positive float, optional
Radius ``r`` of the ... | python | {
"resource": ""
} |
q35653 | proj_simplex | train | def proj_simplex(x, diameter=1, out=None):
r"""Projection onto simplex.
Projection onto::
``{ x \in X | x_i \geq 0, \sum_i x_i = r}``
with :math:`r` being the diameter. It is computed by the formula proposed
in [D+2008].
Parameters
----------
space : `LinearSpace`
Space /... | python | {
"resource": ""
} |
q35654 | proximal_convex_conj_kl | train | def proximal_convex_conj_kl(space, lam=1, g=None):
r"""Proximal operator factory of the convex conjugate of the KL divergence.
Function returning the proximal operator of the convex conjugate of the
functional F where F is the entropy-type Kullback-Leibler (KL) divergence::
F(x) = sum_i (x_i - g_i... | python | {
"resource": ""
} |
q35655 | proximal_convex_conj_kl_cross_entropy | train | def proximal_convex_conj_kl_cross_entropy(space, lam=1, g=None):
r"""Proximal factory of the convex conj of cross entropy KL divergence.
Function returning the proximal factory of the convex conjugate of the
functional F, where F is the cross entropy Kullback-Leibler (KL)
divergence given by::
... | python | {
"resource": ""
} |
q35656 | proximal_huber | train | def proximal_huber(space, gamma):
"""Proximal factory of the Huber norm.
Parameters
----------
space : `TensorSpace`
The domain of the functional
gamma : float
The smoothing parameter of the Huber norm functional.
Returns
-------
prox_factory : function
Factory ... | python | {
"resource": ""
} |
q35657 | mri_head_reco_op_32_channel | train | def mri_head_reco_op_32_channel():
"""Reconstruction operator for 32 channel MRI of a head.
This is a T2 weighted TSE scan of a healthy volunteer.
The reconstruction operator is the sum of the modulus of each channel.
See the data source with DOI `10.5281/zenodo.800527`_ or the
`project webpage`_... | python | {
"resource": ""
} |
q35658 | mri_knee_data_8_channel | train | def mri_knee_data_8_channel():
"""Raw data for 8 channel MRI of a knee.
This is an SE measurement of the knee of a healthy volunteer.
The data has been rescaled so that the reconstruction fits approximately in
[0, 1].
See the data source with DOI `10.5281/zenodo.800529`_ or the
`project webpa... | python | {
"resource": ""
} |
q35659 | convert_to_odl | train | def convert_to_odl(image):
"""Convert image to ODL object."""
shape = image.shape
if len(shape) == 2:
space = odl.uniform_discr([0, 0], shape, shape)
elif len(shape) == 3:
d = shape[2]
shape = shape[:2]
image = np.transpose(image, (2, 0, 1))
space = odl.uniform_... | python | {
"resource": ""
} |
q35660 | IntervalProd.mid_pt | train | def mid_pt(self):
"""Midpoint of this interval product."""
midp = (self.max_pt + self.min_pt) / 2.
midp[~self.nondegen_byaxis] = self.min_pt[~self.nondegen_byaxis]
return midp | python | {
"resource": ""
} |
q35661 | IntervalProd.element | train | def element(self, inp=None):
"""Return an element of this interval product.
Parameters
----------
inp : float or `array-like`, optional
Point to be cast to an element.
Returns
-------
element : `numpy.ndarray` or float
Array (`ndim` > 1) ... | python | {
"resource": ""
} |
q35662 | IntervalProd.approx_equals | train | def approx_equals(self, other, atol):
"""Return ``True`` if ``other`` is equal to this set up to ``atol``.
Parameters
----------
other :
Object to be tested.
atol : float
Maximum allowed difference in maximum norm between the
interval endpoint... | python | {
"resource": ""
} |
q35663 | IntervalProd.approx_contains | train | def approx_contains(self, point, atol):
"""Return ``True`` if ``point`` is "almost" contained in this set.
Parameters
----------
point : `array-like` or float
Point to be tested. Its length must be equal to `ndim`.
In the 1d case, ``point`` can be given as a floa... | python | {
"resource": ""
} |
q35664 | IntervalProd.contains_all | train | def contains_all(self, other, atol=0.0):
"""Return ``True`` if all points defined by ``other`` are contained.
Parameters
----------
other :
Collection of points to be tested. Can be given as a single
point, a ``(d, N)`` array-like where ``d`` is the
n... | python | {
"resource": ""
} |
q35665 | IntervalProd.measure | train | def measure(self, ndim=None):
"""Return the Lebesgue measure of this interval product.
Parameters
----------
ndim : int, optional
Dimension of the measure to apply. ``None`` is interpreted
as `true_ndim`, which always results in a finite and
positive ... | python | {
"resource": ""
} |
q35666 | IntervalProd.dist | train | def dist(self, point, exponent=2.0):
"""Return the distance of ``point`` to this set.
Parameters
----------
point : `array-like` or float
Point whose distance to calculate. Its length must be equal
to the set's dimension. Can be a float in the 1d case.
ex... | python | {
"resource": ""
} |
q35667 | IntervalProd.collapse | train | def collapse(self, indices, values):
"""Partly collapse the interval product to single values.
Note that no changes are made in-place.
Parameters
----------
indices : int or sequence of ints
The indices of the dimensions along which to collapse.
values : `ar... | python | {
"resource": ""
} |
q35668 | IntervalProd.squeeze | train | def squeeze(self):
"""Remove the degenerate dimensions.
Note that no changes are made in-place.
Returns
-------
squeezed : `IntervalProd`
Squeezed set.
Examples
--------
>>> min_pt, max_pt = [-1, 0, 2], [-0.5, 1, 3]
>>> rbox = Interv... | python | {
"resource": ""
} |
q35669 | IntervalProd.insert | train | def insert(self, index, *intvs):
"""Return a copy with ``intvs`` inserted before ``index``.
The given interval products are inserted (as a block) into ``self``,
yielding a new interval product whose number of dimensions is the
sum of the numbers of dimensions of all involved interval pr... | python | {
"resource": ""
} |
q35670 | IntervalProd.corners | train | def corners(self, order='C'):
"""Return the corner points as a single array.
Parameters
----------
order : {'C', 'F'}, optional
Ordering of the axes in which the corners appear in
the output. ``'C'`` means that the first axis varies slowest
and the la... | python | {
"resource": ""
} |
q35671 | RayTransform._call_real | train | def _call_real(self, x_real, out_real):
"""Real-space forward projection for the current set-up.
This method also sets ``self._astra_projector`` for
``impl='astra_cuda'`` and enabled cache.
"""
if self.impl.startswith('astra'):
backend, data_impl = self.impl.split('_... | python | {
"resource": ""
} |
q35672 | RayBackProjection._call_real | train | def _call_real(self, x_real, out_real):
"""Real-space back-projection for the current set-up.
This method also sets ``self._astra_backprojector`` for
``impl='astra_cuda'`` and enabled cache.
"""
if self.impl.startswith('astra'):
backend, data_impl = self.impl.split('... | python | {
"resource": ""
} |
q35673 | mlem | train | def mlem(op, x, data, niter, callback=None, **kwargs):
"""Maximum Likelihood Expectation Maximation algorithm.
Attempts to solve::
max_x L(x | data)
where ``L(x | data)`` is the Poisson likelihood of ``x`` given ``data``.
The likelihood depends on the forward operator ``op`` such that
(a... | python | {
"resource": ""
} |
q35674 | osmlem | train | def osmlem(op, x, data, niter, callback=None, **kwargs):
r"""Ordered Subsets Maximum Likelihood Expectation Maximation algorithm.
This solver attempts to solve::
max_x L(x | data)
where ``L(x, | data)`` is the likelihood of ``x`` given ``data``. The
likelihood depends on the forward operators... | python | {
"resource": ""
} |
q35675 | poisson_log_likelihood | train | def poisson_log_likelihood(x, data):
"""Poisson log-likelihood of ``data`` given noise parametrized by ``x``.
Parameters
----------
x : ``op.domain`` element
Value to condition the log-likelihood on.
data : ``op.range`` element
Data whose log-likelihood given ``x`` shall be calculat... | python | {
"resource": ""
} |
q35676 | fom | train | def fom(reco, true_image):
"""Sobolev type FoM enforcing both gradient and absolute similarity."""
gradient = odl.Gradient(reco.space)
return (gradient(reco - true_image).norm() +
reco.space.dist(reco, true_image)) | python | {
"resource": ""
} |
q35677 | astra_cuda_bp_scaling_factor | train | def astra_cuda_bp_scaling_factor(proj_space, reco_space, geometry):
"""Volume scaling accounting for differing adjoint definitions.
ASTRA defines the adjoint operator in terms of a fully discrete
setting (transposed "projection matrix") without any relation to
physical dimensions, which makes a re-scal... | python | {
"resource": ""
} |
q35678 | AstraCudaProjectorImpl.call_forward | train | def call_forward(self, vol_data, out=None):
"""Run an ASTRA forward projection on the given data using the GPU.
Parameters
----------
vol_data : ``reco_space`` element
Volume data to which the projector is applied.
out : ``proj_space`` element, optional
E... | python | {
"resource": ""
} |
q35679 | AstraCudaProjectorImpl.create_ids | train | def create_ids(self):
"""Create ASTRA objects."""
# Create input and output arrays
if self.geometry.motion_partition.ndim == 1:
motion_shape = self.geometry.motion_partition.shape
else:
# Need to flatten 2- or 3-dimensional angles into one axis
motion_... | python | {
"resource": ""
} |
q35680 | AstraCudaBackProjectorImpl.call_backward | train | def call_backward(self, proj_data, out=None):
"""Run an ASTRA back-projection on the given data using the GPU.
Parameters
----------
proj_data : ``proj_space`` element
Projection data to which the back-projector is applied.
out : ``reco_space`` element, optional
... | python | {
"resource": ""
} |
q35681 | find_min_signature | train | def find_min_signature(ufunc, dtypes_in):
"""Determine the minimum matching ufunc signature for given dtypes.
Parameters
----------
ufunc : str or numpy.ufunc
Ufunc whose signatures are to be considered.
dtypes_in :
Sequence of objects specifying input dtypes. Its length must match
... | python | {
"resource": ""
} |
q35682 | gradient_factory | train | def gradient_factory(name):
"""Create gradient `Functional` for some ufuncs."""
if name == 'sin':
def gradient(self):
"""Return the gradient operator."""
return cos(self.domain)
elif name == 'cos':
def gradient(self):
"""Return the gradient operator."""
... | python | {
"resource": ""
} |
q35683 | derivative_factory | train | def derivative_factory(name):
"""Create derivative function for some ufuncs."""
if name == 'sin':
def derivative(self, point):
"""Return the derivative operator."""
return MultiplyOperator(cos(self.domain)(point))
elif name == 'cos':
def derivative(self, point):
... | python | {
"resource": ""
} |
q35684 | ufunc_functional_factory | train | def ufunc_functional_factory(name, nargin, nargout, docstring):
"""Create a ufunc `Functional` from a given specification."""
assert 0 <= nargin <= 2
def __init__(self, field):
"""Initialize an instance.
Parameters
----------
field : `Field`
The domain of the f... | python | {
"resource": ""
} |
q35685 | pdhg_stepsize | train | def pdhg_stepsize(L, tau=None, sigma=None):
r"""Default step sizes for `pdhg`.
Parameters
----------
L : `Operator` or float
Operator or norm of the operator that are used in the `pdhg` method.
If it is an `Operator`, the norm is computed with
``Operator.norm(estimate=True)``.
... | python | {
"resource": ""
} |
q35686 | haarpsi_similarity_map | train | def haarpsi_similarity_map(img1, img2, axis, c, a):
r"""Local similarity map for directional features along an axis.
Parameters
----------
img1, img2 : array-like
The images to compare. They must have equal shape.
axis : {0, 1}
Direction in which to look for edge similarities.
c... | python | {
"resource": ""
} |
q35687 | haarpsi_weight_map | train | def haarpsi_weight_map(img1, img2, axis):
r"""Weighting map for directional features along an axis.
Parameters
----------
img1, img2 : array-like
The images to compare. They must have equal shape.
axis : {0, 1}
Direction in which to look for edge similarities.
Returns
-----... | python | {
"resource": ""
} |
q35688 | spherical_sum | train | def spherical_sum(image, binning_factor=1.0):
"""Sum image values over concentric annuli.
Parameters
----------
image : `DiscreteLp` element
Input data whose radial sum should be computed.
binning_factor : positive float, optional
Reduce the number of output bins by this factor. Inc... | python | {
"resource": ""
} |
q35689 | simple_functional | train | def simple_functional(space, fcall=None, grad=None, prox=None, grad_lip=np.nan,
convex_conj_fcall=None, convex_conj_grad=None,
convex_conj_prox=None, convex_conj_grad_lip=np.nan,
linear=False):
"""Simplified interface to create a functional with spec... | python | {
"resource": ""
} |
q35690 | FunctionalLeftScalarMult.convex_conj | train | def convex_conj(self):
"""Convex conjugate functional of the scaled functional.
``Functional.__rmul__`` takes care of the case scalar = 0.
"""
if self.scalar <= 0:
raise ValueError('scaling with nonpositive values have no convex '
'conjugate. Cur... | python | {
"resource": ""
} |
q35691 | FunctionalLeftScalarMult.proximal | train | def proximal(self):
"""Proximal factory of the scaled functional.
``Functional.__rmul__`` takes care of the case scalar = 0
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_const_func
"""
if self.scalar < 0:
raise ValueError('prox... | python | {
"resource": ""
} |
q35692 | FunctionalComp.gradient | train | def gradient(self):
"""Gradient of the compositon according to the chain rule."""
func = self.left
op = self.right
class FunctionalCompositionGradient(Operator):
"""Gradient of the compositon according to the chain rule."""
def __init__(self):
"... | python | {
"resource": ""
} |
q35693 | FunctionalQuadraticPerturb.proximal | train | def proximal(self):
"""Proximal factory of the quadratically perturbed functional."""
if self.quadratic_coeff < 0:
raise TypeError('`quadratic_coeff` {} must be non-negative'
''.format(self.quadratic_coeff))
return proximal_quadratic_perturbation(
... | python | {
"resource": ""
} |
q35694 | FunctionalQuadraticPerturb.convex_conj | train | def convex_conj(self):
r"""Convex conjugate functional of the functional.
Notes
-----
Given a functional :math:`f`, the convex conjugate of a linearly
perturbed version :math:`f(x) + <y, x>` is given by a translation of
the convex conjugate of :math:`f`:
.. math... | python | {
"resource": ""
} |
q35695 | estimate_noise_std | train | def estimate_noise_std(img, average=True):
"""Estimate standard deviation of noise in ``img``.
The algorithm, given in [Immerkaer1996], estimates the noise in an image.
Parameters
----------
img : array-like
Array to estimate noise in.
average : bool
If ``True``, return the mea... | python | {
"resource": ""
} |
q35696 | cone_beam_geometry | train | def cone_beam_geometry(space, src_radius, det_radius, num_angles=None,
short_scan=False, det_shape=None):
r"""Create a default fan or cone beam geometry from ``space``.
This function is intended for simple test cases where users do not
need the full flexibility of the geometries, but... | python | {
"resource": ""
} |
q35697 | helical_geometry | train | def helical_geometry(space, src_radius, det_radius, num_turns,
n_pi=1, num_angles=None, det_shape=None):
"""Create a default helical geometry from ``space``.
This function is intended for simple test cases where users do not
need the full flexibility of the geometries, but simply wants... | python | {
"resource": ""
} |
q35698 | FanBeamGeometry.frommatrix | train | def frommatrix(cls, apart, dpart, src_radius, det_radius, init_matrix,
det_curvature_radius=None, **kwargs):
"""Create an instance of `FanBeamGeometry` using a matrix.
This alternative constructor uses a matrix to rotate and
translate the default configuration. It is most use... | python | {
"resource": ""
} |
q35699 | FanBeamGeometry.src_position | train | def src_position(self, angle):
"""Return the source position at ``angle``.
For an angle ``phi``, the source position is given by ::
src(phi) = translation +
rot_matrix(phi) * (-src_rad * src_to_det_init)
where ``src_to_det_init`` is the initial unit vector p... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.