_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q35300
LinCombOperator._call
train
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
{ "resource": "" }
q35301
MultiplyOperator._call
train
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: ou...
python
{ "resource": "" }
q35302
PowerOperator._call
train
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 **= se...
python
{ "resource": "" }
q35303
NormOperator.derivative
train
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 whi...
python
{ "resource": "" }
q35304
DistOperator.derivative
train
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 whic...
python
{ "resource": "" }
q35305
ConstantOperator._call
train
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
{ "resource": "" }
q35306
ConstantOperator.derivative
train
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.derivativ...
python
{ "resource": "" }
q35307
ZeroOperator._call
train
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: ...
python
{ "resource": "" }
q35308
ImagPart.inverse
train
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 in...
python
{ "resource": "" }
q35309
convert
train
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/o...
python
{ "resource": "" }
q35310
resolution_phantom
train
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 d...
python
{ "resource": "" }
q35311
building
train
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...
python
{ "resource": "" }
q35312
blurring_kernel
train
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: flo...
python
{ "resource": "" }
q35313
TensorSpace.real_space
train
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...
python
{ "resource": "" }
q35314
TensorSpace.complex_space
train
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 de...
python
{ "resource": "" }
q35315
TensorSpace.examples
train
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.s...
python
{ "resource": "" }
q35316
astra_supports
train
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 c...
python
{ "resource": "" }
q35317
astra_volume_geometry
train
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 ...
python
{ "resource": "" }
q35318
astra_projection_geometry
train
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 : `Geometr...
python
{ "resource": "" }
q35319
astra_data
train
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 ...
python
{ "resource": "" }
q35320
astra_projector
train
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 cho...
python
{ "resource": "" }
q35321
astra_algorithm
train
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...
python
{ "resource": "" }
q35322
space_shape
train
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[...
python
{ "resource": "" }
q35323
Convolution._call
train
def _call(self, x): """Implement calling the operator by calling scipy.""" return scipy.signal.fftconvolve(self.kernel, x, mode='same')
python
{ "resource": "" }
q35324
apply_on_boundary
train
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...
python
{ "resource": "" }
q35325
fast_1d_tensor_mult
train
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.ran...
python
{ "resource": "" }
q35326
_intersection_slice_tuples
train
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 i...
python
{ "resource": "" }
q35327
_assign_intersection
train
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
{ "resource": "" }
q35328
_padding_slices_outer
train
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 ``ax...
python
{ "resource": "" }
q35329
_padding_slices_inner
train
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...
python
{ "resource": "" }
q35330
zscore
train
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: ...
python
{ "resource": "" }
q35331
FunctionSpace.real_out_dtype
train
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: ...
python
{ "resource": "" }
q35332
FunctionSpace.complex_out_dtype
train
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))) els...
python
{ "resource": "" }
q35333
FunctionSpace.zero
train
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):...
python
{ "resource": "" }
q35334
FunctionSpace.one
train
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) e...
python
{ "resource": "" }
q35335
FunctionSpace.astype
train
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-...
python
{ "resource": "" }
q35336
FunctionSpace._lincomb
train
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 ...
python
{ "resource": "" }
q35337
FunctionSpace._multiply
train
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 funct...
python
{ "resource": "" }
q35338
FunctionSpace._scalar_power
train
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 isin...
python
{ "resource": "" }
q35339
FunctionSpace._realpart
train
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): ...
python
{ "resource": "" }
q35340
FunctionSpace._imagpart
train
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): ...
python
{ "resource": "" }
q35341
FunctionSpace._conj
train
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): re...
python
{ "resource": "" }
q35342
FunctionSpace.byaxis_out
train
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...
python
{ "resource": "" }
q35343
FunctionSpace.byaxis_in
train
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(...
python
{ "resource": "" }
q35344
FunctionSpaceElement._call
train
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
{ "resource": "" }
q35345
FunctionSpaceElement.assign
train
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 elem...
python
{ "resource": "" }
q35346
optimal_parameters
train
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 o...
python
{ "resource": "" }
q35347
OperatorAsAutogradFunction.forward
train
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 holdin...
python
{ "resource": "" }
q35348
OperatorAsAutogradFunction.backward
train
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._TensorBa...
python
{ "resource": "" }
q35349
OperatorAsModule.forward
train
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_shap...
python
{ "resource": "" }
q35350
mean_squared_error
train
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 -...
python
{ "resource": "" }
q35351
mean_absolute_error
train
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 ---------- ...
python
{ "resource": "" }
q35352
mean_value_difference
train
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 ...
python
{ "resource": "" }
q35353
standard_deviation_difference
train
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...
python
{ "resource": "" }
q35354
range_difference
train
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 normali...
python
{ "resource": "" }
q35355
blurring
train
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 --------...
python
{ "resource": "" }
q35356
false_structures_mask
train
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. ...
python
{ "resource": "" }
q35357
ssim
train
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 `th...
python
{ "resource": "" }
q35358
psnr
train
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...
python
{ "resource": "" }
q35359
haarpsi
train
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/...
python
{ "resource": "" }
q35360
Detector.surface_normal
train
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)`` ...
python
{ "resource": "" }
q35361
Detector.surface_measure
train
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 ...
python
{ "resource": "" }
q35362
CircularDetector.surface_measure
train
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 ----...
python
{ "resource": "" }
q35363
adupdates
train
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 a...
python
{ "resource": "" }
q35364
adupdates_simple
train
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....
python
{ "resource": "" }
q35365
ParallelHoleCollimatorGeometry.frommatrix
train
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 alr...
python
{ "resource": "" }
q35366
_compute_nearest_weights_edge
train
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"...
python
{ "resource": "" }
q35367
_compute_linear_weights_edge
train
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 ne...
python
{ "resource": "" }
q35368
PerAxisInterpolation._call
train
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 ...
python
{ "resource": "" }
q35369
_Interpolator._find_indices
train
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_dista...
python
{ "resource": "" }
q35370
_NearestInterpolator._evaluate
train
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.appe...
python
{ "resource": "" }
q35371
_PerAxisInterpolator._evaluate
train
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 ...
python
{ "resource": "" }
q35372
accelerated_proximal_gradient
train
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. ...
python
{ "resource": "" }
q35373
_blas_is_applicable
train
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 conti...
python
{ "resource": "" }
q35374
_weighting
train
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 poss...
python
{ "resource": "" }
q35375
_norm_default
train
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 ...
python
{ "resource": "" }
q35376
_pnorm_default
train
def _pnorm_default(x, p): """Default p-norm implementation.""" return np.linalg.norm(x.data.ravel(), ord=p)
python
{ "resource": "" }
q35377
_pnorm_diagweight
train
def _pnorm_diagweight(x, p, w): """Diagonally weighted p-norm implementation.""" # Ravel both in the same order (w is a numpy array) order = 'F' if all(a.flags.f_contiguous for a in (x.data, w)) else 'C' # This is faster than first applying the weights and then summing with # BLAS dot or nrm2 x...
python
{ "resource": "" }
q35378
_inner_default
train
def _inner_default(x1, x2): """Default Euclidean inner product implementation.""" # Ravel both in the same order order = 'F' if all(a.data.flags.f_contiguous for a in (x1, x2)) else 'C' if is_real_dtype(x1.dtype): if x1.size > THRESHOLD_MEDIUM: # This is as fast as BLAS dotc ...
python
{ "resource": "" }
q35379
NumpyTensorSpace.zero
train
def zero(self): """Return a tensor of all zeros. Examples -------- >>> space = odl.rn(3) >>> x = space.zero() >>> x rn(3).element([ 0., 0., 0.]) """ return self.element(np.zeros(self.shape, dtype=self.dtype, ...
python
{ "resource": "" }
q35380
NumpyTensorSpace.one
train
def one(self): """Return a tensor of all ones. Examples -------- >>> space = odl.rn(3) >>> x = space.one() >>> x rn(3).element([ 1., 1., 1.]) """ return self.element(np.ones(self.shape, dtype=self.dtype, order...
python
{ "resource": "" }
q35381
NumpyTensorSpace.available_dtypes
train
def available_dtypes(): """Return the set of data types available in this implementation. Notes ----- This is all dtypes available in Numpy. See ``numpy.sctypes`` for more information. The available dtypes may depend on the specific system used. """ all_...
python
{ "resource": "" }
q35382
NumpyTensorSpace.default_dtype
train
def default_dtype(field=None): """Return the default data type of this class for a given field. Parameters ---------- field : `Field`, optional Set of numbers to be represented by a data type. Currently supported : `RealNumbers`, `ComplexNumbers` The ...
python
{ "resource": "" }
q35383
NumpyTensorSpace._lincomb
train
def _lincomb(self, a, x1, b, x2, out): """Implement the linear combination of ``x1`` and ``x2``. Compute ``out = a*x1 + b*x2`` using optimized BLAS routines if possible. This function is part of the subclassing API. Do not call it directly. Parameters ---------...
python
{ "resource": "" }
q35384
NumpyTensorSpace.byaxis
train
def byaxis(self): """Return the subspace defined along one or several dimensions. Examples -------- Indexing with integers or slices: >>> space = odl.rn((2, 3, 4)) >>> space.byaxis[0] rn(2) >>> space.byaxis[1:] rn((3, 4)) Lists can be us...
python
{ "resource": "" }
q35385
NumpyTensor.asarray
train
def asarray(self, out=None): """Extract the data of this array as a ``numpy.ndarray``. This method is invoked when calling `numpy.asarray` on this tensor. Parameters ---------- out : `numpy.ndarray`, optional Array in which the result should be written in-pl...
python
{ "resource": "" }
q35386
NumpyTensor.imag
train
def imag(self): """Imaginary part of ``self``. Returns ------- imag : `NumpyTensor` Imaginary part this element as an element of a `NumpyTensorSpace` with real data type. Examples -------- Get the imaginary part: >>> space = odl....
python
{ "resource": "" }
q35387
NumpyTensor.conj
train
def conj(self, out=None): """Return the complex conjugate of ``self``. Parameters ---------- out : `NumpyTensor`, optional Element to which the complex conjugate is written. Must be an element of ``self.space``. Returns ------- out : `Num...
python
{ "resource": "" }
q35388
NumpyTensorSpaceConstWeighting.dist
train
def dist(self, x1, x2): """Return the weighted distance between ``x1`` and ``x2``. Parameters ---------- x1, x2 : `NumpyTensor` Tensors whose mutual distance is calculated. Returns ------- dist : float The distance between the tensors. ...
python
{ "resource": "" }
q35389
CallbackProgressBar.reset
train
def reset(self): """Set `iter` to 0.""" import tqdm self.iter = 0 self.pbar = tqdm.tqdm(total=self.niter, **self.kwargs)
python
{ "resource": "" }
q35390
warning_free_pause
train
def warning_free_pause(): """Issue a matplotlib pause without the warning.""" import matplotlib.pyplot as plt with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Using default event loop until " "function...
python
{ "resource": "" }
q35391
_safe_minmax
train
def _safe_minmax(values): """Calculate min and max of array with guards for nan and inf.""" # Nan and inf guarded min and max isfinite = np.isfinite(values) if np.any(isfinite): # Only use finite values values = values[isfinite] minval = np.min(values) maxval = np.max(values) ...
python
{ "resource": "" }
q35392
_colorbar_format
train
def _colorbar_format(minval, maxval): """Return the format string for the colorbar.""" if not (np.isfinite(minval) and np.isfinite(maxval)): return str(maxval) else: return '%.{}f'.format(_digits(minval, maxval))
python
{ "resource": "" }
q35393
import_submodules
train
def import_submodules(package, name=None, recursive=True): """Import all submodules of ``package``. Parameters ---------- package : `module` or string Package whose submodules to import. name : string, optional Override the package name with this value in the full submodule ...
python
{ "resource": "" }
q35394
make_interface
train
def make_interface(): """Generate the RST files for the API doc of ODL.""" modnames = ['odl'] + list(import_submodules(odl).keys()) for modname in modnames: if not modname.startswith('odl'): modname = 'odl.' + modname shortmodname = modname.split('.')[-1] print('{: <25}...
python
{ "resource": "" }
q35395
LpNorm._call
train
def _call(self, x): """Return the Lp-norm of ``x``.""" if self.exponent == 0: return self.domain.one().inner(np.not_equal(x, 0)) elif self.exponent == 1: return x.ufuncs.absolute().inner(self.domain.one()) elif self.exponent == 2: return np.sqrt(x.inne...
python
{ "resource": "" }
q35396
GroupL1Norm._call
train
def _call(self, x): """Return the group L1-norm of ``x``.""" # TODO: update when integration operator is in place: issue #440 pointwise_norm = self.pointwise_norm(x) return pointwise_norm.inner(pointwise_norm.space.one())
python
{ "resource": "" }
q35397
GroupL1Norm.convex_conj
train
def convex_conj(self): """The convex conjugate functional of the group L1-norm.""" conj_exp = conj_exponent(self.pointwise_norm.exponent) return IndicatorGroupL1UnitBall(self.domain, exponent=conj_exp)
python
{ "resource": "" }
q35398
IndicatorGroupL1UnitBall.convex_conj
train
def convex_conj(self): """Convex conjugate functional of IndicatorLpUnitBall. Returns ------- convex_conj : GroupL1Norm The convex conjugate is the the group L1-norm. """ conj_exp = conj_exponent(self.pointwise_norm.exponent) return GroupL1Norm(self.d...
python
{ "resource": "" }
q35399
IndicatorLpUnitBall.convex_conj
train
def convex_conj(self): """The conjugate functional of IndicatorLpUnitBall. The convex conjugate functional of an ``Lp`` norm, ``p < infty`` is the indicator function on the unit ball defined by the corresponding dual norm ``q``, given by ``1/p + 1/q = 1`` and where ``q = infty`` if ...
python
{ "resource": "" }