_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q35400 | KullbackLeibler.gradient | train | def gradient(self):
r"""Gradient of the KL functional.
The gradient of `KullbackLeibler` with ``prior`` :math:`g` is given
as
.. math::
\nabla F(x) = 1 - \frac{g}{x}.
The gradient is not defined in points where one or more components
are non-positive.
... | python | {
"resource": ""
} |
q35401 | KullbackLeiblerCrossEntropyConvexConj._call | train | def _call(self, x):
"""Return the value in the point ``x``."""
if self.prior is None:
tmp = self.domain.element((np.exp(x) - 1)).inner(self.domain.one())
else:
tmp = (self.prior * (np.exp(x) - 1)).inner(self.domain.one())
return tmp | python | {
"resource": ""
} |
q35402 | SeparableSum._call | train | def _call(self, x):
"""Return the separable sum evaluated in ``x``."""
return sum(fi(xi) for xi, fi in zip(x, self.functionals)) | python | {
"resource": ""
} |
q35403 | SeparableSum.convex_conj | train | def convex_conj(self):
"""The convex conjugate functional.
Convex conjugate distributes over separable sums, so the result is
simply the separable sum of the convex conjugates.
"""
convex_conjs = [func.convex_conj for func in self.functionals]
return SeparableSum(*convex... | python | {
"resource": ""
} |
q35404 | QuadraticForm.convex_conj | train | def convex_conj(self):
r"""The convex conjugate functional of the quadratic form.
Notes
-----
The convex conjugate of the quadratic form :math:`<x, Ax> + <b, x> + c`
is given by
.. math::
(<x, Ax> + <b, x> + c)^* (x) =
<(x - b), A^-1 (x - b)> - c... | python | {
"resource": ""
} |
q35405 | NuclearNorm._asarray | train | def _asarray(self, vec):
"""Convert ``x`` to an array.
Here the indices are changed such that the "outer" indices come last
in order to have the access order as `numpy.linalg.svd` needs it.
This is the inverse of `_asvector`.
"""
shape = self.domain[0, 0].shape + self.p... | python | {
"resource": ""
} |
q35406 | NuclearNorm._asvector | train | def _asvector(self, arr):
"""Convert ``arr`` to a `domain` element.
This is the inverse of `_asarray`.
"""
result = moveaxis(arr, [-2, -1], [0, 1])
return self.domain.element(result) | python | {
"resource": ""
} |
q35407 | NuclearNorm.proximal | train | def proximal(self):
"""Return the proximal operator.
Raises
------
NotImplementedError
if ``outer_exp`` is not 1 or ``singular_vector_exp`` is not 1, 2 or
infinity
"""
if self.outernorm.exponent != 1:
raise NotImplementedError('`proxim... | python | {
"resource": ""
} |
q35408 | NuclearNorm.convex_conj | train | def convex_conj(self):
"""Convex conjugate of the nuclear norm.
The convex conjugate is the indicator function on the unit ball of
the dual norm where the dual norm is obtained by taking the conjugate
exponent of both the outer and singular vector exponents.
"""
return I... | python | {
"resource": ""
} |
q35409 | IndicatorNuclearNormUnitBall.convex_conj | train | def convex_conj(self):
"""Convex conjugate of the unit ball indicator of the nuclear norm.
The convex conjugate is the dual nuclear norm where the dual norm is
obtained by taking the conjugate exponent of both the outer and
singular vector exponents.
"""
return NuclearNo... | python | {
"resource": ""
} |
q35410 | Huber.convex_conj | train | def convex_conj(self):
"""The convex conjugate"""
if isinstance(self.domain, ProductSpace):
norm = GroupL1Norm(self.domain, 2)
else:
norm = L1Norm(self.domain)
return FunctionalQuadraticPerturb(norm.convex_conj,
quadratic... | python | {
"resource": ""
} |
q35411 | TheanoOperator.make_node | train | def make_node(self, x):
"""Create a node for the computation graph.
Parameters
----------
x : `theano.tensor.var.TensorVariable`
Input to the node.
Returns
-------
node : `theano.gof.graph.Apply`
Node for the Theano expression graph. Its ... | python | {
"resource": ""
} |
q35412 | TheanoOperator.perform | train | def perform(self, node, inputs, output_storage):
"""Evaluate this node's computation.
Parameters
----------
node : `theano.gof.graph.Apply`
The node of this Op in the computation graph.
inputs : 1-element list of arrays
Contains an array (usually `numpy.n... | python | {
"resource": ""
} |
q35413 | TheanoOperator.infer_shape | train | def infer_shape(self, node, input_shapes):
"""Return a list of output shapes based on ``input_shapes``.
This method is optional. It allows to compute the shape of the
output without having to evaluate.
Parameters
----------
node : `theano.gof.graph.Apply`
Th... | python | {
"resource": ""
} |
q35414 | TheanoOperator.R_op | train | def R_op(self, inputs, eval_points):
"""Apply the adjoint of the Jacobian at ``inputs`` to ``eval_points``.
This is the symbolic counterpart of ODL's ::
op.derivative(x).adjoint(v)
See `grad` for its usage.
Parameters
----------
inputs : 1-element list of ... | python | {
"resource": ""
} |
q35415 | reciprocal_grid | train | def reciprocal_grid(grid, shift=True, axes=None, halfcomplex=False):
"""Return the reciprocal of the given regular grid.
This function calculates the reciprocal (Fourier/frequency space)
grid for a given regular grid defined by the nodes::
x[k] = x[0] + k * s,
where ``k = (k[0], ..., k[d-1])`... | python | {
"resource": ""
} |
q35416 | realspace_grid | train | def realspace_grid(recip_grid, x0, axes=None, halfcomplex=False,
halfcx_parity='even'):
"""Return the real space grid from the given reciprocal grid.
Given a reciprocal grid::
xi[j] = xi[0] + j * sigma,
with a multi-index ``j = (j[0], ..., j[d-1])`` in the range
``0 <= j < ... | python | {
"resource": ""
} |
q35417 | dft_preprocess_data | train | def dft_preprocess_data(arr, shift=True, axes=None, sign='-', out=None):
"""Pre-process the real-space data before DFT.
This function multiplies the given data with the separable
function::
p(x) = exp(+- 1j * dot(x - x[0], xi[0]))
where ``x[0]`` and ``xi[0]`` are the minimum coodinates of
... | python | {
"resource": ""
} |
q35418 | _interp_kernel_ft | train | def _interp_kernel_ft(norm_freqs, interp):
"""Scaled FT of a one-dimensional interpolation kernel.
For normalized frequencies ``-1/2 <= xi <= 1/2``, this
function returns::
sinc(pi * xi)**k / sqrt(2 * pi)
where ``k=1`` for 'nearest' and ``k=2`` for 'linear' interpolation.
Parameters
... | python | {
"resource": ""
} |
q35419 | dft_postprocess_data | train | def dft_postprocess_data(arr, real_grid, recip_grid, shift, axes,
interp, sign='-', op='multiply', out=None):
"""Post-process the Fourier-space data after DFT.
This function multiplies the given data with the separable
function::
q(xi) = exp(+- 1j * dot(x[0], xi)) * s * ph... | python | {
"resource": ""
} |
q35420 | reciprocal_space | train | def reciprocal_space(space, axes=None, halfcomplex=False, shift=True,
**kwargs):
"""Return the range of the Fourier transform on ``space``.
Parameters
----------
space : `DiscreteLp`
Real space whose reciprocal is calculated. It must be
uniformly discretized.
ax... | python | {
"resource": ""
} |
q35421 | _initialize_if_needed | train | def _initialize_if_needed():
"""Initialize ``TENSOR_SPACE_IMPLS`` if not already done."""
global IS_INITIALIZED, TENSOR_SPACE_IMPLS
if not IS_INITIALIZED:
# pkg_resources has long import time
from pkg_resources import iter_entry_points
for entry_point in iter_entry_points(group='odl.... | python | {
"resource": ""
} |
q35422 | tensor_space_impl | train | def tensor_space_impl(impl):
"""Tensor space class corresponding to the given impl name.
Parameters
----------
impl : str
Name of the implementation, see `tensor_space_impl_names` for
the full list.
Returns
-------
tensor_space_impl : type
Class inheriting from `Ten... | python | {
"resource": ""
} |
q35423 | steepest_descent | train | def steepest_descent(f, x, line_search=1.0, maxiter=1000, tol=1e-16,
projection=None, callback=None):
r"""Steepest descent method to minimize an objective function.
General implementation of steepest decent (also known as gradient
decent) for solving
.. math::
\min f(x)
... | python | {
"resource": ""
} |
q35424 | adam | train | def adam(f, x, learning_rate=1e-3, beta1=0.9, beta2=0.999, eps=1e-8,
maxiter=1000, tol=1e-16, callback=None):
r"""ADAM method to minimize an objective function.
General implementation of ADAM for solving
.. math::
\min f(x)
where :math:`f` is a differentiable functional.
The alg... | python | {
"resource": ""
} |
q35425 | _approx_equal | train | def _approx_equal(x, y, eps):
"""Test if elements ``x`` and ``y`` are approximately equal.
``eps`` is a given absolute tolerance.
"""
if x.space != y.space:
return False
if x is y:
return True
try:
return x.dist(y) <= eps
except NotImplementedError:
try:
... | python | {
"resource": ""
} |
q35426 | get_data_dir | train | def get_data_dir():
"""Get the data directory."""
base_odl_dir = os.environ.get('ODL_HOME', expanduser(join('~', '.odl')))
data_home = join(base_odl_dir, 'datasets')
if not exists(data_home):
os.makedirs(data_home)
return data_home | python | {
"resource": ""
} |
q35427 | get_data | train | def get_data(filename, subset, url):
"""Get a dataset with from a url with local caching.
Parameters
----------
filename : str
Name of the file, for caching.
subset : str
To what subset the file belongs (e.g. 'ray_transform'). Each subset
is saved in a separate subfolder.
... | python | {
"resource": ""
} |
q35428 | forward_backward_pd | train | def forward_backward_pd(x, f, g, L, h, tau, sigma, niter,
callback=None, **kwargs):
r"""The forward-backward primal-dual splitting algorithm.
The algorithm minimizes the sum of several convex functionals composed with
linear operators::
min_x f(x) + sum_i g_i(L_i x) + h(x)
... | python | {
"resource": ""
} |
q35429 | samples | train | def samples(*sets):
"""Generate samples from the given sets using their ``examples`` method.
Parameters
----------
set1, ..., setN : `Set` instance
Set(s) from which to generate the samples.
Returns
-------
samples : `generator`
Generator that yields tuples of examples from... | python | {
"resource": ""
} |
q35430 | cuboid | train | def cuboid(space, min_pt=None, max_pt=None):
"""Rectangular cuboid.
Parameters
----------
space : `DiscreteLp`
Space in which the phantom should be created.
min_pt : array-like of shape ``(space.ndim,)``, optional
Lower left corner of the cuboid. If ``None`` is given, a quarter
... | python | {
"resource": ""
} |
q35431 | defrise | train | def defrise(space, nellipses=8, alternating=False, min_pt=None, max_pt=None):
"""Phantom with regularily spaced ellipses.
This phantom is often used to verify cone-beam algorithms.
Parameters
----------
space : `DiscreteLp`
Space in which the phantom should be created, must be 2- or
... | python | {
"resource": ""
} |
q35432 | defrise_ellipses | train | def defrise_ellipses(ndim, nellipses=8, alternating=False):
"""Ellipses for the standard Defrise phantom in 2 or 3 dimensions.
Parameters
----------
ndim : {2, 3}
Dimension of the space for the ellipses/ellipsoids.
nellipses : int, optional
Number of ellipses. If more ellipses are u... | python | {
"resource": ""
} |
q35433 | indicate_proj_axis | train | def indicate_proj_axis(space, scale_structures=0.5):
"""Phantom indicating along which axis it is projected.
The number (n) of rectangles in a parallel-beam projection along a main
axis (0, 1, or 2) indicates the projection to be along the (n-1)the
dimension.
Parameters
----------
space : ... | python | {
"resource": ""
} |
q35434 | _getshapes_2d | train | def _getshapes_2d(center, max_radius, shape):
"""Calculate indices and slices for the bounding box of a disk."""
index_mean = shape * center
index_radius = max_radius / 2.0 * np.array(shape)
# Avoid negative indices
min_idx = np.maximum(np.floor(index_mean - index_radius), 0).astype(int)
max_id... | python | {
"resource": ""
} |
q35435 | _ellipse_phantom_2d | train | def _ellipse_phantom_2d(space, ellipses):
"""Create a phantom of ellipses in 2d space.
Parameters
----------
space : `DiscreteLp`
Uniformly discretized space in which the phantom should be generated.
If ``space.shape`` is 1 in an axis, a corresponding slice of the
phantom is cre... | python | {
"resource": ""
} |
q35436 | ellipsoid_phantom | train | def ellipsoid_phantom(space, ellipsoids, min_pt=None, max_pt=None):
"""Return a phantom given by ellipsoids.
Parameters
----------
space : `DiscreteLp`
Space in which the phantom should be created, must be 2- or
3-dimensional. If ``space.shape`` is 1 in an axis, a corresponding
... | python | {
"resource": ""
} |
q35437 | smooth_cuboid | train | def smooth_cuboid(space, min_pt=None, max_pt=None, axis=0):
"""Cuboid with smooth variations.
Parameters
----------
space : `DiscreteLp`
Discretized space in which the phantom is supposed to be created.
min_pt : array-like of shape ``(space.ndim,)``, optional
Lower left corner of th... | python | {
"resource": ""
} |
q35438 | tgv_phantom | train | def tgv_phantom(space, edge_smoothing=0.2):
"""Piecewise affine phantom.
This phantom is taken from [Bre+2010] and includes both linearly varying
regions and sharp discontinuities. It is designed to work well with
Total Generalized Variation (TGV) type regularization.
Parameters
----------
... | python | {
"resource": ""
} |
q35439 | print_objective | train | def print_objective(x):
"""Calculate the objective value and prints it."""
value = 0
for minp, maxp in rectangles:
x_proj = np.minimum(np.maximum(x, minp), maxp)
value += (x - x_proj).norm()
print('Point = [{:.4f}, {:.4f}], Value = {:.4f}'.format(x[0], x[1], value)) | python | {
"resource": ""
} |
q35440 | sparse_meshgrid | train | def sparse_meshgrid(*x):
"""Make a sparse `meshgrid` by adding empty dimensions.
Parameters
----------
x1,...,xN : `array-like`
Input arrays to turn into sparse meshgrid vectors.
Returns
-------
meshgrid : tuple of `numpy.ndarray`'s
Sparse coordinate vectors representing an... | python | {
"resource": ""
} |
q35441 | uniform_grid_fromintv | train | def uniform_grid_fromintv(intv_prod, shape, nodes_on_bdry=True):
"""Return a grid from sampling an interval product uniformly.
The resulting grid will by default include ``intv_prod.min_pt`` and
``intv_prod.max_pt`` as grid points. If you want a subdivision into
equally sized cells with grid points in ... | python | {
"resource": ""
} |
q35442 | uniform_grid | train | def uniform_grid(min_pt, max_pt, shape, nodes_on_bdry=True):
"""Return a grid from sampling an implicit interval product uniformly.
Parameters
----------
min_pt : float or sequence of float
Vectors of lower ends of the intervals in the product.
max_pt : float or sequence of float
Ve... | python | {
"resource": ""
} |
q35443 | RectGrid.ndim | train | def ndim(self):
"""Number of dimensions of the grid."""
try:
return self.__ndim
except AttributeError:
ndim = len(self.coord_vectors)
self.__ndim = ndim
return ndim | python | {
"resource": ""
} |
q35444 | RectGrid.shape | train | def shape(self):
"""Number of grid points per axis."""
try:
return self.__shape
except AttributeError:
shape = tuple(len(vec) for vec in self.coord_vectors)
self.__shape = shape
return shape | python | {
"resource": ""
} |
q35445 | RectGrid.size | train | def size(self):
"""Total number of grid points."""
# Since np.prod(()) == 1.0 we need to handle that by ourselves
return (0 if self.shape == () else
int(np.prod(self.shape, dtype='int64'))) | python | {
"resource": ""
} |
q35446 | RectGrid.min | train | def min(self, **kwargs):
"""Return `min_pt`.
Parameters
----------
kwargs
For duck-typing with `numpy.amin`
See Also
--------
max
odl.set.domain.IntervalProd.min
Examples
--------
>>> g = RectGrid([1, 2, 5], [-2, 1.5,... | python | {
"resource": ""
} |
q35447 | RectGrid.max | train | def max(self, **kwargs):
"""Return `max_pt`.
Parameters
----------
kwargs
For duck-typing with `numpy.amax`
See Also
--------
min
odl.set.domain.IntervalProd.max
Examples
--------
>>> g = RectGrid([1, 2, 5], [-2, 1.5,... | python | {
"resource": ""
} |
q35448 | RectGrid.stride | train | def stride(self):
"""Step per axis between neighboring points of a uniform grid.
If the grid contains axes that are not uniform, ``stride`` has
a ``NaN`` entry.
For degenerate (length 1) axes, ``stride`` has value ``0.0``.
Returns
-------
stride : numpy.array
... | python | {
"resource": ""
} |
q35449 | RectGrid.approx_equals | train | def approx_equals(self, other, atol):
"""Test if this grid is equal to another grid.
Parameters
----------
other :
Object to be tested
atol : float
Allow deviations up to this number in absolute value
per vector entry.
Returns
... | python | {
"resource": ""
} |
q35450 | RectGrid.approx_contains | train | def approx_contains(self, other, atol):
"""Test if ``other`` belongs to this grid up to a tolerance.
Parameters
----------
other : `array-like` or float
The object to test for membership in this grid
atol : float
Allow deviations up to this number in abso... | python | {
"resource": ""
} |
q35451 | RectGrid.is_subgrid | train | def is_subgrid(self, other, atol=0.0):
"""Return ``True`` if this grid is a subgrid of ``other``.
Parameters
----------
other : `RectGrid`
The other grid which is supposed to contain this grid
atol : float, optional
Allow deviations up to this number in ... | python | {
"resource": ""
} |
q35452 | RectGrid.insert | train | def insert(self, index, *grids):
"""Return a copy with ``grids`` inserted before ``index``.
The given grids are inserted (as a block) into ``self``, yielding
a new grid whose number of dimensions is the sum of the numbers of
dimensions of all involved grids.
Note that no changes... | python | {
"resource": ""
} |
q35453 | RectGrid.points | train | def points(self, order='C'):
"""All grid points in a single array.
Parameters
----------
order : {'C', 'F'}, optional
Axis ordering in the resulting point array.
Returns
-------
points : `numpy.ndarray`
The shape of the array is ``size x ... | python | {
"resource": ""
} |
q35454 | RectGrid.corner_grid | train | def corner_grid(self):
"""Return a grid with only the corner points.
Returns
-------
cgrid : `RectGrid`
Grid with size 2 in non-degenerate dimensions and 1
in degenerate ones
Examples
--------
>>> g = RectGrid([0, 1], [-1, 0, 2])
... | python | {
"resource": ""
} |
q35455 | PartialDerivative._call | train | def _call(self, x, out=None):
"""Calculate partial derivative of ``x``."""
if out is None:
out = self.range.element()
# TODO: this pipes CUDA arrays through NumPy. Write native operator.
with writable_array(out) as out_arr:
finite_diff(x.asarray(), axis=self.axis... | python | {
"resource": ""
} |
q35456 | Gradient._call | train | def _call(self, x, out=None):
"""Calculate the spatial gradient of ``x``."""
if out is None:
out = self.range.element()
x_arr = x.asarray()
ndim = self.domain.ndim
dx = self.domain.cell_sides
for axis in range(ndim):
with writable_array(out[axis]... | python | {
"resource": ""
} |
q35457 | Divergence._call | train | def _call(self, x, out=None):
"""Calculate the divergence of ``x``."""
if out is None:
out = self.range.element()
ndim = self.range.ndim
dx = self.range.cell_sides
tmp = np.empty(out.shape, out.dtype, order=out.space.default_order)
with writable_array(out) a... | python | {
"resource": ""
} |
q35458 | Laplacian._call | train | def _call(self, x, out=None):
"""Calculate the spatial Laplacian of ``x``."""
if out is None:
out = self.range.zero()
else:
out.set_zero()
x_arr = x.asarray()
out_arr = out.asarray()
tmp = np.empty(out.shape, out.dtype, order=out.space.default_ord... | python | {
"resource": ""
} |
q35459 | divide_1Darray_equally | train | def divide_1Darray_equally(ind, nsub):
"""Divide an array into equal chunks to be used for instance in OSEM.
Parameters
----------
ind : ndarray
input array
nsubsets : int
number of subsets to be divided into
Returns
-------
sub2ind : list
list of indices for ea... | python | {
"resource": ""
} |
q35460 | total_variation | train | def total_variation(domain, grad=None):
"""Total variation functional.
Parameters
----------
domain : odlspace
domain of TV functional
grad : gradient operator, optional
Gradient operator of the total variation functional. This may be any
linear operator and thereby generali... | python | {
"resource": ""
} |
q35461 | fgp_dual | train | def fgp_dual(p, data, alpha, niter, grad, proj_C, proj_P, tol=None, **kwargs):
"""Computes a solution to the ROF problem with the fast gradient
projection algorithm.
Parameters
----------
p : np.array
dual initial variable
data : np.array
noisy data / proximal point
alpha : ... | python | {
"resource": ""
} |
q35462 | TotalVariationNonNegative.proximal | train | def proximal(self, sigma):
"""Prox operator of TV. It allows the proximal step length to be a
vector of positive elements.
Examples
--------
Check that the proximal operator is the identity for sigma=0
>>> import odl.contrib.solvers.spdhg as spdhg, odl, numpy as np
... | python | {
"resource": ""
} |
q35463 | _fields_from_table | train | def _fields_from_table(spec_table, id_key):
"""Read a specification and return a list of fields.
The given specification is assumed to be in
`reST grid table format
<http://docutils.sourceforge.net/docs/user/rst/quickref.html#tables>`_.
Parameters
----------
spec_table : str
Specif... | python | {
"resource": ""
} |
q35464 | header_fields_from_table | train | def header_fields_from_table(spec_table, keys, dtype_map):
"""Convert the specification table to a standardized format.
The specification table is assumed to be in
`reST grid table format
<http://docutils.sourceforge.net/docs/user/rst/quickref.html#tables>`_.
It must have the following 5 columns:
... | python | {
"resource": ""
} |
q35465 | FileReaderRawBinaryWithHeader.header_size | train | def header_size(self):
"""Size of `file`'s header in bytes.
The size of the header is determined from `header`. If this is not
possible (i.e., before the header has been read), 0 is returned.
"""
if not self.header:
return 0
# Determine header size by findin... | python | {
"resource": ""
} |
q35466 | FileReaderRawBinaryWithHeader.read_header | train | def read_header(self):
"""Read the header from `file`.
The header is also stored in the `header` attribute.
Returns
-------
header : `OrderedDict`
Header from `file`, stored in an ordered dictionary, where each
entry has the following form::
... | python | {
"resource": ""
} |
q35467 | FileReaderRawBinaryWithHeader.read_data | train | def read_data(self, dstart=None, dend=None):
"""Read data from `file` and return it as Numpy array.
Parameters
----------
dstart : int, optional
Offset in bytes of the data field. By default, it is taken to
be the header size as determined from reading the header... | python | {
"resource": ""
} |
q35468 | FileWriterRawBinaryWithHeader.write_header | train | def write_header(self):
"""Write `header` to `file`.
See Also
--------
write_data
"""
for properties in self.header.values():
value = properties['value']
offset_bytes = int(properties['offset'])
self.file.seek(offset_bytes)
... | python | {
"resource": ""
} |
q35469 | RosenbrockFunctional.gradient | train | def gradient(self):
"""Gradient operator of the Rosenbrock functional."""
functional = self
c = self.scale
class RosenbrockGradient(Operator):
"""The gradient operator of the Rosenbrock functional."""
def __init__(self):
"""Initialize a new inst... | python | {
"resource": ""
} |
q35470 | normalized_scalar_param_list | train | def normalized_scalar_param_list(param, length, param_conv=None,
keep_none=True, return_nonconv=False):
"""Return a list of given length from a scalar parameter.
The typical use case is when a single value or a sequence of
values is accepted as input. This function makes a ... | python | {
"resource": ""
} |
q35471 | normalized_index_expression | train | def normalized_index_expression(indices, shape, int_to_slice=False):
"""Enable indexing with almost Numpy-like capabilities.
Implements the following features:
- Usage of general slices and sequences of slices
- Conversion of `Ellipsis` into an adequate number of ``slice(None)``
objects
- Fe... | python | {
"resource": ""
} |
q35472 | normalized_nodes_on_bdry | train | def normalized_nodes_on_bdry(nodes_on_bdry, length):
"""Return a list of 2-tuples of bool from the input parameter.
This function is intended to normalize a ``nodes_on_bdry`` parameter
that can be given as a single boolean (global) or as a sequence
(per axis). Each entry of the sequence can either be a... | python | {
"resource": ""
} |
q35473 | normalized_axes_tuple | train | def normalized_axes_tuple(axes, ndim):
"""Return a tuple of ``axes`` converted to positive integers.
This function turns negative entries into equivalent positive
ones according to standard Python indexing "from the right".
Parameters
----------
axes : int or sequence of ints
Single in... | python | {
"resource": ""
} |
q35474 | safe_int_conv | train | def safe_int_conv(number):
"""Safely convert a single number to integer."""
try:
return int(np.array(number).astype(int, casting='safe'))
except TypeError:
raise ValueError('cannot safely convert {} to integer'.format(number)) | python | {
"resource": ""
} |
q35475 | astra_cpu_forward_projector | train | def astra_cpu_forward_projector(vol_data, geometry, proj_space, out=None):
"""Run an ASTRA forward projection on the given data using the CPU.
Parameters
----------
vol_data : `DiscreteLpElement`
Volume data to which the forward projector is applied
geometry : `Geometry`
Geometry de... | python | {
"resource": ""
} |
q35476 | astra_cpu_back_projector | train | def astra_cpu_back_projector(proj_data, geometry, reco_space, out=None):
"""Run an ASTRA back-projection on the given data using the CPU.
Parameters
----------
proj_data : `DiscreteLpElement`
Projection data to which the back-projector is applied
geometry : `Geometry`
Geometry defin... | python | {
"resource": ""
} |
q35477 | _default_call_out_of_place | train | def _default_call_out_of_place(op, x, **kwargs):
"""Default out-of-place evaluation.
Parameters
----------
op : `Operator`
Operator to call
x : ``op.domain`` element
Point in which to call the operator.
kwargs:
Optional arguments to the operator.
Returns
-------... | python | {
"resource": ""
} |
q35478 | _function_signature | train | def _function_signature(func):
"""Return the signature of a callable as a string.
Parameters
----------
func : callable
Function whose signature to extract.
Returns
-------
sig : string
Signature of the function.
"""
if sys.version_info.major > 2:
# Python 3... | python | {
"resource": ""
} |
q35479 | Operator.norm | train | def norm(self, estimate=False, **kwargs):
"""Return the operator norm of this operator.
If this operator is non-linear, this should be the Lipschitz constant.
Parameters
----------
estimate : bool
If true, estimate the operator norm. By default, it is estimated
... | python | {
"resource": ""
} |
q35480 | OperatorSum.derivative | train | def derivative(self, x):
"""Return the operator derivative at ``x``.
The derivative of a sum of two operators is equal to the sum of
the derivatives.
Parameters
----------
x : `domain` `element-like`
Evaluation point of the derivative
"""
if ... | python | {
"resource": ""
} |
q35481 | OperatorComp.derivative | train | def derivative(self, x):
"""Return the operator derivative.
The derivative of the operator composition follows the chain
rule:
``OperatorComp(left, right).derivative(y) ==
OperatorComp(left.derivative(right(y)), right.derivative(y))``
Parameters
-------... | python | {
"resource": ""
} |
q35482 | _indent | train | def _indent(x):
"""Indent a string by 4 characters."""
lines = x.splitlines()
for i, line in enumerate(lines):
lines[i] = ' ' + line
return '\n'.join(lines) | python | {
"resource": ""
} |
q35483 | ProductSpace.shape | train | def shape(self):
"""Total spaces per axis, computed recursively.
The recursion ends at the fist level that does not have a shape.
Examples
--------
>>> r2, r3 = odl.rn(2), odl.rn(3)
>>> pspace = odl.ProductSpace(r2, r3)
>>> pspace.shape
(2,)
>>> ... | python | {
"resource": ""
} |
q35484 | ProductSpace.dtype | train | def dtype(self):
"""The data type of this space.
This is only well defined if all subspaces have the same dtype.
Raises
------
AttributeError
If any of the subspaces does not implement `dtype` or if the dtype
of the subspaces does not match.
"""
... | python | {
"resource": ""
} |
q35485 | ProductSpace.element | train | def element(self, inp=None, cast=True):
"""Create an element in the product space.
Parameters
----------
inp : optional
If ``inp`` is ``None``, a new element is created from
scratch by allocation in the spaces. If ``inp`` is
already an element of this... | python | {
"resource": ""
} |
q35486 | ProductSpace.examples | train | def examples(self):
"""Return examples from all sub-spaces."""
for examples in product(*[spc.examples for spc in self.spaces]):
name = ', '.join(name for name, _ in examples)
element = self.element([elem for _, elem in examples])
yield (name, element) | python | {
"resource": ""
} |
q35487 | ProductSpaceElement.asarray | train | def asarray(self, out=None):
"""Extract the data of this vector as a numpy array.
Only available if `is_power_space` is True.
The ordering is such that it commutes with indexing::
self[ind].asarray() == self.asarray()[ind]
Parameters
----------
out : `nump... | python | {
"resource": ""
} |
q35488 | ProductSpaceElement.real | train | def real(self):
"""Real part of the element.
The real part can also be set using ``x.real = other``, where ``other``
is array-like or scalar.
Examples
--------
>>> space = odl.ProductSpace(odl.cn(3), odl.cn(2))
>>> x = space.element([[1 + 1j, 2, 3 - 3j],
... | python | {
"resource": ""
} |
q35489 | ProductSpaceElement.real | train | def real(self, newreal):
"""Setter for the real part.
This method is invoked by ``x.real = other``.
Parameters
----------
newreal : array-like or scalar
Values to be assigned to the real part of this element.
"""
try:
iter(newreal)
... | python | {
"resource": ""
} |
q35490 | ProductSpaceElement.imag | train | def imag(self):
"""Imaginary part of the element.
The imaginary part can also be set using ``x.imag = other``, where
``other`` is array-like or scalar.
Examples
--------
>>> space = odl.ProductSpace(odl.cn(3), odl.cn(2))
>>> x = space.element([[1 + 1j, 2, 3 - 3... | python | {
"resource": ""
} |
q35491 | ProductSpaceElement.conj | train | def conj(self):
"""Complex conjugate of the element."""
complex_conj = [part.conj() for part in self.parts]
return self.space.element(complex_conj) | python | {
"resource": ""
} |
q35492 | ProductSpaceElement.show | train | def show(self, title=None, indices=None, **kwargs):
"""Display the parts of this product space element graphically.
Parameters
----------
title : string, optional
Title of the figures
indices : int, slice, tuple or list, optional
Display parts of ``self`... | python | {
"resource": ""
} |
q35493 | ProductSpaceArrayWeighting.inner | train | def inner(self, x1, x2):
"""Calculate the array-weighted inner product of two elements.
Parameters
----------
x1, x2 : `ProductSpaceElement`
Elements whose inner product is calculated.
Returns
-------
inner : float or complex
The inner pr... | python | {
"resource": ""
} |
q35494 | ProductSpaceArrayWeighting.norm | train | def norm(self, x):
"""Calculate the array-weighted norm of an element.
Parameters
----------
x : `ProductSpaceElement`
Element whose norm is calculated.
Returns
-------
norm : float
The norm of the provided element.
"""
if... | python | {
"resource": ""
} |
q35495 | ProductSpaceConstWeighting.inner | train | def inner(self, x1, x2):
"""Calculate the constant-weighted inner product of two elements.
Parameters
----------
x1, x2 : `ProductSpaceElement`
Elements whose inner product is calculated.
Returns
-------
inner : float or complex
The inner... | python | {
"resource": ""
} |
q35496 | ProductSpaceConstWeighting.dist | train | def dist(self, x1, x2):
"""Calculate the constant-weighted distance between two elements.
Parameters
----------
x1, x2 : `ProductSpaceElement`
Elements whose mutual distance is calculated.
Returns
-------
dist : float
The distance between... | python | {
"resource": ""
} |
q35497 | euler_matrix | train | def euler_matrix(phi, theta=None, psi=None):
"""Rotation matrix in 2 and 3 dimensions.
Its rows represent the canonical unit vectors as seen from the
rotated system while the columns are the rotated unit vectors as
seen from the canonical system.
Parameters
----------
phi : float or `array... | python | {
"resource": ""
} |
q35498 | axis_rotation | train | def axis_rotation(axis, angle, vectors, axis_shift=(0, 0, 0)):
"""Rotate a vector or an array of vectors around an axis in 3d.
The rotation is computed by `Rodrigues' rotation formula`_.
Parameters
----------
axis : `array-like`, shape ``(3,)``
Rotation axis, assumed to be a unit vector.
... | python | {
"resource": ""
} |
q35499 | axis_rotation_matrix | train | def axis_rotation_matrix(axis, angle):
"""Matrix of the rotation around an axis in 3d.
The matrix is computed according to `Rodriguez' rotation formula`_.
Parameters
----------
axis : `array-like`, shape ``(3,)``
Rotation axis, assumed to be a unit vector.
angle : float or `array-like`... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.