Esempio n. 1
0
# Copyright 2014-2018 The ODL contributors
#
# This file is part of ODL.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
"""Unit tests for the ODL-shearlab integration."""

import pytest
import numpy as np
import odl
import odl.contrib.shearlab
from odl.util.testutils import all_almost_equal, simple_fixture

dtype = simple_fixture('dtype', ['float32', 'float64'])
shape = simple_fixture('shape', [(64, 64), (128, 128)])


def test_operator(dtype, shape):
    """Test ShearlabOperator operator."""
    rel = 100 * np.finfo('float32').resolution

    space = odl.uniform_discr([-1, -1], [1, 1], shape, dtype=dtype)

    op = odl.contrib.pyshearlab.ShearlabOperator(space, num_scales=2)

    phantom = odl.phantom.shepp_logan(space, True)

    # Test evaluation
    y = op(phantom)
Esempio n. 2
0
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.

from __future__ import division
import numpy as np
import pytest
import operator

import odl
from odl.util.testutils import (all_equal, all_almost_equal, almost_equal,
                                noise_elements, simple_fixture)


exponent = simple_fixture('exponent', [2.0, 1.0, float('inf'), 0.5, 1.5])


def test_emptyproduct():
    with pytest.raises(ValueError):
        odl.ProductSpace()

    reals = odl.RealNumbers()
    spc = odl.ProductSpace(field=reals)
    assert spc.field == reals
    assert spc.size == 0

    with pytest.raises(IndexError):
        spc[0]

Esempio n. 3
0
import odl
from odl.trafos.util.ft_utils import (reciprocal_grid, dft_preprocess_data,
                                      dft_postprocess_data, _interp_kernel_ft)
from odl.trafos.fourier import (DiscreteFourierTransform,
                                DiscreteFourierTransformInverse,
                                FourierTransform)
from odl.util import (all_almost_equal, never_skip, skip_if_no_pyfftw,
                      noise_element, is_real_dtype, conj_exponent,
                      complex_dtype)
from odl.util.testutils import simple_fixture

# --- pytest fixtures --- #

impl = simple_fixture(
    'impl',
    [never_skip('numpy'), skip_if_no_pyfftw('pyfftw')])
exponent = simple_fixture('exponent', [2.0, 1.0, float('inf'), 1.5])
sign = simple_fixture('sign', ['-', '+'])

# --- helper functions --- #


def _params_from_dtype(dtype):
    if is_real_dtype(dtype):
        halfcomplex = True
    else:
        halfcomplex = False
    return halfcomplex, complex_dtype(dtype)

Esempio n. 4
0
from __future__ import division

import numpy as np
import pytest

import odl
from odl.discr.lp_discr import DiscreteLp, DiscreteLpElement
from odl.space.base_tensors import TensorSpace
from odl.space.npy_tensors import NumpyTensor
from odl.space.weighting import ConstWeighting
from odl.util.testutils import (all_almost_equal, all_equal, noise_elements,
                                simple_fixture)

# --- Pytest fixtures --- #

exponent = simple_fixture('exponent', [2.0, 1.0, float('inf'), 0.5, 1.5])
power = simple_fixture('power', [1.0, 2.0, 0.5, -0.5, -1.0, -2.0])
shape = simple_fixture('shape', [(2, 3, 4), (3, 4), (2, ), (1, ), (1, 1, 1)])
power = simple_fixture('power', [1.0, 2.0, 0.5, -0.5, -1.0, -2.0])

# --- DiscreteLp --- #


def test_discretelp_init():
    """Test initialization and basic properties of DiscreteLp."""
    # Real space
    fspace = odl.FunctionSpace(odl.IntervalProd([0, 0], [1, 1]))
    part = odl.uniform_partition_fromintv(fspace.domain, (2, 4))
    tspace = odl.rn(part.shape)

    discr = DiscreteLp(fspace, part, tspace)
Esempio n. 5
0
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
"""Test for the figures of merit (FOMs) that use a known ground truth."""

from __future__ import division
import numpy as np
import pytest
import scipy.signal
import scipy.misc
import odl
from odl.contrib import fom
from odl.util.testutils import simple_fixture, noise_element

fft_impl = simple_fixture('fft_impl', [
    odl.util.testutils.never_skip('numpy'),
    odl.util.testutils.skip_if_no_pyfftw('pyfftw')
])

space = simple_fixture('space', [
    odl.rn(3),
    odl.rn(3, dtype='float32'),
    odl.uniform_discr(0, 1, 10),
    odl.uniform_discr([0, 0], [1, 1], [5, 5])
])

scalar_fom = simple_fixture('scalar_fom', [
    fom.mean_squared_error, fom.mean_absolute_error, fom.mean_value_difference,
    fom.standard_deviation_difference, fom.range_difference, fom.blurring
])

from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()

import numpy as np
import pytest
import scipy.special
import odl
from odl.util.testutils import (noise_element, all_almost_equal,
                                simple_fixture)
from odl.solvers.functional.functional import FunctionalDefaultConvexConjugate

pytestmark = odl.util.skip_if_no_largescale


stepsize = simple_fixture('stepsize', [0.1, 1.0, 10.0])
offset = simple_fixture('offset', [False, True])
dual = simple_fixture('dual', [False, True])


func_params = ['l1', 'l2', 'l2^2', 'kl', 'kl_cross_ent', 'const',
               'groupl1-1', 'groupl1-2',
               'nuclearnorm-1-1', 'nuclearnorm-1-2', 'nuclearnorm-1-inf']
func_ids = [' f = {} '.format(p.ljust(10)) for p in func_params]


@pytest.fixture(scope="module", ids=func_ids, params=func_params)
def functional(request, offset, dual):
    """Return functional whose proximal should be tested."""
    name = request.param.strip()
Esempio n. 7
0
from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()

import pytest
import numpy as np

import odl
from odl.discr.diff_ops import (
    finite_diff, PartialDerivative, Gradient, Divergence, Laplacian)
from odl.util.testutils import (
    all_equal, all_almost_equal, almost_equal, never_skip, noise_element,
    simple_fixture)


method = simple_fixture('method', ['central', 'forward', 'backward'])
padding = simple_fixture('padding', [('constant', 0), ('constant', 1),
                                     'symmetric', 'periodic',
                                     'order0', 'order1', 'order2'])


@pytest.fixture(scope="module", params=[1, 2, 3], ids=['1d', '2d', '3d'])
def space(request, fn_impl):
    ndim = request.param

    return odl.uniform_discr([0] * ndim, [1] * ndim, [5] * ndim, impl=fn_impl)


# Test data
DATA_1D = np.array([0.5, 1, 3.5, 2, -.5, 3, -1, -1, 0, 3])
Esempio n. 8
0
# along with ODL.  If not, see <http://www.gnu.org/licenses/>.

# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()

import pytest
import numpy as np

import odl
from odl.util.testutils import (all_almost_equal, noise_element,
                                skip_if_no_pywavelets, simple_fixture)

# --- pytest fixtures --- #
wavelet = simple_fixture('wavelet', ['db1', 'sym2'])
pad_mode = simple_fixture('pad_mode', ['constant', 'pywt_periodic'])
ndim = simple_fixture('ndim', [1, 2, 3])
nlevels = simple_fixture('nlevels', [1, 3])
wave_impl = simple_fixture('wave_impl', [skip_if_no_pywavelets('pywt')])


@pytest.fixture(scope='module')
def shape_setup(ndim, wavelet, pad_mode):
    nlevels = 2

    if ndim == 1:
        image_shape = (16, )
        if wavelet == 'db1':
            coeff_shapes = [(4, ), (4, ), (8, )]
        elif wavelet == 'sym2':
"""Test for the default functionals."""

# External
import numpy as np
import scipy
import pytest

# Internal
import odl
from odl.util.testutils import (all_almost_equal, noise_element,
                                simple_fixture)
from odl.solvers.functional.default_functionals import (
    KullbackLeiblerConvexConj, KullbackLeiblerCrossEntropyConvexConj)

# --- pytest fixtures --- #
scalar = simple_fixture('scalar', [0.01, 2.7, np.array(5.0), 10, -2, -0.2,
                                   -np.array(7.1), 0])
sigma = simple_fixture('sigma', [0.001, 2.7, np.array(0.5), 10])
exponent = simple_fixture('sigma', [1, 2, 1.5, 2.5, -1.6])


space_params = ['r10', 'uniform_discr']
space_ids = [' space = {}'.format(p.ljust(10)) for p in space_params]


@pytest.fixture(scope="module", ids=space_ids, params=space_params)
def space(request, fn_impl):
    name = request.param.strip()

    if name == 'r10':
        return odl.rn(10, impl=fn_impl)
    elif name == 'uniform_discr':
Esempio n. 10
0
from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()

# External
import pytest
import numpy as np

# Internal
import odl
import odl.tomo as tomo
from odl.util.testutils import skip_if_no_largescale, simple_fixture
from odl.tomo.util.testutils import (skip_if_no_astra, skip_if_no_astra_cuda,
                                     skip_if_no_scikit)

filter_type = simple_fixture(
    'filter_type', ['Ram-Lak', 'Shepp-Logan', 'Cosine', 'Hamming', 'Hann'])
frequency_scaling = simple_fixture(
    'frequency_scaling', [0.5, 0.9, 1.0])

# Find the valid projectors
# TODO: Add nonuniform once #671 is solved
projectors = [skip_if_no_astra('par2d astra_cpu uniform'),
              skip_if_no_astra('cone2d astra_cpu uniform'),
              skip_if_no_astra_cuda('par2d astra_cuda uniform'),
              skip_if_no_astra_cuda('cone2d astra_cuda uniform'),
              skip_if_no_astra_cuda('par3d astra_cuda uniform'),
              skip_if_no_astra_cuda('cone3d astra_cuda uniform'),
              skip_if_no_astra_cuda('helical astra_cuda uniform'),
              skip_if_no_scikit('par2d scikit uniform')]

projector_ids = ['geom={}, impl={}, angles={}'
Esempio n. 11
0
# --- pytest fixtures --- #


mode_dtype_params = [(0, 'int8'), (1, 'int16'), (2, 'float32'), (6, 'uint16')]
mode_dtype_ids = [" mode = {p[0]}, dtype = '{p[1]}' ".format(p=p)
                  for p in mode_dtype_params]


@pytest.fixture(scope='module', ids=mode_dtype_ids, params=mode_dtype_params)
def mrc_mode_dtype(request):
    mode, dtype = request.param
    return mode, np.dtype(dtype)

axis_order = simple_fixture(
    name='axis_order',
    params=list(permutations((0, 1, 2))))

shape = simple_fixture(
    name='shape',
    params=[(5, 10, 20), (1, 5, 6), (10, 1, 1), (1, 1, 1)])

ispg_kind_params = [(0, 'projections'), (1, 'volume')]
ispg_kind_ids = [" ispg = {p[0]}, kind = '{p[1]}' ".format(p=p)
                 for p in ispg_kind_params]


@pytest.fixture(scope='module', ids=ispg_kind_ids, params=ispg_kind_params)
def ispg_kind(request):
    return request.param
Esempio n. 12
0
# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()

import pytest
import numpy as np

import odl
from odl.util.testutils import (all_almost_equal, noise_element,
                                skip_if_no_pywavelets, simple_fixture)


# --- pytest fixtures --- #
wavelet = simple_fixture('wavelet', ['db1', 'sym2'])
pad_mode = simple_fixture('pad_mode', ['constant', 'pywt_periodic'])
ndim = simple_fixture('ndim', [1, 2, 3])
nlevels = simple_fixture('nlevels', [1, 3])
wave_impl = simple_fixture('wave_impl', [skip_if_no_pywavelets('pywt')])


@pytest.fixture(scope='module')
def shape_setup(ndim, wavelet, pad_mode):
    nlevels = 2

    if ndim == 1:
        image_shape = (16,)
        if wavelet == 'db1':
            coeff_shapes = [(4,), (4,), (8,)]
        elif wavelet == 'sym2':
Esempio n. 13
0
    one_vec = fspace.one()

    assert one_vec([0.5, 1.5]) == 1.0
    assert all_equal(one_vec(points), np.ones(5, dtype=float))
    assert all_equal(one_vec(mg), np.ones((2, 3), dtype=float))

    # complex
    fspace = FunctionSpace(rect, field=odl.ComplexNumbers())
    one_vec = fspace.one()

    assert one_vec([0.5, 1.5]) == 1.0 + 1j * 0.0
    assert all_equal(one_vec(points), np.ones(5, dtype=complex))
    assert all_equal(one_vec(mg), np.ones((2, 3), dtype=complex))


a = simple_fixture('a', [2.0, 0.0, -1.0])
b = simple_fixture('b', [2.0, 0.0, -1.0])


def test_fspace_lincomb(a, b):
    rect, points, mg = _standard_setup_2d()
    point = points.T[0]

    fspace = FunctionSpace(rect)

    # Note: Special cases and alignment are tested later in the magic methods

    # Not vectorized
    true_novec = a * func_2d_novec(point) + b * other_func_2d_novec(point)
    f_novec = fspace.element(func_2d_novec, vectorized=False)
    g_novec = fspace.element(other_func_2d_novec, vectorized=False)
Esempio n. 14
0
# obtain one at https://mozilla.org/MPL/2.0/.
"""Test analytical reconstruction methods."""

from __future__ import division
import pytest
import numpy as np

import odl
import odl.tomo as tomo
from odl.util.testutils import skip_if_no_largescale, simple_fixture
from odl.tomo.util.testutils import (skip_if_no_astra, skip_if_no_astra_cuda,
                                     skip_if_no_skimage)

# --- pytest fixtures --- #

filter_type = simple_fixture(
    'filter_type', ['Ram-Lak', 'Shepp-Logan', 'Cosine', 'Hamming', 'Hann'])
frequency_scaling = simple_fixture('frequency_scaling', [0.5, 0.9, 1.0])

# Find the valid projectors
# TODO: Add nonuniform once #671 is solved
projectors = [
    skip_if_no_astra('par2d astra_cpu uniform'),
    skip_if_no_astra('cone2d astra_cpu uniform'),
    skip_if_no_astra_cuda('par2d astra_cuda uniform'),
    skip_if_no_astra_cuda('cone2d astra_cuda uniform'),
    skip_if_no_astra_cuda('par3d astra_cuda uniform'),
    skip_if_no_astra_cuda('cone3d astra_cuda uniform'),
    skip_if_no_astra_cuda('helical astra_cuda uniform'),
    skip_if_no_skimage('par2d skimage uniform')
]
Esempio n. 15
0
import numpy as np
import pytest
import sys

# Internal
import odl
from odl.tomo.backends.astra_cuda import (
    AstraCudaProjectorImpl, AstraCudaBackProjectorImpl)
from odl.tomo.util.testutils import skip_if_no_astra_cuda
from odl.util.testutils import simple_fixture


# TODO: test with CUDA implemented uniform_discr


use_cache = simple_fixture('use_cache', [False, True])

# Find the valid projectors
projectors = [skip_if_no_astra_cuda('par2d'),
              skip_if_no_astra_cuda('cone2d'),
              skip_if_no_astra_cuda('par3d'),
              skip_if_no_astra_cuda('cone3d'),
              skip_if_no_astra_cuda('helical')]


space_and_geometry_ids = ['geom = {}'.format(p.args[1]) for p in projectors]


@pytest.fixture(scope="module", params=projectors, ids=space_and_geometry_ids)
def space_and_geometry(request):
    dtype = 'float32'
Esempio n. 16
0
from __future__ import division
import numpy as np
import pytest

import odl
from odl.tomo.backends.astra_cuda import (AstraCudaProjectorImpl,
                                          AstraCudaBackProjectorImpl)
from odl.tomo.util.testutils import skip_if_no_astra_cuda
from odl.util.testutils import simple_fixture

# TODO: test with CUDA implemented uniform_discr

# --- pytest fixtures --- #

use_cache = simple_fixture('use_cache', [False, True])

# Find the valid projectors
projectors = [
    skip_if_no_astra_cuda('par2d'),
    skip_if_no_astra_cuda('cone2d'),
    skip_if_no_astra_cuda('par3d'),
    skip_if_no_astra_cuda('cone3d'),
    skip_if_no_astra_cuda('helical')
]

space_and_geometry_ids = ['geom = {}'.format(p.args[1]) for p in projectors]


@pytest.fixture(scope="module", params=projectors, ids=space_and_geometry_ids)
def space_and_geometry(request):
Esempio n. 17
0

# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()

import numpy as np
import pytest

from odl.util.normalize import (
    normalized_scalar_param_list, normalized_axes_tuple)
from odl.util.testutils import simple_fixture

# --- pytest fixtures --- #
length = simple_fixture('length', [1, 2])


single_conv_params = [(-1.0, float),
                      (2, float),
                      ('10', float),
                      (np.array(2.3, dtype=float), float),
                      (np.array(2, dtype=int), float),
                      (-1, int),
                      ('10', int),
                      (np.array(2, dtype=int), int),
                      (1, bool),
                      (False, bool)]

single_conv_ids = [' input = {0[0]}, conv = {0[1]} '.format(p)
                   for p in single_conv_params]
Esempio n. 18
0
"""Test for the default functionals."""

from __future__ import division
import numpy as np
import scipy.special
import pytest

import odl
from odl.util.testutils import all_almost_equal, noise_element, simple_fixture
from odl.solvers.functional.default_functionals import (
    KullbackLeiblerConvexConj, KullbackLeiblerCrossEntropyConvexConj)

# --- pytest fixtures --- #

scalar = simple_fixture(
    'scalar',
    [0.01, 2.7, np.array(5.0), 10, -2, -0.2, -np.array(7.1), 0])
sigma = simple_fixture('sigma', [0.001, 2.7, 10])
exponent = simple_fixture('sigma', [1, 2, 1.5, 2.5, -1.6])

space_params = ['r10', 'uniform_discr', 'power_space_unif_discr']
space_ids = [' space={} '.format(p) for p in space_params]


@pytest.fixture(scope="module", ids=space_ids, params=space_params)
def space(request, odl_tspace_impl):
    name = request.param.strip()
    impl = odl_tspace_impl

    if name == 'r10':
        return odl.rn(10, impl=impl)
Esempio n. 19
0
from future import standard_library
standard_library.install_aliases()

# External module imports
import pytest
import numpy as np

# Internal
import odl
from odl.discr.lp_discr import DiscreteLp
from odl.space.base_ntuples import FnBase
from odl.util.testutils import (almost_equal, all_equal, all_almost_equal,
                                noise_elements, simple_fixture)

# Simply modify exp_params to modify the fixture
exponent = simple_fixture('exponent', [2.0, 1.0, float('inf'), 0.5, 1.5])


def test_init(exponent):
    # Validate that the different init patterns work and do not crash.
    space = odl.FunctionSpace(odl.IntervalProd(0, 1))
    part = odl.uniform_partition_fromintv(space.domain, 10)
    rn = odl.rn(10, exponent=exponent)
    odl.DiscreteLp(space, part, rn, exponent=exponent)
    odl.DiscreteLp(space, part, rn, exponent=exponent, interp='linear')

    # Normal discretization of unit interval with complex
    complex_space = odl.FunctionSpace(odl.IntervalProd(0, 1),
                                      field=odl.ComplexNumbers())

    cn = odl.cn(10, exponent=exponent)
Esempio n. 20
0
import numpy as np
from scipy.signal import convolve

import odl
from odl.trafos.backends.pywt_bindings import (
    PYWT_AVAILABLE, pywt_coeff_shapes, pywt_flat_array_from_coeffs,
    pywt_coeffs_from_flat_array, pywt_single_level_decomp,
    pywt_multi_level_decomp, pywt_multi_level_recon)
from odl.util.testutils import (all_almost_equal, all_equal, noise_array,
                                simple_fixture)

pytestmark = pytest.mark.skipif(not PYWT_AVAILABLE,
                                reason='`pywt` backend not available')

# --- pytest fixtures --- #
wavelet = simple_fixture('wavelet', ['db1', 'sym2'])
pywt_mode = simple_fixture('pywt_mode', ['zero', 'periodization'])
ndim = simple_fixture('ndim', [1, 2, 3])
nlevels = simple_fixture('nlevels', [1, 3])


@pytest.fixture(scope='module')
def shape_setup(ndim, wavelet, pywt_mode):
    nlevels = 2

    if ndim == 1:
        image_shape = (16, )
        if wavelet == 'db1':
            coeff_shapes = [(4, ), (4, ), (8, )]
        elif wavelet == 'sym2':
            if pywt_mode == 'zero':
Esempio n. 21
0
import pytest

from odl.trafos.backends import pyfftw_call, PYFFTW_AVAILABLE
from odl.util import (
    is_real_dtype, complex_dtype)
from odl.util.testutils import (
    all_almost_equal, simple_fixture)


pytestmark = pytest.mark.skipif(not PYFFTW_AVAILABLE,
                                reason='`pyfftw` backend not available')


# --- pytest fixtures --- #

planning = simple_fixture('planning', ['estimate', 'measure', 'patient',
                                       'exhaustive'])
direction = simple_fixture('direction', ['forward', 'backward'])

# --- helper functions --- #


def _random_array(shape, dtype):
    if is_real_dtype(dtype):
        return np.random.rand(*shape).astype(dtype)
    else:
        return (np.random.rand(*shape).astype(dtype) +
                1j * np.random.rand(*shape).astype(dtype))


def _params_from_dtype(dtype):
    if is_real_dtype(dtype):
Esempio n. 22
0
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.

from __future__ import division
import pytest
import numpy as np

import odl
from odl.discr.lp_discr import DiscreteLp
from odl.space.base_ntuples import FnBase
from odl.util.testutils import (almost_equal, all_equal, all_almost_equal,
                                noise_elements, simple_fixture)

exponent = simple_fixture('exponent', [2.0, 1.0, float('inf'), 0.5, 1.5])
power = simple_fixture('power', [1.0, 2.0, 0.5, -0.5, -1.0, -2.0])


def test_init(exponent):
    # Validate that the different init patterns work and do not crash.
    space = odl.FunctionSpace(odl.IntervalProd(0, 1))
    part = odl.uniform_partition_fromintv(space.domain, 10)
    rn = odl.rn(10, exponent=exponent)
    odl.DiscreteLp(space, part, rn, exponent=exponent)
    odl.DiscreteLp(space, part, rn, exponent=exponent, interp='linear')

    # Normal discretization of unit interval with complex
    complex_space = odl.FunctionSpace(odl.IntervalProd(0, 1),
                                      field=odl.ComplexNumbers())
Esempio n. 23
0
Header-related things are tested in the MRC tests, so we only test
the raw binary data I/O here.
"""

from __future__ import division
import numpy as np
import tempfile

import odl
from odl.contrib.mrc import (FileWriterRawBinaryWithHeader,
                             FileReaderRawBinaryWithHeader)
from odl.util.testutils import simple_fixture

# --- pytest fixtures --- #

shape = simple_fixture(name='shape',
                       params=[(5, 10, 20), (1, 5, 6), (10, 1, 1), (1, 1, 1)])

order = simple_fixture(name='order', params=['F', 'C'])

# --- Tests --- #


def test_uncompr_bin_io_without_header(shape, floating_dtype, order):
    """Test I/O bypassing the header processing."""
    dtype = np.dtype(floating_dtype)
    order = str(order).upper()
    with tempfile.NamedTemporaryFile() as named_file:
        file = named_file.file

        # data is f(x, y, z) = z
        data = np.ones(shape, dtype=dtype)
Esempio n. 24
0
# obtain one at https://mozilla.org/MPL/2.0/.

"""Tests for supervised FoMs."""

from __future__ import division
import numpy as np
import pytest
import scipy.signal
import scipy.misc
import odl
import odl.contrib.fom
from odl.contrib.fom.util import filter_image_sep2d
from odl.util.testutils import simple_fixture

fft_impl = simple_fixture('fft_impl',
                          [odl.util.testutils.never_skip('numpy'),
                           odl.util.testutils.skip_if_no_pyfftw('pyfftw')])
space = simple_fixture('space',
                       [odl.rn(3),
                        odl.uniform_discr(0, 1, 10)])


def filter_image(image, fh, fv):
    """Reference filtering function using ``scipy.signal.convolve``."""
    fh, fv = np.asarray(fh), np.asarray(fv)
    image = scipy.signal.convolve(image, fh[:, None], mode='same')
    return scipy.signal.convolve(image, fv[None, :], mode='same')


def test_filter_image_fft(fft_impl):
    """Test the FFT filtering function against the real-space variant."""
from __future__ import division, print_function
import numpy as np
import pytest
import scipy.special

import odl
from odl.util.testutils import (noise_element, all_almost_equal,
                                simple_fixture)
from odl.solvers.functional.functional import FunctionalDefaultConvexConjugate

# --- pytest fixtures --- #

pytestmark = odl.util.skip_if_no_largescale

stepsize = simple_fixture('stepsize', [0.1, 1.0, 10.0])
linear_offset = simple_fixture('linear_offset', [False, True])
quadratic_offset = simple_fixture('quadratic_offset', [False, True])
dual = simple_fixture('dual', [False, True])

func_params = [
    'l1', 'l2', 'l2^2', 'kl', 'kl_cross_ent', 'const', 'groupl1-1',
    'groupl1-2', 'nuclearnorm-1-1', 'nuclearnorm-1-2', 'nuclearnorm-1-inf',
    'quadratic', 'linear', 'huber'
]

func_ids = [" functional='{}' ".format(p) for p in func_params]


@pytest.fixture(scope="module", ids=func_ids, params=func_params)
def functional(request, linear_offset, quadratic_offset, dual):
Esempio n. 26
0
# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from future import standard_library

standard_library.install_aliases()

import numpy as np
import pytest

import odl
from odl.deform import LinDeformFixedTempl, LinDeformFixedDisp
from odl.util.testutils import almost_equal, simple_fixture

# Set up fixtures
dtype = simple_fixture('dtype', ['float', 'complex'])
interp = simple_fixture('interp', ['linear', 'nearest'])
ndim = simple_fixture('ndim', [1, 2, 3])


@pytest.fixture
def space(request, ndim, interp, dtype, fn_impl):
    """Example space.

    Generates example spaces with various implementations, dimensions, dtypes
    and interpolations.
    """
    if np.dtype(dtype) not in odl.FN_IMPLS[fn_impl].available_dtypes():
        pytest.skip('dtype not available for this backend')

    return odl.uniform_discr([-1] * ndim, [1] * ndim, [20] * ndim,
Esempio n. 27
0
import pytest

import odl
from odl.trafos.fourier import (DiscreteFourierTransform,
                                DiscreteFourierTransformInverse,
                                FourierTransform)
from odl.trafos.util.ft_utils import (_interp_kernel_ft, dft_postprocess_data,
                                      dft_preprocess_data, reciprocal_grid)
from odl.util import (all_almost_equal, complex_dtype, conj_exponent,
                      is_real_dtype, noise_element, skip_if_no_pyfftw)
from odl.util.testutils import simple_fixture

# --- pytest fixtures --- #

impl = simple_fixture(
    'impl',
    [pytest.param('numpy'),
     pytest.param('pyfftw', marks=skip_if_no_pyfftw)])
exponent = simple_fixture('exponent', [2.0, 1.0, float('inf'), 1.5])
sign = simple_fixture('sign', ['-', '+'])

# --- Helper functions --- #


def _params_from_dtype(dtype):
    if is_real_dtype(dtype):
        halfcomplex = True
    else:
        halfcomplex = False
    return halfcomplex, complex_dtype(dtype)

Esempio n. 28
0
"""Test ODL geometry objects for tomography."""

from __future__ import division

from itertools import permutations, product
import pytest
import numpy as np

import odl
from odl.util.testutils import all_almost_equal, all_equal, simple_fixture

# --- pytest fixtures --- #

det_pos_init_2d = simple_fixture(
    name='det_pos_init',
    params=list(
        set(permutations([1, 0])) | set(permutations([-1, 0]))
        | set(permutations([1, -1]))))
det_pos_init_3d_params = list(
    set(permutations([1, 0, 0])) | set(permutations([-1, 0, 0]))
    | set(permutations([1, -1, 0])) | set(product([-1, 1], repeat=3)))
det_pos_init_3d = simple_fixture('det_pos_init', det_pos_init_3d_params)
axis = simple_fixture('axis', det_pos_init_3d_params)
shift = simple_fixture('shift', [0, 1])

# --- tests --- #


def test_parallel_2d_props(shift):
    """Test basic properties of 2D parallel geometries."""
    full_angle = np.pi
Esempio n. 29
0
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.

from __future__ import division

import numpy as np
import pytest

import odl
from odl.util.normalize import (normalized_axes_tuple,
                                normalized_scalar_param_list)
from odl.util.testutils import simple_fixture

# --- pytest fixtures --- #

length = simple_fixture('length', [1, 2])

# For this and other fixtures below:
# scope='module' removed due to pytest issue, see
# https://github.com/pytest-dev/pytest/issues/6497
# TODO: re-introduce when fixed
single_conv_params = [(-1.0, float), (2, float), ('10', float),
                      (np.array(2.3, dtype=float), float),
                      (np.array(2, dtype=int), float), (-1, int), ('10', int),
                      (np.array(2, dtype=int), int), (1, bool), (False, bool)]

single_conv_ids = [
    ' input = {0[0]}, conv = {0[1]} '.format(p) for p in single_conv_params
]

Esempio n. 30
0
    for i in range(ndim):
        vec = np.random.uniform(low=min_pt[i], high=max_pt[i], size=shape[i])
        vec.sort()
        coord_vecs.append(vec)
    return sparse_meshgrid(*coord_vecs)


class FuncList(list):  # So we can set __name__
    pass


# --- pytest fixtures (general) --- #

out_dtype_params = ['float32', 'float64', 'complex64']
out_dtype = simple_fixture('out_dtype',
                           out_dtype_params,
                           fmt=' {name} = {value!r} ')

out_shape = simple_fixture('out_shape', [(), (2, ), (2, 3)])
domain_ndim = simple_fixture('domain_ndim', [1, 2])
vectorized = simple_fixture('vectorized', [True, False])
a = simple_fixture('a', [0.0, 1.0, -2.0])
b = simple_fixture('b', [0.0, 1.0, -2.0])
power = simple_fixture('power', [3, 1.0, 0.5, -2.0])


@pytest.fixture(scope='module')
def fspace_scal(domain_ndim, out_dtype):
    """Fixture returning a function space with given properties."""
    domain = odl.IntervalProd([0] * domain_ndim, [1] * domain_ndim)
    return FunctionSpace(domain, out_dtype=out_dtype)
Esempio n. 31
0
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.

from __future__ import division
import pytest
import odl
from odl.util.testutils import simple_fixture, noise_element

# --- pytest fixtures --- #

hilbert_spaces = [odl.rn(3), odl.cn(3), odl.uniform_discr(0, 1, 3)]
normed_spaces = [odl.rn(3, exponent=1)] + hilbert_spaces
metric_spaces = normed_spaces
linear_spaces = metric_spaces

hilbert_space = simple_fixture('hilbert_space', hilbert_spaces)
normed_space = simple_fixture('normed_space', normed_spaces)
metric_space = simple_fixture('metric_space', metric_spaces)
linear_space = simple_fixture('linear_space', linear_spaces)

# --- LinearSpace tests --- #


def test_hash(linear_space):
    """Verify that hashing spaces works but elements doesnt."""
    hsh = hash(linear_space)

    # Check that the trivial hash algorithm is not used
    assert hsh != id(linear_space)

    x = noise_element(linear_space)
Esempio n. 32
0
import pytest
from packaging.version import parse as parse_version

import odl
from odl.tomo.backends import ASTRA_VERSION
from odl.tomo.util.testutils import (
    skip_if_no_astra, skip_if_no_astra_cuda, skip_if_no_skimage)
from odl.util.testutils import all_almost_equal, simple_fixture


# --- pytest fixtures --- #


impl = simple_fixture(
    name='impl',
    params=[pytest.param('astra_cpu', marks=skip_if_no_astra),
            pytest.param('astra_cuda', marks=skip_if_no_astra_cuda),
            pytest.param('skimage', marks=skip_if_no_skimage)]
)

geometry_params = ['par2d', 'par3d', 'cone2d', 'cone3d', 'helical']
geometry_ids = [" geometry='{}' ".format(p) for p in geometry_params]


@pytest.fixture(scope='module', ids=geometry_ids, params=geometry_params)
def geometry(request):
    geom = request.param
    m = 100
    n_angles = 100

    if geom == 'par2d':
        apart = odl.uniform_partition(0, np.pi, n_angles)
Esempio n. 33
0
# This file is part of ODL.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
"""Unit tests for the ODL-PyTorch integration."""

import numpy as np
import torch
from torch import nn

import odl
from odl.contrib import torch as odl_torch
from odl.util.testutils import all_almost_equal, simple_fixture

dtype = simple_fixture('dtype', ['float32', 'float64'])
device_params = ['cpu']
if torch.cuda.is_available():
    device_params.append('cuda')
device = simple_fixture('device', device_params)
shape = simple_fixture('shape', [(3, ), (2, 3), (2, 2, 3)])


def test_autograd_function_forward(dtype, device):
    """Test forward evaluation with operators as autograd functions."""
    # Define ODL operator
    matrix = np.random.rand(2, 3).astype(dtype)
    odl_op = odl.MatrixOperator(matrix)

    # Compute forward pass with both ODL and PyTorch
    x_arr = np.ones(3, dtype=dtype)
Esempio n. 34
0
import pytest

import odl
from odl.operator import OpTypeError
from odl.util.testutils import (all_almost_equal, dtype_ndigits, dtype_tol,
                                noise_element, simple_fixture)
from odl.solvers.functional.default_functionals import (
    KullbackLeiblerConvexConj)

# TODO: maybe add tests for if translations etc. belongs to the wrong space.
# These tests don't work as intended now, since casting is possible between
# spaces with the same number of discretization points.

# --- pytest fixtures --- #

scalar = simple_fixture('scalar', [0.01, 2.7, 10, -2, -0.2, -7.1, 0])
sigma = simple_fixture('sigma', [0.001, 2.7, np.array(0.5), 10])

space_params = ['r10', 'uniform_discr', 'power_space_unif_discr']
space_ids = [' space={} '.format(p) for p in space_params]


@pytest.fixture(scope="module", ids=space_ids, params=space_params)
def space(request, odl_tspace_impl):
    name = request.param.strip()
    impl = odl_tspace_impl

    if name == 'r10':
        return odl.rn(10, impl=impl)
    elif name == 'uniform_discr':
        # Discretization parameters
Esempio n. 35
0
from odl.trafos.backends.pywt_bindings import (
    PYWT_AVAILABLE,
    pywt_coeff_shapes,
    pywt_flat_array_from_coeffs, pywt_coeffs_from_flat_array,
    pywt_single_level_decomp,
    pywt_multi_level_decomp, pywt_multi_level_recon)
from odl.util.testutils import (all_almost_equal, all_equal, noise_array,
                                simple_fixture)


pytestmark = pytest.mark.skipif(not PYWT_AVAILABLE,
                                reason='`pywt` backend not available')


# --- pytest fixtures --- #
wavelet = simple_fixture('wavelet', ['db1', 'sym2'])
pywt_mode = simple_fixture('pywt_mode', ['zero', 'periodization'])
ndim = simple_fixture('ndim', [1, 2, 3])
nlevels = simple_fixture('nlevels', [1, 3])


@pytest.fixture(scope='module')
def shape_setup(ndim, wavelet, pywt_mode):
    nlevels = 2

    if ndim == 1:
        image_shape = (16,)
        if wavelet == 'db1':
            coeff_shapes = [(4,), (4,), (8,)]
        elif wavelet == 'sym2':
            if pywt_mode == 'zero':
Esempio n. 36
0
# --- pytest fixtures --- #

mode_dtype_params = [(0, 'int8'), (1, 'int16'), (2, 'float32'), (6, 'uint16')]
mode_dtype_ids = [
    " mode = {p[0]}, dtype = '{p[1]}' ".format(p=p) for p in mode_dtype_params
]


@pytest.fixture(scope='module', ids=mode_dtype_ids, params=mode_dtype_params)
def mrc_mode_dtype(request):
    mode, dtype = request.param
    return mode, np.dtype(dtype)


axis_order = simple_fixture(name='axis_order',
                            params=list(permutations((0, 1, 2))))

shape = simple_fixture(name='shape',
                       params=[(5, 10, 20), (1, 5, 6), (10, 1, 1), (1, 1, 1)])

ispg_kind_params = [(0, 'projections'), (1, 'volume')]
ispg_kind_ids = [
    " ispg = {p[0]}, kind = '{p[1]}' ".format(p=p) for p in ispg_kind_params
]


@pytest.fixture(scope='module', ids=ispg_kind_ids, params=ispg_kind_params)
def ispg_kind(request):
    return request.param

Esempio n. 37
0
from __future__ import division
import pytest
import numpy as np
from pkg_resources import parse_version

import odl
import odl.tomo as tomo
from odl.util.testutils import skip_if_no_largescale, simple_fixture
from odl.tomo.util.testutils import (skip_if_no_astra, skip_if_no_astra_cuda,
                                     skip_if_no_skimage)

# --- pytest fixtures --- #

dtype_params = ['float32', 'float64', 'complex64']
dtype = simple_fixture('dtype', dtype_params)

# Find the valid projectors
projectors = [
    skip_if_no_astra('par2d astra_cpu uniform'),
    skip_if_no_astra('par2d astra_cpu nonuniform'),
    skip_if_no_astra('par2d astra_cpu random'),
    skip_if_no_astra('cone2d astra_cpu uniform'),
    skip_if_no_astra('cone2d astra_cpu nonuniform'),
    skip_if_no_astra('cone2d astra_cpu random'),
    skip_if_no_astra_cuda('par2d astra_cuda uniform'),
    skip_if_no_astra_cuda('par2d astra_cuda nonuniform'),
    skip_if_no_astra_cuda('par2d astra_cuda random'),
    skip_if_no_astra_cuda('cone2d astra_cuda uniform'),
    skip_if_no_astra_cuda('cone2d astra_cuda nonuniform'),
    skip_if_no_astra_cuda('cone2d astra_cuda random'),
Esempio n. 38
0
                                                                  copy=False)
    elif np.issubdtype(fn.dtype, np.complexfloating):
        mat = (np.random.rand(fn.size, fn.size) +
               1j * np.random.rand(fn.size, fn.size)).astype(fn.dtype,
                                                             copy=False)

    # Make symmetric and positive definite
    return mat + mat.conj().T + fn.size * np.eye(fn.size, dtype=fn.dtype)


def _sparse_matrix(fn):
    """Create a sparse positive definite Hermitian matrix for `fn`."""
    return scipy.sparse.coo_matrix(_dense_matrix(fn))


exponent = simple_fixture('exponent', [2.0, 1.0, float('inf'), 3.5, 1.5])
fn = simple_fixture('fn', [
    odl.rn(10, np.float64),
    odl.rn(10, np.float32),
    odl.cn(10, np.complex128),
    odl.cn(10, np.complex64),
    odl.rn(100),
    odl.uniform_discr(0, 1, 5)
])

# ---- PointwiseNorm ----


def test_pointwise_norm_init_properties():
    # 1d
    fspace = odl.uniform_discr([0, 0], [1, 1], (2, 2))
Esempio n. 39
0
import odl
from odl import (Operator, OperatorSum, OperatorComp, OperatorLeftScalarMult,
                 OperatorRightScalarMult, FunctionalLeftVectorMult,
                 OperatorRightVectorMult, MatrixOperator,
                 OperatorLeftVectorMult, OpTypeError, OpDomainError,
                 OpRangeError)
from odl.operator.operator import _function_signature, _dispatch_call_args
from odl.util.testutils import (all_almost_equal, noise_element,
                                noise_elements, simple_fixture)
from odl.util.utility import getargspec

# --- Fixtures --- #

# This fixture is intended to activate testing of operator evaluation
# with aliased input and output, which is only possible if domain == range.
dom_eq_ran = simple_fixture('dom_eq_ran', [True, False])

# --- Auxilliary --- #


class MultiplyAndSquareOp(Operator):
    """Example of a nonlinear operator, x --> (mat*x)**2."""
    def __init__(self, matrix, domain=None, range=None):
        dom = (odl.rn(matrix.shape[1]) if domain is None else domain)
        ran = (odl.rn(matrix.shape[0]) if range is None else range)

        super(MultiplyAndSquareOp, self).__init__(dom, ran)
        self.matrix = matrix

    def _call(self, x, out=None):
        if out is None:
Esempio n. 40
0
# obtain one at https://mozilla.org/MPL/2.0/.
"""Unit tests for `diff_ops`."""

from __future__ import division
import pytest
import numpy as np

import odl
from odl.discr.diff_ops import (finite_diff, PartialDerivative, Gradient,
                                Divergence, Laplacian)
from odl.util.testutils import (all_equal, all_almost_equal, almost_equal,
                                noise_element, simple_fixture)

# --- pytest fixtures --- #

method = simple_fixture('method', ['central', 'forward', 'backward'])
padding = simple_fixture(
    'padding',
    [('constant', 0),
     ('constant', 1), 'symmetric', 'periodic', 'order0', 'order1', 'order2'])


@pytest.fixture(scope="module", params=[1, 2, 3], ids=['1d', '2d', '3d'])
def space(request, odl_tspace_impl):
    impl = odl_tspace_impl
    ndim = request.param

    return odl.uniform_discr([0] * ndim, [1] * ndim, [5] * ndim, impl=impl)


# Test data
from packaging.version import parse as parse_version

import odl
from odl.tomo.util.testutils import (
    skip_if_no_astra, skip_if_no_astra_cuda, skip_if_no_skimage)
from odl.util.testutils import simple_fixture, skip_if_no_largescale


# --- pytest fixtures --- #


pytestmark = skip_if_no_largescale


dtype_params = ['float32', 'float64', 'complex64']
dtype = simple_fixture('dtype', dtype_params)


# Find the valid projectors
projectors = []
projectors.extend(
    (pytest.param(proj_cfg, marks=skip_if_no_astra)
     for proj_cfg in ['par2d astra_cpu uniform',
                      'par2d astra_cpu nonuniform',
                      'par2d astra_cpu random',
                      'cone2d astra_cpu uniform',
                      'cone2d astra_cpu nonuniform',
                      'cone2d astra_cpu random'])
)
projectors.extend(
    (pytest.param(proj_cfg, marks=skip_if_no_astra_cuda)
Esempio n. 42
0
                                       'wavelet.py'))

# Remove duplicates
collect_ignore = list(set(collect_ignore))
collect_ignore = [os.path.normcase(ignored) for ignored in collect_ignore]


def pytest_ignore_collect(path, config):
    normalized = os.path.normcase(str(path))
    return any(normalized.startswith(ignored) for ignored in collect_ignore)


# --- Reusable fixtures ---

# Simple ones, use helper
tspace_impl = simple_fixture(name='tspace_impl',
                             params=tensor_space_impl_names())

floating_dtypes = np.sctypes['float'] + np.sctypes['complex']
floating_dtype_params = [np.dtype(dt) for dt in floating_dtypes]
floating_dtype = simple_fixture(name='dtype',
                                params=floating_dtype_params,
                                fmt=' {name} = np.{value.name} ')

scalar_dtypes = floating_dtype_params + np.sctypes['int'] + np.sctypes['uint']
scalar_dtype_params = [np.dtype(dt) for dt in floating_dtypes]
scalar_dtype = simple_fixture(name='dtype',
                              params=scalar_dtype_params,
                              fmt=' {name} = np.{value.name} ')

elem_order = simple_fixture(name='order', params=[None, 'C', 'F'])
Esempio n. 43
0
standard_library.install_aliases()

import pytest
import numpy as np
import tempfile

from odl.tomo.data import (
    FileWriterRawBinaryWithHeader, FileReaderRawBinaryWithHeader)
from odl.util.testutils import simple_fixture


# --- pytest fixtures --- #


shape = simple_fixture(
    name='shape',
    params=[(5, 10, 20), (1, 5, 6), (10, 1, 1), (1, 1, 1)])

order = simple_fixture(name='order', params=['F', 'C'])


# --- Tests --- #


def test_uncompr_bin_io_without_header(shape, floating_dtype, order):
    """Test I/O bypassing the header processing."""
    dtype = np.dtype(floating_dtype)
    with tempfile.NamedTemporaryFile() as named_file:
        file = named_file.file

        # data is f(x, y, z) = z