Skip to content

Commit

Permalink
MAINT: fix names, docs, doctests, comments etc.
Browse files Browse the repository at this point in the history
  • Loading branch information
Holger Kohr committed Sep 1, 2017
1 parent 270313b commit 68ed1e1
Show file tree
Hide file tree
Showing 14 changed files with 217 additions and 141 deletions.
3 changes: 1 addition & 2 deletions odl/deform/linearized.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ def _linear_deform(template, displacement, out=None):
for i, vi in enumerate(displacement):
image_pts[:, i] += vi.asarray().ravel(order=vi.order)
values = template.interpolation(image_pts.T, out=out, bounds_check=False)
return values.reshape(displacement.space[0].shape,
order=displacement.space[0].order)
return values.reshape(template.space.shape, order=template.space.order)


class LinDeformFixedTempl(Operator):
Expand Down
4 changes: 2 additions & 2 deletions odl/discr/diff_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,8 @@ def __init__(self, domain=None, range=None, method='forward',
>>> adj_g = grad.adjoint(g)
>>> adj_g
uniform_discr([0.0, 0.0], [2.0, 5.0], (2, 5)).element(
[[ -0., -2., -5., -8., -11.],
[ -0., -5., -14., -23., -32.]]
[[ 0., -2., -5., -8., -11.],
[ 0., -5., -14., -23., -32.]]
)
>>> g.inner(grad_f) / f.inner(adj_g)
1.0
Expand Down
28 changes: 14 additions & 14 deletions odl/discr/discr_mappings.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,22 +586,22 @@ def __repr__(self):

posargs = [self.range, self.grid, self.domain, schemes]

nontriv_var = None
for var in self.nn_variants:
if var is not None:
nontriv_var = var
break

if nontriv_var is None:
variants = 'left'
elif all(var == nontriv_var
for var in self.nn_variants
if var is not None):
variants = nontriv_var
# nn_variants are displayed as:
# - 'left' if
nn_relevant = filter(lambda x: x is not None, self.nn_variants)
if not nn_relevant:
# No NN axes, ignore nn_variants
optargs = []
else:
variants = self.nn_variants
# Use single string if all are equal, one per axis otherwise
first_relevant = next(nn_relevant)

optargs = [('nn_variants', variants, 'left')]
if all(var == first_relevant for var in nn_relevant):
variants = first_relevant
else:
variants = self.nn_variants

optargs = [('nn_variants', variants, 'left')]

inner_str = signature_string(posargs, optargs,
sep=[',\n', ', ', ',\n'],
Expand Down
4 changes: 2 additions & 2 deletions odl/discr/discretization.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,15 +129,15 @@ def dspace_type(self):

@property
def sampling(self):
"""Operator mapping a `uspace` element to a tensor."""
"""Operator mapping a `uspace` element to a `Tensor`."""
if self.__sampling is not None:
return self.__sampling
else:
raise NotImplementedError('no sampling operator provided')

@property
def interpolation(self):
"""Operator mapping a tensor to a `uspace` element."""
"""Operator mapping a `Tensor` to a `uspace` element."""
if self.__interpolation is not None:
return self.__interpolation
else:
Expand Down
8 changes: 4 additions & 4 deletions odl/discr/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -1020,16 +1020,16 @@ def __array__(self, dtype=None):
def __repr__(self):
"""Return ``repr(self)``."""
if self.is_uniform:
constructor = 'uniform_grid'
ctor = 'uniform_grid'
posargs = [list(self.min_pt), list(self.max_pt), self.shape]
inner_str = signature_string(posargs, [])
return '{}({})'.format(constructor, inner_str)
return '{}({})'.format(ctor, inner_str)
else:
constructor = self.__class__.__name__
ctor = self.__class__.__name__
posargs = [array_str(v) for v in self.coord_vectors]
inner_str = signature_string(posargs, [], sep=[',\n', ', ', ', '],
mod=['!s', ''])
return '{}(\n{}\n)'.format(constructor, indent(inner_str))
return '{}(\n{}\n)'.format(ctor, indent(inner_str))

__str__ = __repr__

Expand Down
33 changes: 13 additions & 20 deletions odl/discr/lp_discr.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ def __repr__(self):
use_uniform = False

if use_uniform:
constructor = 'uniform_discr'
ctor = 'uniform_discr'
if self.ndim == 1:
posargs = [self.min_pt[0], self.max_pt[0], self.shape[0]]
else:
Expand Down Expand Up @@ -543,17 +543,17 @@ def __repr__(self):
inner_str = signature_string(posargs, optargs,
mod=[['!r'] * len(posargs),
[''] * len(optargs)])
return '{}({})'.format(constructor, inner_str)
return '{}({})'.format(ctor, inner_str)

else:
constructor = self.__class__.__name__
ctor = self.__class__.__name__
posargs = [self.uspace, self.partition, self.dspace]
optargs = [('interp', self.interp, 'nearest')]
inner_str = signature_string(posargs, optargs,
sep=[',\n', ', ', ',\n'],
mod=['!r', '!s'])

return '{}(\n{}\n)'.format(constructor, indent(inner_str))
return '{}(\n{}\n)'.format(ctor, indent(inner_str))

def __str__(self):
"""Return ``str(self)``."""
Expand Down Expand Up @@ -844,12 +844,11 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
References
----------
.. _corresponding NEP:
https://github.com/numpy/numpy/blob/master/doc/neps/\
ufunc-overrides.rst
https://docs.scipy.org/doc/numpy/neps/ufunc-overrides.html
.. _interface documentation:
https://github.com/charris/numpy/blob/master/doc/source/reference/\
arrays.classes.rst#special-attributes-and-methods
https://docs.scipy.org/doc/numpy/reference/arrays.classes.html\
#numpy.class.__array_ufunc__
.. _general documentation on Numpy ufuncs:
https://docs.scipy.org/doc/numpy/reference/ufuncs.html
Expand Down Expand Up @@ -996,17 +995,13 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
raise ValueError('`reduceat` not supported')

elif (method == 'outer' and
not all(isinstance(inp, type(self)) for inp in inputs[:2])):
not all(isinstance(inp, type(self)) for inp in inputs)):
raise TypeError(
"inputs must be of type {} for `method='outer'`, "
'got types {}'
''.format(type(self),
tuple(type(inp) for inp in inputs[:2])))
''.format(type(self), tuple(type(inp) for inp in inputs)))

else: # method != '__call__', and otherwise valid
# TODO: fix weighting for 'outer' and 'reduce' by looking at
# the constant(s) (if equal to cell volume, use also for new
# space)

if method != 'at':
# No kwargs allowed for 'at'
Expand Down Expand Up @@ -1038,16 +1033,15 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
elif method == 'outer':
# Concatenate domains, partitions, interp, axis_labels,
# and determine `dspace` from the result tensor
inp1, inp2 = inputs[:2]
inp1, inp2 = inputs
domain = inp1.space.domain.append(inp2.space.domain)
fspace = FunctionSpace(domain, out_dtype=res_tens.dtype)
part = inp1.space.partition.append(inp2.space.partition)
interp = (inp1.space.interp_byaxis +
inp2.space.interp_byaxis)
labels = inp1.space.axis_labels + inp2.space.axis_labels
if len(set(labels)) != len(labels):
# Duplicates, take default
labels = None
labels1 = [lbl + ' (1)' for lbl in inp1.space.axis_labels]
labels2 = [lbl + ' (2)' for lbl in inp2.space.axis_labels]
labels = labels1 + labels2

if all(isinstance(inp.space.weighting, ConstWeighting)
for inp in inputs):
Expand Down Expand Up @@ -1816,6 +1810,5 @@ def scaling_func(x):


if __name__ == '__main__':
# pylint: disable=wrong-import-position
from odl.util.testutils import run_doctests
run_doctests()
8 changes: 4 additions & 4 deletions odl/discr/partition.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,7 +844,7 @@ def __repr__(self):
csizes_r)

if self.is_uniform and default_bdry_fracs:
constructor = 'uniform_partition'
ctor = 'uniform_partition'
if self.ndim == 1:
posargs = [self.min_pt[0], self.max_pt[0], self.shape[0]]
else:
Expand All @@ -853,9 +853,9 @@ def __repr__(self):
optargs = [('nodes_on_bdry', self.nodes_on_bdry, False)]

sig_str = signature_string(posargs, optargs)
return '{}({})'.format(constructor, sig_str)
return '{}({})'.format(ctor, sig_str)
else:
constructor = 'nonuniform_partition'
ctor = 'nonuniform_partition'
posargs = [list(v) for v in self.coord_vectors]

optargs = []
Expand Down Expand Up @@ -884,7 +884,7 @@ def __repr__(self):

sig_str = signature_string(posargs, optargs,
sep=[',\n', ', ', ',\n'])
return '{}(\n{}\n)'.format(constructor, indent(sig_str))
return '{}(\n{}\n)'.format(ctor, indent(sig_str))

def __str__(self):
"""Return ``str(self)``."""
Expand Down
4 changes: 2 additions & 2 deletions odl/operator/default_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -1150,10 +1150,10 @@ class ComplexEmbedding(Operator):
Implements::
ComplexEmbedding(x) == x + 1j * zero()
ComplexEmbedding(space)(x) == space.complex_space.element(x)
"""

def __init__(self, space, scalar=1):
def __init__(self, space, scalar=1.0):
"""Initialize a new instance.
Parameters
Expand Down
48 changes: 31 additions & 17 deletions odl/operator/tensor_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -756,12 +756,15 @@ def __init__(self, matrix, domain=None, range=None, axis=0):
The operator also works on `uniform_discr` type spaces. Note,
however, that the ``weighting`` of the domain is propagated to
the range by default:
the range by default, in order to keep the correspondence between
adjoint and transposed matrix:
>>> space = odl.uniform_discr(0, 1, 4)
>>> op = MatrixOperator(m, domain=space)
>>> op(space.one())
rn(3, weighting=0.25).element([ 4., 4., 4.])
>>> np.array_equal(op.adjoint.matrix, m.T)
True
Notes
-----
Expand Down Expand Up @@ -944,7 +947,18 @@ def __str__(self):


def _normalize_sampling_points(sampling_points, ndim):
"""Normalize points to an ndim-long list of linear index arrays."""
"""Normalize points to an ndim-long list of linear index arrays.
This helper converts sampling indices for `SamplingOperator` from
integers or array-like objects to a list of length ``ndim``, where
each entry is a `numpy.ndarray` with ``dtype=int``.
The function also checks if all arrays have equal lengths, and that
they fulfill ``array.ndim=1`` (or ``size=0`` for if ``ndim == 0``).
The result of this normalization is intended to be used for indexing
an ``ndim``-dimensional array at ``sampling_points`` via NumPy fancy
indexing, i.e., ``result = ndim_array[sampling_points]``.
"""
sampling_points_in = sampling_points
if ndim == 0:
sampling_points = [np.array(sampling_points, dtype=int, copy=False)]
Expand Down Expand Up @@ -987,14 +1001,13 @@ class SamplingOperator(Operator):
The operator is defined by ::
SamplingOperator(f) == c * f[indices]
SamplingOperator(f) == c * f[sampling_points]
with the weight c being determined by the variant. By choosing
c = 1, this operator approximates point evaluations or inner products
with dirac deltas, see option ``'point_eval'``. By choosing
c = cell_volume it approximates the integration of f over the cell by
multiplying its function valume with the cell volume, see option
``'integrate'``.
with the weight ``c`` being determined by the variant. By choosing
``c = 1``, this operator approximates point evaluations or inner
products with Dirac deltas, see option ``variant='point_eval'``.
By choosing ``c = cell_volume``, it approximates the integration of
``f`` over the indexed cells, see option ``variant='integrate'``.
"""

def __init__(self, domain, sampling_points, variant='point_eval'):
Expand Down Expand Up @@ -1054,11 +1067,11 @@ def __init__(self, domain, sampling_points, variant='point_eval'):
... [4, 5, 6]])
>>> op(x)
rn(1).element([ 3.])
>>> sampling_points = [[0, 1], # indices (0, 2) and (1, 1)
... [2, 1]]
>>> sampling_points = [[0, 1, 1], # indices (0, 2), (1, 1), (1, 0)
... [2, 1, 0]]
>>> op = odl.SamplingOperator(space, sampling_points)
>>> op(x)
rn(2).element([ 3., 5.])
rn(3).element([ 3., 5., 4.])
"""
if not isinstance(domain, TensorSpace):
raise TypeError('`domain` must be a `TensorSpace` instance, got '
Expand Down Expand Up @@ -1118,24 +1131,25 @@ def adjoint(self):
Examples
--------
>>> space = odl.uniform_discr([-1, -1], [1, 1], shape=(2, 3))
>>> # Point (0, 0) occurs twice
>>> sampling_points = [[0, 1, 1, 0],
... [0, 1, 2, 0]]
>>> op = odl.SamplingOperator(space, sampling_points)
>>> x = space.element([[1, 2, 3],
... [4, 5, 6]])
>>> op.adjoint(op(x)).inner(x) - op(x).inner(op(x)) < 1e-10
True
The ``'integrate'`` variant adjoint puts ones at the indices in
``sampling_points``, multiplied by their multiplicity:
>>> op = odl.SamplingOperator(space, sampling_points,
... variant='integrate')
>>> # Put ones at the indices in sampling_points, using double
>>> # weight at (0, 0) since it occurs twice
>>> op.adjoint(op.range.one())
>>> op.adjoint(op.range.one()) # (0, 0) occurs twice
uniform_discr([-1.0, -1.0], [1.0, 1.0], (2, 3)).element(
[[ 2., 0., 0.],
[ 0., 1., 1.]]
)
>>> op.adjoint(op(x)).inner(x) - op(x).inner(op(x)) < 1e-10
>>> abs(op.adjoint(op(x)).inner(x) - op(x).inner(op(x))) < 1e-10
True
"""
if self.variant == 'point_eval':
Expand Down
Loading

0 comments on commit 68ed1e1

Please sign in to comment.