Skip to content

Commit

Permalink
Merge pull request #1161 from kohr-h/issue-1061__super
Browse files Browse the repository at this point in the history
MAINT: unify usage of calls to parent classes, closes #1061
  • Loading branch information
Holger Kohr authored Sep 26, 2017
2 parents 9769446 + 5daf0aa commit b14b962
Show file tree
Hide file tree
Showing 53 changed files with 483 additions and 420 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ def __init__(self, kernel):
# Initialize the Operator class by calling its __init__ method.
# This sets properties such as domain and range and allows the other
# operator convenience functions to work.
odl.Operator.__init__(self, domain=kernel.space, range=kernel.space,
linear=True)
super(Convolution, self).__init__(
domain=kernel.space, range=kernel.space, linear=True)

def _call(self, x):
"""Implement calling the operator by calling scipy."""
Expand Down
4 changes: 2 additions & 2 deletions doc/source/getting_started/first_steps.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ and create a wrapping `Operator` for it in ODL.
# Initialize the Operator class by calling its __init__ method.
# This sets properties such as domain and range and allows the other
# operator convenience functions to work.
odl.Operator.__init__(self, domain=kernel.space, range=kernel.space,
linear=True)
super(Convolution, self).__init__(
domain=kernel.space, range=kernel.space, linear=True)
def _call(self, x):
"""Implement calling the operator by calling scipy."""
Expand Down
12 changes: 6 additions & 6 deletions doc/source/guide/code/functional_indepth_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ def __init__(self, space, y):
# This comand calls the init of Functional and sets a number of
# parameters associated with a functional. All but domain have default
# values if not set.
odl.solvers.Functional.__init__(self, space=space, linear=False,
grad_lipschitz=2)
super(MyFunctional, self).__init__(
space=space, linear=False, grad_lipschitz=2)

# We need to check that linear_term is in the domain. Then we store the
# value of linear_term for future use.
Expand Down Expand Up @@ -43,8 +43,8 @@ class MyGradientOperator(odl.Operator):

def __init__(self):
"""Initialize a new instance."""
super().__init__(domain=functional.domain,
range=functional.domain)
super(MyGradientOperator, self).__init__(
domain=functional.domain, range=functional.domain)

def _call(self, x):
"""Evaluate the gradient."""
Expand Down Expand Up @@ -79,8 +79,8 @@ class MyFunctionalConjugate(odl.solvers.Functional):

def __init__(self, space, y):
"""initialize a new instance."""
odl.solvers.Functional.__init__(self, space=space, linear=False,
grad_lipschitz=2)
super(MyFunctionalConjugate, self).__init__(
space=space, linear=False, grad_lipschitz=2)

if y not in space:
raise TypeError('y is not in the domain!')
Expand Down
21 changes: 6 additions & 15 deletions doc/source/guide/faq.rst
Original file line number Diff line number Diff line change
Expand Up @@ -98,27 +98,18 @@ General errors
Errors related to Python 2/3
----------------------------

#. **Q:** I follow your recommendation to call ``super().__init__(domain, range)``
in the ``__init__()`` method of ``MyOperator``, but I get the following
error::
#. **Q:** I follow your recommendation to call ``super().__init__(domain, range)`` in the ``__init__()`` method of ``MyOperator``, but I get the following error::

File <...>, line ..., in __init__
super().__init__(dom, ran)
File <...>, line ..., in __init__
super().__init__(dom, ran)

TypeError: super() takes at least 1 argument (0 given)
TypeError: super() takes at least 1 argument (0 given)

What is this error related to and how can I fix it?

**P:** The ``super()`` function `in Python 2
<https://docs.python.org/2/library/functions.html#super>`_ has to
be called with a type as first argument, whereas
`in Python 3
<https://docs.python.org/3/library/functions.html#super>`_, the
type argument is optional and usually not needed.
**P:** The ``super()`` function `in Python 2 <https://docs.python.org/2/library/functions.html#super>`_ has to be called with a type as first argument, whereas `in Python 3 <https://docs.python.org/3/library/functions.html#super>`_, the type argument is optional and usually not needed.

**S:** We recommend to include ``from builtins import super`` in your
module to backport the new Py3 ``super()`` function. This way, your code
will run in both Python 2 and 3.
**S:** We recommend to use the explicit ``super(MyOperator, self)`` since it works in both Python 2 and 3.


Usage
Expand Down
2 changes: 1 addition & 1 deletion doc/source/guide/functional_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ To define your own functional, start by writing::

def __init__(self, space):
# Sets `Operator.domain` to `space` and `Operator.range` to `space.field`
odl.solvers.Functional.__init__(self, space)
super(MyFunctional, self).__init__(space)

...

Expand Down
4 changes: 2 additions & 2 deletions doc/source/guide/numpy_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ To solve the above issue, it is often useful to write an `Operator` wrapping Num
...
... # Initialize operator base class.
... # This operator maps from the space of vector to the same space and is linear
... odl.Operator.__init__(self, domain=vector.space, range=vector.space,
... linear=True)
... super(MyConvolution, self).__init__(
... domain=vector.space, range=vector.space, linear=True)
...
... def _call(self, x):
... # The output of an Operator is automatically cast to an ODL vector
Expand Down
2 changes: 1 addition & 1 deletion doc/source/guide/operator_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ for a matrix :math:`A\in \mathbb{R}^{n\times m}` as follows::
self.matrix = matrix
dom = odl.rn(matrix.shape[1])
ran = odl.rn(matrix.shape[0])
odl.Operator.__init__(self, dom, ran)
super(MatVecOperator, self).__init__(dom, ran)

In addition, an `Operator` needs at least one way of
evaluation, *in-place* or *out-of-place*.
Expand Down
2 changes: 1 addition & 1 deletion examples/operator/simple_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

class AddOp(odl.Operator):
def __init__(self, space, add_this):
odl.Operator.__init__(self, domain=space, range=space)
super(AddOp, self).__init__(domain=space, range=space)
self.add_this = add_this

def _call(self, x):
Expand Down
4 changes: 2 additions & 2 deletions examples/solvers/deconvolution_1d.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ def __init__(self, kernel, adjkernel=None):
self.adjkernel = (adjkernel if adjkernel is not None
else kernel.space.element(kernel[::-1].copy()))
self.norm = float(np.sum(np.abs(self.kernel.ntuple)))
odl.Operator.__init__(self, domain=kernel.space, range=kernel.space,
linear=True)
super(Convolution, self).__init__(
domain=kernel.space, range=kernel.space, linear=True)

def _call(self, rhs, out):
ndimage.convolve(rhs.ntuple.data, self.kernel.ntuple.data,
Expand Down
4 changes: 2 additions & 2 deletions examples/solvers/functional_basic_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ def __init__(self, space):
# This comand calls the init of Functional and sets a number of
# parameters associated with a functional. All but domain have default
# values if not set.
odl.solvers.Functional.__init__(self, space=space, linear=False,
grad_lipschitz=2)
super(MyFunctional, self).__init__(
space=space, linear=False, grad_lipschitz=2)

def _call(self, x):
# This is what is returned when calling my_func(x)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@


# define callback to store function values
class CallbackStore(odl.solvers.util.callback.SolverCallback):
class CallbackStore(odl.solvers.util.callback.Callback):
def __init__(self):
self.iteration_count = 0
self.iteration_counts = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
x = op.domain.zero()

# Run algorithm (and display intermediates)
odl.solvers.chambolle_pock_solver(
odl.solvers.pdhg(
x, f, g, op, tau=tau, sigma=sigma, niter=niter, callback=callback)

# Display images
Expand Down
4 changes: 2 additions & 2 deletions examples/space/simple_r.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Reals(odl.LinearSpace):
"""The real numbers."""

def __init__(self):
odl.LinearSpace.__init__(self, field=odl.RealNumbers())
super(Reals, self).__init__(field=odl.RealNumbers())

def _inner(self, x1, x2):
return x1.__val__ * x2.__val__
Expand All @@ -32,7 +32,7 @@ class RealNumber(odl.LinearSpaceElement):
__val__ = None

def __init__(self, space, v):
odl.LinearSpaceElement.__init__(self, space=space)
super(RealNumber, self).__init__(space=space)
self.__val__ = v

def __float__(self):
Expand Down
6 changes: 3 additions & 3 deletions examples/space/simple_rn.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class SimpleRn(FnBase):
"""The real space R^n, non-optimized implmentation."""

def __init__(self, size):
FnBase.__init__(self, size, np.float)
super(SimpleRn, self).__init__(size, np.float)

def zero(self):
return self.element(np.zeros(self.size))
Expand Down Expand Up @@ -51,7 +51,7 @@ def element(self, *args, **kwargs):

class RnVector(FnBaseVector):
def __init__(self, space, data):
FnBaseVector.__init__(self, space)
super(RnVector, self).__init__(space)
self.data = data

def __getitem__(self, index):
Expand All @@ -65,7 +65,7 @@ def asarray(self, *args):


r5 = SimpleRn(5)
#odl.diagnostics.SpaceTest(r5).run_tests()
# odl.diagnostics.SpaceTest(r5).run_tests()

# Do some tests to compare
n = 10**7
Expand Down
Empty file added nohup.out
Empty file.
10 changes: 6 additions & 4 deletions odl/contrib/mrc/mrc.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from builtins import int, super
from builtins import int

from collections import OrderedDict
from itertools import permutations
Expand Down Expand Up @@ -470,7 +470,9 @@ def __init__(self, file, header_fields=None):
keys=MRC_SPEC_KEYS,
dtype_map=MRC_DTYPE_TO_NPY_DTYPE)

super().__init__(file, header_fields)
# `MRCHeaderProperties` has no `__init__`, so this calls
# `FileReaderRawBinaryWithHeader.__init__`
super(FileReaderMRC, self).__init__(file, header_fields)

def read_extended_header(self, groupby='field', force_type=''):
"""Read the extended header according to `extended_header_type`.
Expand Down Expand Up @@ -610,8 +612,8 @@ def read_data(self, dstart=None, dend=None, swap_axes=True):
data : `numpy.ndarray`
The data read from `file`.
"""
data = super().read_data(dstart, dend).reshape(self.data_shape,
order='F')
data = super(FileReaderMRC, self).read_data(dstart, dend)
data = data.reshape(self.data_shape, order='F')
if swap_axes:
data = np.transpose(data, axes=self.data_axis_order)
assert data.shape == self.data_shape
Expand Down
7 changes: 4 additions & 3 deletions odl/contrib/solvers/functional/nonlocalmeans_functionals.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from builtins import super

import numpy as np

Expand Down Expand Up @@ -77,15 +76,17 @@ def __init__(self, space, h,
self.impl = impl
self.patch_size = patch_size
self.patch_distance = patch_distance
super().__init__(space=space, linear=False, grad_lipschitz=np.nan)
super(NLMRegularizer, self).__init__(
space=space, linear=False, grad_lipschitz=np.nan)

@property
def proximal(self):
func = self

class NLMProximal(Operator):
def __init__(self, stepsize):
Operator.__init__(self, func.domain, func.domain, False)
super(NLMProximal, self).__init__(
func.domain, func.domain, linear=False)
self.stepsize = stepsize

def _call(self, x):
Expand Down
2 changes: 1 addition & 1 deletion odl/contrib/tensorflow/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(self, input_tensor, output_tensor, linear=False, sess=None):
else:
self.sess = sess

odl.Operator.__init__(self, domain, range, linear=linear)
super(TensorflowOperator, self).__init__(domain, range, linear=linear)

def _call(self, x):
result = self.sess.run(self.output_tensor,
Expand Down
6 changes: 3 additions & 3 deletions odl/contrib/tensorflow/space.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class TensorflowSpace(LinearSpace):
"""A space of tensorflow Tensors."""

def __init__(self, shape, name='ODLTensorflowSpace'):
LinearSpace.__init__(self, RealNumbers())
super(TensorflowSpace, self).__init__(RealNumbers())
self.shape = tuple(tf.Dimension(si) if not isinstance(si, tf.Dimension)
else si
for si in shape)
Expand Down Expand Up @@ -94,7 +94,7 @@ class TensorflowSpaceElement(LinearSpaceElement):
"""Elements in TensorflowSpace."""

def __init__(self, space, data):
LinearSpaceElement.__init__(self, space)
super(TensorflowSpaceElement, self).__init__(space)
self.data = data

@property
Expand All @@ -116,7 +116,7 @@ class TensorflowSpaceOperator(Operator):
"""Wrap ODL operator so that it acts on TensorflowSpace elements."""

def __init__(self, domain, range, func, adjoint=None, linear=False):
Operator.__init__(self, domain, range, linear)
super(TensorflowSpaceOperator, self).__init__(domain, range, linear)
self.func = func
self.adjoint_func = adjoint

Expand Down
9 changes: 4 additions & 5 deletions odl/deform/linearized.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from builtins import super

import numpy as np

Expand Down Expand Up @@ -188,9 +187,8 @@ def __init__(self, template, domain=None):
'partiton ({!r} != {!r})'
''.format(template.space.partition, domain[0].partition))

super().__init__(domain=domain,
range=self.template.space,
linear=False)
super(LinDeformFixedTempl, self).__init__(
domain=domain, range=self.template.space, linear=False)

@property
def template(self):
Expand Down Expand Up @@ -339,8 +337,9 @@ def __init__(self, displacement, templ_space=None):
'partiton ({!r} != {!r})'
''.format(templ_space.partition, space[0].partition))

super(LinDeformFixedDisp, self).__init__(
domain=templ_space, range=templ_space, linear=True)
self.__displacement = displacement
super().__init__(domain=templ_space, range=templ_space, linear=True)

@property
def displacement(self):
Expand Down
15 changes: 8 additions & 7 deletions odl/discr/diff_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from builtins import super

import numpy as np

Expand Down Expand Up @@ -109,8 +108,8 @@ def __init__(self, space, axis, method='forward', pad_mode='constant',

# Method is affine if nonzero padding is given.
linear = not (pad_mode == 'constant' and pad_const != 0)
super().__init__(domain=space, range=space, base_space=space,
linear=linear)
super(PartialDerivative, self).__init__(
domain=space, range=space, base_space=space, linear=linear)
self.axis = int(axis)
self.dx = space.cell_sides[axis]

Expand Down Expand Up @@ -286,7 +285,8 @@ def __init__(self, domain=None, range=None, method='forward',
range = ProductSpace(domain, domain.ndim)

linear = not (pad_mode == 'constant' and pad_const != 0)
super().__init__(domain, range, base_space=domain, linear=linear)
super(Gradient, self).__init__(
domain, range, base_space=domain, linear=linear)

self.method, method_in = str(method).lower(), method
if method not in _SUPPORTED_DIFF_METHODS:
Expand Down Expand Up @@ -467,7 +467,8 @@ def __init__(self, domain=None, range=None, method='forward',
range = domain[0]

linear = not (pad_mode == 'constant' and pad_const != 0)
super().__init__(domain, range, base_space=range, linear=linear)
super(Divergence, self).__init__(
domain, range, base_space=range, linear=linear)

self.method, method_in = str(method).lower(), method
if method not in _SUPPORTED_DIFF_METHODS:
Expand Down Expand Up @@ -601,8 +602,8 @@ def __init__(self, space, pad_mode='constant', pad_const=0):
if not isinstance(space, DiscreteLp):
raise TypeError('`space` {!r} is not a DiscreteLp instance'
''.format(space))
super().__init__(domain=space, range=space, base_space=space,
linear=True)
super(Laplacian, self).__init__(
domain=space, range=space, base_space=space, linear=True)

self.pad_mode, pad_mode_in = str(pad_mode).lower(), pad_mode
if pad_mode not in _SUPPORTED_PAD_MODES:
Expand Down
Loading

0 comments on commit b14b962

Please sign in to comment.