Exemplo n.º 1
0
def test_nearest_interpolation_2d_string():
    rect = odl.Rectangle([0, 0], [1, 1])
    part = odl.uniform_partition_fromintv(rect, [4, 2], nodes_on_bdry=False)
    # Coordinate vectors are:
    # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75]

    space = odl.FunctionSet(rect, odl.Strings(1))
    dspace = odl.Ntuples(part.size, dtype='U1')
    interp_op = NearestInterpolation(space, part, dspace)
    values = np.array([c for c in 'mystring'])
    function = interp_op(values)

    # Evaluate at single point
    val = function([0.3, 0.6])  # closest to index (1, 1) -> 3
    assert val == 't'
    # Input array, with and without output array
    pts = np.array([[0.3, 0.6], [1.0, 1.0]])
    true_arr = ['t', 'g']
    assert all_equal(function(pts.T), true_arr)
    out = np.empty(2, dtype='U1')
    function(pts.T, out=out)
    assert all_equal(out, true_arr)
    # Input meshgrid, with and without output array
    mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0])
    # Indices: (1, 3) x (0, 1)
    true_mg = [['s', 't'], ['n', 'g']]
    assert all_equal(function(mg), true_mg)
    out = np.empty((2, 2), dtype='U1')
    function(mg, out=out)
    assert all_equal(out, true_mg)
Exemplo n.º 2
0
def test_pointwise_inner_init_properties():
    fspace = odl.uniform_discr([0, 0], [1, 1], (2, 2))
    vfspace = ProductSpace(fspace, 3, exponent=2)

    # Make sure the code runs and test the properties
    pwinner = PointwiseInner(vfspace, vfspace.one())
    assert pwinner.base_space == fspace
    assert all_equal(pwinner.weights, [1, 1, 1])
    assert not pwinner.is_weighted
    repr(pwinner)

    pwinner = PointwiseInner(vfspace, vfspace.one(), weight=[1, 2, 3])
    assert all_equal(pwinner.weights, [1, 2, 3])
    assert pwinner.is_weighted

    # Bad input
    with pytest.raises(TypeError):
        PointwiseInner(odl.Rn(3), odl.Rn(3).one())  # No power space

    # TODO: Does not raise currently, although bad_vecfield not in vfspace!
    """
    bad_vecfield = ProductSpace(fspace, 3, exponent=1).one()
    with pytest.raises(TypeError):
        PointwiseInner(vfspace, bad_vecfield)
    """

    with pytest.raises(ValueError):
        PointwiseInner(vfspace, vfspace.one(), weight=-1)  # < 0 not allowed

    with pytest.raises(ValueError):
        PointwiseInner(vfspace, vfspace.one(), weight=[1, 0, 1])  # 0 invalid
Exemplo n.º 3
0
def test_nearest_interpolation_1d_complex():
    """Test nearest neighbor interpolation in 1d with complex values."""
    coord_vecs = [[0.1, 0.3, 0.5, 0.7, 0.9]]
    f = np.array([0 + 1j, 1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j], dtype="complex128")
    interpolator = nearest_interpolator(f, coord_vecs)

    # Evaluate at single point
    val = interpolator(0.35)  # closest to index 1 -> 1 + 2j
    assert val == 1.0 + 2.0j
    # Input array, with and without output array
    pts = np.array([0.39, 0.0, 0.65, 0.95])
    true_arr = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j]
    assert all_equal(interpolator(pts), true_arr)
    # Should also work with a (1, N) array
    pts = pts[None, :]
    assert all_equal(interpolator(pts), true_arr)
    out = np.empty(4, dtype='complex128')
    interpolator(pts, out=out)
    assert all_equal(out, true_arr)
    # Input meshgrid, with and without output array
    # Same as array for 1d
    mg = sparse_meshgrid([0.39, 0.0, 0.65, 0.95])
    true_mg = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j]
    assert all_equal(interpolator(mg), true_mg)
    interpolator(mg, out=out)
    assert all_equal(out, true_mg)
Exemplo n.º 4
0
def test_nearest_interpolation_2d_float():
    """Test nearest neighbor interpolation in 2d."""
    rect = odl.IntervalProd([0, 0], [1, 1])
    part = odl.uniform_partition_fromintv(rect, [4, 2], nodes_on_bdry=False)
    # Coordinate vectors are:
    # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75]

    fspace = odl.FunctionSpace(rect)
    tspace = odl.rn(part.shape)
    interp_op = NearestInterpolation(fspace, part, tspace)
    function = interp_op(np.reshape([0, 1, 2, 3, 4, 5, 6, 7], part.shape))

    # Evaluate at single point
    val = function([0.3, 0.6])  # closest to index (1, 1) -> 3
    assert val == 3.0
    # Input array, with and without output array
    pts = np.array([[0.3, 0.6], [1.0, 1.0]])
    true_arr = [3, 7]
    assert all_equal(function(pts.T), true_arr)
    out = np.empty(2, dtype='float64')
    function(pts.T, out=out)
    assert all_equal(out, true_arr)
    # Input meshgrid, with and without output array
    mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0])
    # Indices: (1, 3) x (0, 1)
    true_mg = [[2, 3], [6, 7]]
    assert all_equal(function(mg), true_mg)
    out = np.empty((2, 2), dtype='float64')
    function(mg, out=out)
    assert all_equal(out, true_mg)

    assert repr(interp_op) != ''
Exemplo n.º 5
0
def test_pointwise_inner_init_properties():
    fspace = odl.uniform_discr([0, 0], [1, 1], (2, 2))
    vfspace = ProductSpace(fspace, 3, exponent=2)

    # Make sure the code runs and test the properties
    pwinner = PointwiseInner(vfspace, vfspace.one())
    assert pwinner.base_space == fspace
    assert all_equal(pwinner.weights, [1, 1, 1])
    assert not pwinner.is_weighted
    repr(pwinner)

    pwinner = PointwiseInner(vfspace, vfspace.one(), weight=[1, 2, 3])
    assert all_equal(pwinner.weights, [1, 2, 3])
    assert pwinner.is_weighted

    # Bad input
    with pytest.raises(TypeError):
        PointwiseInner(odl.Rn(3), odl.Rn(3).one())  # No power space

    # TODO: Does not raise currently, although bad_vecfield not in vfspace!
    """
    bad_vecfield = ProductSpace(fspace, 3, exponent=1).one()
    with pytest.raises(TypeError):
        PointwiseInner(vfspace, bad_vecfield)
    """

    with pytest.raises(ValueError):
        PointwiseInner(vfspace, vfspace.one(), weight=-1)  # < 0 not allowed

    with pytest.raises(ValueError):
        PointwiseInner(vfspace, vfspace.one(), weight=[1, 0, 1])  # 0 invalid
Exemplo n.º 6
0
def test_asarray_2d():
    discr_F = odl.uniform_discr([0, 0], [1, 1], [2, 2], order='F')
    elem_F = discr_F.element([[1, 2], [3, 4]])

    # Verify that returned array equals input data
    assert all_equal(elem_F.asarray(), [[1, 2], [3, 4]])
    # Check order of out array
    assert elem_F.asarray().flags['F_CONTIGUOUS']

    # test out parameter
    out_F = np.asfortranarray(np.empty([2, 2]))
    result_F = elem_F.asarray(out=out_F)
    assert result_F is out_F
    assert all_equal(out_F, [[1, 2], [3, 4]])

    # Try discontinuous
    out_F_wrong = np.asfortranarray(np.empty([2, 2]))[::2, :]
    with pytest.raises(ValueError):
        result_F = elem_F.asarray(out=out_F_wrong)

    # Try wrong shape
    out_F_wrong = np.asfortranarray(np.empty([2, 3]))
    with pytest.raises(ValueError):
        result_F = elem_F.asarray(out=out_F_wrong)

    # Try wrong order
    out_F_wrong = np.empty([2, 2])
    with pytest.raises(ValueError):
        elem_F.asarray(out=out_F_wrong)

    # Also check with C ordering
    discr_C = odl.uniform_discr([0, 0], [1, 1], (2, 2), order='C')
    elem_C = discr_C.element([[1, 2], [3, 4]])

    # Verify that returned array equals input data
    assert all_equal(elem_C.asarray(), [[1, 2], [3, 4]])

    # Check order of out array
    assert elem_C.asarray().flags['C_CONTIGUOUS']

    # test out parameter
    out_C = np.empty([2, 2])
    result_C = elem_C.asarray(out=out_C)
    assert result_C is out_C
    assert all_equal(out_C, [[1, 2], [3, 4]])

    # Try discontinuous
    out_C_wrong = np.empty([4, 2])[::2, :]
    with pytest.raises(ValueError):
        result_C = elem_C.asarray(out=out_C_wrong)

    # Try wrong shape
    out_C_wrong = np.empty([2, 3])
    with pytest.raises(ValueError):
        result_C = elem_C.asarray(out=out_C_wrong)

    # Try wrong order
    out_C_wrong = np.asfortranarray(np.empty([2, 2]))
    with pytest.raises(ValueError):
        elem_C.asarray(out=out_C_wrong)
Exemplo n.º 7
0
def test_element_setitem_fancy():
    """Test assignment of pspace parts with lists."""
    pspace = odl.ProductSpace(odl.rn(1), odl.rn(2), odl.rn(3))

    x0 = pspace[0].element([0])
    x1 = pspace[1].element([1, 2])
    x2 = pspace[2].element([3, 4, 5])
    x = pspace.element([x0, x1, x2])
    old_x0 = x[0]
    old_x2 = x[2]

    # Check that values are set, but identity is preserved
    new_x0 = pspace[0].element([6])
    new_x2 = pspace[2].element([7, 8, 9])
    x[[0, 2]] = pspace[[0, 2]].element([new_x0, new_x2])
    assert x[[0, 2]][0] is old_x0
    assert x[[0, 2]][0] == new_x0
    assert x[[0, 2]][1] is old_x2
    assert x[[0, 2]][1] == new_x2

    # Set values with sequences of scalars
    x[[0, 2]] = [-1, -2]
    assert x[[0, 2]][0] is old_x0
    assert all_equal(x[[0, 2]][0], [-1])
    assert x[[0, 2]][1] is old_x2
    assert all_equal(x[[0, 2]][1], [-2, -2, -2])
Exemplo n.º 8
0
def test_element_getitem_multi():
    """Test element access with multiple indices."""
    pspace = odl.ProductSpace(odl.rn(1), odl.rn(2))
    pspace2 = odl.ProductSpace(pspace, 3)
    pspace3 = odl.ProductSpace(pspace2, 2)
    z = pspace3.element(
        [[[[1],
           [2, 3]],
          [[4],
           [5, 6]],
          [[7],
           [8, 9]]],
         [[[10],
           [12, 13]],
          [[14],
           [15, 16]],
          [[17],
           [18, 19]]]
         ]
    )

    assert pspace3.shape == (2, 3, 2)
    assert z[0, 0, 0, 0] == 1
    assert all_equal(z[0, 0, 1], [2, 3])
    assert all_equal(z[0, 0], [[1], [2, 3]])
    assert all_equal(z[0, 1:], [[[4],
                                 [5, 6]],
                                [[7],
                                 [8, 9]]])
    assert all_equal(z[0, 1:, 1], [[5, 6],
                                   [8, 9]])
    assert all_equal(z[0, 1:, :, 0], [[[4],
                                       [5]],
                                      [[7],
                                       [8]]])
Exemplo n.º 9
0
def test_nearest_interpolation_1d_variants():
    intv = odl.Interval(0, 1)
    part = odl.uniform_partition_fromintv(intv, 5, nodes_on_bdry=False)
    # Coordinate vectors are:
    # [0.1, 0.3, 0.5, 0.7, 0.9]

    space = odl.FunctionSpace(intv)
    dspace = odl.Rn(part.size)

    # 'left' variant
    interp_op = NearestInterpolation(space, part, dspace, variant='left')
    function = interp_op([0, 1, 2, 3, 4])

    # Testing two midpoints and the extreme values
    pts = np.array([0.4, 0.8, 0.0, 1.0])
    true_arr = [1, 3, 0, 4]
    assert all_equal(function(pts), true_arr)

    # 'right' variant
    interp_op = NearestInterpolation(space, part, dspace, variant='right')
    function = interp_op([0, 1, 2, 3, 4])

    # Testing two midpoints and the extreme values
    pts = np.array([0.4, 0.8, 0.0, 1.0])
    true_arr = [2, 4, 0, 4]
    assert all_equal(function(pts), true_arr)
Exemplo n.º 10
0
def test_vectorize_callable_class():

    # Test vectorization in 1d without data type --> lazy vectorization
    arr = [[-2, -1, 0, 1, 2]]
    mg = [[-3, -2, -1, 0, 1]]
    val_1 = -1
    val_2 = 2

    # Class with __call__ method
    class CallableClass(object):
        def __call__(self, x):
            return 0 if x < 0 else 1

    vectorized_call = vectorize(CallableClass())

    true_result_arr = [0, 0, 1, 1, 1]
    true_result_mg = [0, 0, 0, 1, 1]

    # Out-of-place
    out = vectorized_call(arr)
    assert isinstance(out, np.ndarray)
    assert is_int_dtype(out.dtype)
    assert out.shape == (5, )
    assert all_equal(out, true_result_arr)

    out = vectorized_call(mg)
    assert isinstance(out, np.ndarray)
    assert out.shape == (5, )
    assert is_int_dtype(out.dtype)
    assert all_equal(out, true_result_mg)

    assert vectorized_call(val_1) == 0
    assert vectorized_call(val_2) == 1
Exemplo n.º 11
0
def test_nearest_interpolation_2d_float():
    rect = odl.Rectangle([0, 0], [1, 1])
    grid = odl.uniform_sampling(rect, [4, 2], as_midp=True)
    # Coordinate vectors are:
    # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75]

    space = odl.FunctionSpace(rect)
    dspace = odl.Rn(grid.ntotal)
    interp_op = NearestInterpolation(space, grid, dspace)
    function = interp_op([0, 1, 2, 3, 4, 5, 6, 7])

    # Evaluate at single point
    val = function([0.3, 0.6])  # closest to index (1, 1) -> 3
    assert val == 3.0
    # Input array, with and without output array
    pts = np.array([[0.3, 0.6],
                    [1.0, 1.0]])
    true_arr = [3, 7]
    assert all_equal(function(pts.T), true_arr)
    out = np.empty(2, dtype='float64')
    function(pts.T, out=out)
    assert all_equal(out, true_arr)
    # Input meshgrid, with and without output array
    mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0])
    # Indices: (1, 3) x (0, 1)
    true_mg = [[2, 3],
               [6, 7]]
    assert all_equal(function(mg), true_mg)
    out = np.empty((2, 2), dtype='float64')
    function(mg, out=out)
    assert all_equal(out, true_mg)
Exemplo n.º 12
0
def test_asarray_2d(odl_elem_order):
    """Test the asarray method."""
    order = odl_elem_order
    discr = odl.uniform_discr([0, 0], [1, 1], [2, 2])
    elem = discr.element([[1, 2], [3, 4]], order=order)

    arr = elem.asarray()
    assert all_equal(arr, [[1, 2], [3, 4]])
    if order is None:
        assert arr.flags[discr.default_order + '_CONTIGUOUS']
    else:
        assert arr.flags[order + '_CONTIGUOUS']

    # test out parameter
    out_c = np.empty([2, 2], order='C')
    result_c = elem.asarray(out=out_c)
    assert result_c is out_c
    assert all_equal(out_c, [[1, 2], [3, 4]])
    out_f = np.empty([2, 2], order='F')
    result_f = elem.asarray(out=out_f)
    assert result_f is out_f
    assert all_equal(out_f, [[1, 2], [3, 4]])

    # Try wrong shape
    out_wrong_shape = np.empty([2, 3])
    with pytest.raises(ValueError):
        elem.asarray(out=out_wrong_shape)
Exemplo n.º 13
0
def test_discrete_gradient_cuda():
    """Discretized spatial gradient operator using CUDA."""

    # Check result of operator with explicit summation
    # phantom data
    data = np.array([[0., 1., 2., 3., 4.],
                     [1., 2., 3., 4., 5.],
                     [2., 3., 4., 5., 6.]])

    # DiscreteLp Vector
    discr_space = uniform_discr([0, 0], [6, 2.5], data.shape, impl='cuda')
    dom_vec = discr_space.element(data)

    # computation of gradient components with helper function
    dx0, dx1 = discr_space.grid.stride
    df0 = finite_diff(data, axis=0, dx=dx0, zero_padding=True, edge_order=2)
    df1 = finite_diff(data, axis=1, dx=dx1, zero_padding=True, edge_order=2)

    # gradient
    grad = DiscreteGradient(discr_space)
    grad_vec = grad(dom_vec)
    assert len(grad_vec) == data.ndim
    assert all_equal(grad_vec[0].asarray(), df0)
    assert all_equal(grad_vec[1].asarray(), df1)

    # adjoint operator
    ran_vec = grad.range.element([data, data ** 2])
    adj_vec = grad.adjoint(ran_vec)
    lhs = ran_vec.inner(grad_vec)
    rhs = dom_vec.inner(adj_vec)
    assert lhs != 0
    assert rhs != 0
    assert lhs == rhs
Exemplo n.º 14
0
def test_cell_sizes():
    vec1 = np.array([1, 3])
    vec2 = np.array([-1, 0, 1])
    vec3 = np.array([2, 4, 5, 10])
    scalar = 0.5

    cs1, cs2, cs3 = [np.diff(vec) for vec in (vec1, vec2, vec3)]
    csscal = 0

    # Grid as set
    grid = TensorGrid(vec1, vec2, vec3, as_midp=False)
    assert all_equal(grid.cell_sizes(), (cs1, cs2, cs3))

    grid = TensorGrid(vec1, scalar, vec3, as_midp=False)
    assert all_equal(grid.cell_sizes(), (cs1, csscal, cs3))

    # Grid as tesselation
    cs1 = (2, 2)
    cs2 = (1, 1, 1)
    cs3 = (2, 1.5, 3, 5)

    grid = TensorGrid(vec1, vec2, vec3, as_midp=True)
    assert all_equal(grid.cell_sizes(), (cs1, cs2, cs3))

    grid = TensorGrid(vec1, scalar, vec3, as_midp=True)
    assert all_equal(grid.cell_sizes(), (cs1, csscal, cs3))
Exemplo n.º 15
0
def test_element_from_array_2d():
    # assert orderings work properly with 2d
    discr = odl.uniform_discr([0, 0], [1, 1], [2, 2], impl='numpy', order='C')
    vec = discr.element([[1, 2],
                         [3, 4]])

    assert isinstance(vec, odl.DiscreteLpVector)
    assert isinstance(vec.ntuple, odl.FnVector)

    # Check ordering
    assert all_equal(vec.ntuple, [1, 2, 3, 4])

    # Linear creation works as well
    linear_vec = discr.element([1, 2, 3, 4])
    assert all_equal(vec.ntuple, [1, 2, 3, 4])

    # Fortran order
    discr = odl.uniform_discr([0, 0], [1, 1], (2, 2), impl='numpy', order='F')
    vec = discr.element([[1, 2],
                         [3, 4]])

    # Check ordering
    assert all_equal(vec.ntuple, [1, 3, 2, 4])

    # Linear creation works aswell
    linear_vec = discr.element([1, 2, 3, 4])
    assert all_equal(linear_vec.ntuple, [1, 2, 3, 4])
Exemplo n.º 16
0
def test_nearest_interpolation_1d_variants():
    """Test nearest neighbor interpolation variants in 1d."""
    intv = odl.IntervalProd(0, 1)
    part = odl.uniform_partition_fromintv(intv, 5, nodes_on_bdry=False)
    # Coordinate vectors are:
    # [0.1, 0.3, 0.5, 0.7, 0.9]

    fspace = odl.FunctionSpace(intv)
    tspace = odl.rn(part.shape)

    # 'left' variant
    interp_op = NearestInterpolation(fspace, part, tspace, variant='left')
    assert repr(interp_op) != ''
    function = interp_op([0, 1, 2, 3, 4])

    # Testing two midpoints and the extreme values
    pts = np.array([0.4, 0.8, 0.0, 1.0])
    true_arr = [1, 3, 0, 4]
    assert all_equal(function(pts), true_arr)

    # 'right' variant
    interp_op = NearestInterpolation(fspace, part, tspace, variant='right')
    assert repr(interp_op) != ''
    function = interp_op([0, 1, 2, 3, 4])

    # Testing two midpoints and the extreme values
    pts = np.array([0.4, 0.8, 0.0, 1.0])
    true_arr = [2, 4, 0, 4]
    assert all_equal(function(pts), true_arr)
Exemplo n.º 17
0
def test_nearest_interpolation_1d_complex():
    intv = odl.Interval(0, 1)
    grid = odl.uniform_sampling(intv, 5, as_midp=True)
    # Coordinate vectors are:
    # [0.1, 0.3, 0.5, 0.7, 0.9]

    space = odl.FunctionSpace(intv, field=odl.ComplexNumbers())
    dspace = odl.Cn(grid.ntotal)
    interp_op = NearestInterpolation(space, grid, dspace)
    function = interp_op([0 + 1j, 1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j])

    # Evaluate at single point
    val = function(0.35)  # closest to index 1 -> 1 + 2j
    assert val == 1.0 + 2.0j
    # Input array, with and without output array
    pts = np.array([0.4, 0.0, 0.65, 0.95])
    true_arr = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j]
    assert all_equal(function(pts), true_arr)
    # Should also work with a (1, N) array
    pts = pts[None, :]
    assert all_equal(function(pts), true_arr)
    out = np.empty(4, dtype='complex128')
    function(pts, out=out)
    assert all_equal(out, true_arr)
    # Input meshgrid, with and without output array
    # Same as array for 1d
    mg = sparse_meshgrid([0.4, 0.0, 0.65, 0.95])
    true_mg = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j]
    assert all_equal(function(mg), true_mg)
    function(mg, out=out)
    assert all_equal(out, true_mg)
Exemplo n.º 18
0
def test_nearest_interpolation_1d_variants():
    intv = odl.IntervalProd(0, 1)
    part = odl.uniform_partition_fromintv(intv, 5, nodes_on_bdry=False)
    # Coordinate vectors are:
    # [0.1, 0.3, 0.5, 0.7, 0.9]

    space = odl.FunctionSpace(intv)
    dspace = odl.rn(part.size)

    # 'left' variant
    interp_op = NearestInterpolation(space, part, dspace, variant='left')
    function = interp_op([0, 1, 2, 3, 4])

    # Testing two midpoints and the extreme values
    pts = np.array([0.4, 0.8, 0.0, 1.0])
    true_arr = [1, 3, 0, 4]
    assert all_equal(function(pts), true_arr)

    # 'right' variant
    interp_op = NearestInterpolation(space, part, dspace, variant='right')
    function = interp_op([0, 1, 2, 3, 4])

    # Testing two midpoints and the extreme values
    pts = np.array([0.4, 0.8, 0.0, 1.0])
    true_arr = [2, 4, 0, 4]
    assert all_equal(function(pts), true_arr)
Exemplo n.º 19
0
def test_nearest_interpolation_2d_string():
    """Test nearest neighbor interpolation in 2d with string values."""
    rect = odl.IntervalProd([0, 0], [1, 1])
    part = odl.uniform_partition_fromintv(rect, [4, 2], nodes_on_bdry=False)
    # Coordinate vectors are:
    # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75]

    fspace = odl.FunctionSpace(rect, out_dtype='U1')
    tspace = odl.tensor_space(part.shape, dtype='U1')
    interp_op = NearestInterpolation(fspace, part, tspace)
    values = np.array([c for c in 'mystring']).reshape(tspace.shape)
    function = interp_op(values)

    # Evaluate at single point
    val = function([0.3, 0.6])  # closest to index (1, 1) -> 3
    assert val == 't'
    # Input array, with and without output array
    pts = np.array([[0.3, 0.6], [1.0, 1.0]])
    true_arr = ['t', 'g']
    assert all_equal(function(pts.T), true_arr)
    out = np.empty(2, dtype='U1')
    function(pts.T, out=out)
    assert all_equal(out, true_arr)
    # Input meshgrid, with and without output array
    mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0])
    # Indices: (1, 3) x (0, 1)
    true_mg = [['s', 't'], ['n', 'g']]
    assert all_equal(function(mg), true_mg)
    out = np.empty((2, 2), dtype='U1')
    function(mg, out=out)
    assert all_equal(out, true_mg)

    assert repr(interp_op) != ''
Exemplo n.º 20
0
def test_sparse_meshgrid():

    # One array only
    x = np.zeros(2)
    true_mg = (x,)
    assert all_equal(sparse_meshgrid(x), true_mg)

    x = np.zeros((2, 2))
    true_mg = (x,)
    assert all_equal(sparse_meshgrid(x), true_mg)

    # Two arrays, 'C' ordering
    x, y = np.zeros(2), np.zeros(3)
    true_mg = (x[:, None], y[None, :])
    mg = sparse_meshgrid(x, y, order='C')
    assert all_equal(mg, true_mg)
    assert all(vec.flags.c_contiguous for vec in mg)

    # Two arrays, 'F' ordering
    x, y = np.zeros(2), np.zeros(3)
    true_mg = (y[None, :], x[:, None])
    mg = sparse_meshgrid(x, y, order='F')
    assert all_equal(mg, true_mg)
    assert all(vec.flags.f_contiguous for vec in mg)

    # Array-like input
    x, y = [1, 2, 3], [4, 5, 6]
    true_mg = (np.array(x)[:, None], np.array(y)[None, :])
    mg = sparse_meshgrid(x, y, order='C')
    assert all_equal(mg, true_mg)
    assert all(vec.flags.c_contiguous for vec in mg)
Exemplo n.º 21
0
def test_nearest_interpolation_1d_complex(odl_tspace_impl):
    """Test nearest neighbor interpolation in 1d with complex values."""
    impl = odl_tspace_impl  # TODO: not used!
    intv = odl.IntervalProd(0, 1)
    part = odl.uniform_partition_fromintv(intv, 5, nodes_on_bdry=False)
    # Coordinate vectors are:
    # [0.1, 0.3, 0.5, 0.7, 0.9]

    fspace = odl.FunctionSpace(intv, out_dtype=complex)
    tspace = odl.cn(part.shape)
    interp_op = NearestInterpolation(fspace, part, tspace)
    function = interp_op([0 + 1j, 1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j])

    # Evaluate at single point
    val = function(0.35)  # closest to index 1 -> 1 + 2j
    assert val == 1.0 + 2.0j
    # Input array, with and without output array
    pts = np.array([0.4, 0.0, 0.65, 0.95])
    true_arr = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j]
    assert all_equal(function(pts), true_arr)
    # Should also work with a (1, N) array
    pts = pts[None, :]
    assert all_equal(function(pts), true_arr)
    out = np.empty(4, dtype='complex128')
    function(pts, out=out)
    assert all_equal(out, true_arr)
    # Input meshgrid, with and without output array
    # Same as array for 1d
    mg = sparse_meshgrid([0.4, 0.0, 0.65, 0.95])
    true_mg = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j]
    assert all_equal(function(mg), true_mg)
    function(mg, out=out)
    assert all_equal(out, true_mg)

    assert repr(interp_op) != ''
Exemplo n.º 22
0
def test_element_from_array_2d():
    # assert orderings work properly with 2d
    square_space = odl.FunctionSpace(odl.Rectangle([0, 0], [1, 1]))
    discr = odl.uniform_discr(square_space, (2, 2), impl='numpy', order='C')
    vec = discr.element([[1, 2],
                         [3, 4]])

    assert isinstance(vec, discr.Vector)
    assert isinstance(vec.ntuple, odl.Rn.Vector)

    # Check ordering
    assert all_equal(vec.ntuple, [1, 2, 3, 4])

    # Linear creation works as well
    linear_vec = discr.element([1, 2, 3, 4])
    assert all_equal(vec.ntuple, [1, 2, 3, 4])

    # Fortran order
    discr = odl.uniform_discr(square_space, (2, 2), impl='numpy', order='F')
    vec = discr.element([[1, 2],
                         [3, 4]])

    # Check ordering
    assert all_equal(vec.ntuple, [1, 3, 2, 4])

    # Linear creation works aswell
    linear_vec = discr.element([1, 2, 3, 4])
    assert all_equal(linear_vec.ntuple, [1, 2, 3, 4])
Exemplo n.º 23
0
def test_vectorize_2d_lazy():

    # Test vectorization in 1d without data type --> lazy vectorization
    arr = np.empty((2, 5), dtype='int')
    arr[0] = ([-3, -2, -1, 0, 1])
    arr[1] = ([-1, 0, 1, 2, 3])
    mg = sparse_meshgrid([-3, -2, -1, 0, 1], [-1, 0, 1, 2, 3])
    val_1 = (-1, 1)
    val_2 = (2, 1)

    @vectorize
    def simple_func(x):
        return 0 if x[0] < 0 and x[1] > 0 else 1

    true_result_arr = [1, 1, 0, 1, 1]

    true_result_mg = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0],
                      [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]

    # Out-of-place
    out = simple_func(arr)
    assert isinstance(out, np.ndarray)
    assert is_int_dtype(out.dtype)
    assert out.shape == (5, )
    assert all_equal(out, true_result_arr)

    out = simple_func(mg)
    assert isinstance(out, np.ndarray)
    assert is_int_dtype(out.dtype)
    assert out.shape == (5, 5)
    assert all_equal(out, true_result_mg)

    assert simple_func(val_1) == 0
    assert simple_func(val_2) == 1
Exemplo n.º 24
0
def test_nearest_interpolation_2d_string():
    rect = odl.Rectangle([0, 0], [1, 1])
    grid = odl.uniform_sampling(rect, [4, 2], as_midp=True)
    # Coordinate vectors are:
    # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75]

    space = odl.FunctionSet(rect, odl.Strings(1))
    dspace = odl.Ntuples(grid.ntotal, dtype='U1')
    interp_op = NearestInterpolation(space, grid, dspace)
    values = np.array([c for c in 'mystring'])
    function = interp_op(values)

    # Evaluate at single point
    val = function([0.3, 0.6])  # closest to index (1, 1) -> 3
    assert val == 't'
    # Input array, with and without output array
    pts = np.array([[0.3, 0.6],
                    [1.0, 1.0]])
    true_arr = ['t', 'g']
    assert all_equal(function(pts.T), true_arr)
    out = np.empty(2, dtype='U1')
    function(pts.T, out=out)
    assert all_equal(out, true_arr)
    # Input meshgrid, with and without output array
    mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0])
    # Indices: (1, 3) x (0, 1)
    true_mg = [['s', 't'],
               ['n', 'g']]
    assert all_equal(function(mg), true_mg)
    out = np.empty((2, 2), dtype='U1')
    function(mg, out=out)
    assert all_equal(out, true_mg)
Exemplo n.º 25
0
def test_fspace_lincomb_vec_tens(a, b, out_shape):
    """Check linear combination in function spaces."""
    if out_shape == ():
        return

    intv = odl.IntervalProd([0, 0], [1, 1])
    fspace = FunctionSpace(intv, out_dtype=(float, out_shape))
    points = _points(fspace.domain, 4)

    ndim = len(out_shape)
    if ndim == 1:
        f_elem1 = fspace.element(func_vec_nd_oop)
        f_elem2 = fspace.element(func_vec_nd_other)
        true_result = (a * func_vec_nd_ref(points) +
                       b * func_vec_nd_other(points))
    elif ndim == 2:
        f_elem1 = fspace.element(func_tens_oop)
        f_elem2 = fspace.element(func_tens_other)
        true_result = a * func_tens_ref(points) + b * func_tens_other(points)
    else:
        assert False

    out_func = fspace.element()
    fspace.lincomb(a, f_elem1, b, f_elem2, out_func)
    assert all_equal(out_func(points), true_result)
    out_arr = np.empty(out_shape + (4, ))
    out_func(points, out=out_arr)
    assert all_equal(out_arr, true_result)
Exemplo n.º 26
0
def test_fspace_one(out_shape):
    """Check one element."""

    fspace = FunctionSpace(odl.IntervalProd(0, 1),
                           out_dtype=(float, out_shape))

    points = _points(fspace.domain, 4)
    mesh_shape = (5, )
    mesh = _meshgrid(fspace.domain, mesh_shape)
    point = 0.5
    values_points_shape = out_shape + (4, )
    values_point_shape = out_shape
    values_mesh_shape = out_shape + mesh_shape

    f_one = fspace.one()

    assert all_equal(f_one(points), np.ones(values_points_shape))
    if not out_shape:
        assert f_one(point) == 1.0
    else:
        assert all_equal(f_one(point), np.ones(values_point_shape))
    assert all_equal(f_one(mesh), np.ones(values_mesh_shape))

    out_points = np.empty(values_points_shape)
    out_mesh = np.empty(values_mesh_shape)

    f_one(points, out=out_points)
    f_one(mesh, out=out_mesh)

    assert all_equal(out_points, np.ones(values_points_shape))
    assert all_equal(out_mesh, np.ones(values_mesh_shape))
Exemplo n.º 27
0
def test_nearest_interpolation_1d_complex(fn_impl):
    intv = odl.IntervalProd(0, 1)
    part = odl.uniform_partition_fromintv(intv, 5, nodes_on_bdry=False)
    # Coordinate vectors are:
    # [0.1, 0.3, 0.5, 0.7, 0.9]

    space = odl.FunctionSpace(intv, field=odl.ComplexNumbers())
    dspace = odl.cn(part.size)
    interp_op = NearestInterpolation(space, part, dspace)
    function = interp_op([0 + 1j, 1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j])

    # Evaluate at single point
    val = function(0.35)  # closest to index 1 -> 1 + 2j
    assert val == 1.0 + 2.0j
    # Input array, with and without output array
    pts = np.array([0.4, 0.0, 0.65, 0.95])
    true_arr = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j]
    assert all_equal(function(pts), true_arr)
    # Should also work with a (1, N) array
    pts = pts[None, :]
    assert all_equal(function(pts), true_arr)
    out = np.empty(4, dtype='complex128')
    function(pts, out=out)
    assert all_equal(out, true_arr)
    # Input meshgrid, with and without output array
    # Same as array for 1d
    mg = sparse_meshgrid([0.4, 0.0, 0.65, 0.95])
    true_mg = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j]
    assert all_equal(function(mg), true_mg)
    function(mg, out=out)
    assert all_equal(out, true_mg)
Exemplo n.º 28
0
def test_vectorize_callable_class():

    # Test vectorization in 1d without data type --> lazy vectorization
    arr = [[-2, -1, 0, 1, 2]]
    mg = [[-3, -2, -1, 0, 1]]
    val_1 = -1
    val_2 = 2

    # Class with __call__ method
    class CallableClass(object):
        def __call__(self, x):
            return 0 if x < 0 else 1

    vectorized_call = vectorize(CallableClass())

    true_result_arr = [0, 0, 1, 1, 1]
    true_result_mg = [0, 0, 0, 1, 1]

    # Out-of-place
    out = vectorized_call(arr)
    assert isinstance(out, np.ndarray)
    assert is_int_dtype(out.dtype)
    assert out.shape == (5,)
    assert all_equal(out, true_result_arr)

    out = vectorized_call(mg)
    assert isinstance(out, np.ndarray)
    assert out.shape == (5,)
    assert is_int_dtype(out.dtype)
    assert all_equal(out, true_result_mg)

    assert vectorized_call(val_1) == 0
    assert vectorized_call(val_2) == 1
Exemplo n.º 29
0
def test_gradient_cuda():
    """Discretized spatial gradient operator using CUDA."""

    # DiscreteLp Vector
    discr_space = odl.uniform_discr([0, 0], [6, 2.5], DATA_2D.shape,
                                    impl='cuda')
    dom_vec = discr_space.element(DATA_2D)

    # computation of gradient components with helper function
    dx0, dx1 = discr_space.cell_sides
    diff_0 = finite_diff(DATA_2D, axis=0, dx=dx0, padding_method='constant')
    diff_1 = finite_diff(DATA_2D, axis=1, dx=dx1, padding_method='constant')

    # gradient
    grad = Gradient(discr_space)
    grad_vec = grad(dom_vec)
    assert len(grad_vec) == DATA_2D.ndim
    assert all_equal(grad_vec[0].asarray(), diff_0)
    assert all_equal(grad_vec[1].asarray(), diff_1)

    # adjoint operator
    ran_vec = grad.range.element([DATA_2D, DATA_2D ** 2])
    adj_vec = grad.adjoint(ran_vec)
    lhs = ran_vec.inner(grad_vec)
    rhs = dom_vec.inner(adj_vec)
    assert lhs != 0
    assert rhs != 0
    assert lhs == rhs
Exemplo n.º 30
0
def test_vectorize_1d_lazy():

    # Test vectorization in 1d without data type --> lazy vectorization
    arr = (np.arange(5) - 2)[None, :]
    mg = sparse_meshgrid(np.arange(5) - 3)
    val_1 = -1
    val_2 = 2

    @vectorize
    def simple_func(x):
        return 0 if x < 0 else 1

    true_result_arr = [0, 0, 1, 1, 1]
    true_result_mg = [0, 0, 0, 1, 1]

    # Out-of-place
    out = simple_func(arr)
    assert isinstance(out, np.ndarray)
    assert is_int_dtype(out.dtype)
    assert out.shape == (5, )
    assert all_equal(out, true_result_arr)

    out = simple_func(mg)
    assert isinstance(out, np.ndarray)
    assert out.shape == (5, )
    assert is_int_dtype(out.dtype)
    assert all_equal(out, true_result_mg)

    assert simple_func(val_1) == 0
    assert simple_func(val_2) == 1
Exemplo n.º 31
0
def test_element_setitem_fancy():
    """Test assignment of pspace parts with lists."""
    pspace = odl.ProductSpace(odl.rn(1), odl.rn(2), odl.rn(3))

    x0 = pspace[0].element([0])
    x1 = pspace[1].element([1, 2])
    x2 = pspace[2].element([3, 4, 5])
    x = pspace.element([x0, x1, x2])
    old_x0 = x[0]
    old_x2 = x[2]

    # Check that values are set, but identity is preserved
    new_x0 = pspace[0].element([6])
    new_x2 = pspace[2].element([7, 8, 9])
    x[[0, 2]] = pspace[[0, 2]].element([new_x0, new_x2])
    assert x[[0, 2]][0] is old_x0
    assert x[[0, 2]][0] == new_x0
    assert x[[0, 2]][1] is old_x2
    assert x[[0, 2]][1] == new_x2

    # Set values with sequences of scalars
    x[[0, 2]] = [-1, -2]
    assert x[[0, 2]][0] is old_x0
    assert all_equal(x[[0, 2]][0], [-1])
    assert x[[0, 2]][1] is old_x2
    assert all_equal(x[[0, 2]][1], [-2, -2, -2])
Exemplo n.º 32
0
def test_uniform_discr_fromdiscr_two_attrs():
    # Change 2 attributes -> resize and translate

    discr = odl.uniform_discr([0, -1], [1, 1], [10, 5])
    # csides = [0.1, 0.4]

    new_min_pt = [-2, 1]
    new_max_pt = [4, 2]
    true_new_csides = [0.6, 0.2]
    new_discr = odl.uniform_discr_fromdiscr(discr,
                                            min_pt=new_min_pt,
                                            max_pt=new_max_pt)
    assert all_almost_equal(new_discr.min_pt, new_min_pt)
    assert all_almost_equal(new_discr.max_pt, new_max_pt)
    assert all_equal(new_discr.shape, discr.shape)
    assert all_almost_equal(new_discr.cell_sides, true_new_csides)

    new_min_pt = [-2, 1]
    new_shape = (5, 20)
    true_new_max_pt = [-1.5, 9]
    new_discr = odl.uniform_discr_fromdiscr(discr,
                                            min_pt=new_min_pt,
                                            shape=new_shape)
    assert all_almost_equal(new_discr.min_pt, new_min_pt)
    assert all_almost_equal(new_discr.max_pt, true_new_max_pt)
    assert all_equal(new_discr.shape, new_shape)
    assert all_almost_equal(new_discr.cell_sides, discr.cell_sides)

    new_min_pt = [-2, 1]
    new_csides = [0.6, 0.2]
    true_new_max_pt = [4, 2]
    new_discr = odl.uniform_discr_fromdiscr(discr,
                                            min_pt=new_min_pt,
                                            cell_sides=new_csides)
    assert all_almost_equal(new_discr.min_pt, new_min_pt)
    assert all_almost_equal(new_discr.max_pt, true_new_max_pt)
    assert all_equal(new_discr.shape, discr.shape)
    assert all_almost_equal(new_discr.cell_sides, new_csides)

    new_max_pt = [4, 2]
    new_shape = (5, 20)
    true_new_min_pt = [3.5, -6]
    new_discr = odl.uniform_discr_fromdiscr(discr,
                                            max_pt=new_max_pt,
                                            shape=new_shape)
    assert all_almost_equal(new_discr.min_pt, true_new_min_pt)
    assert all_almost_equal(new_discr.max_pt, new_max_pt)
    assert all_equal(new_discr.shape, new_shape)
    assert all_almost_equal(new_discr.cell_sides, discr.cell_sides)

    new_max_pt = [4, 2]
    new_csides = [0.6, 0.2]
    true_new_min_pt = [-2, 1]
    new_discr = odl.uniform_discr_fromdiscr(discr,
                                            max_pt=new_max_pt,
                                            cell_sides=new_csides)
    assert all_almost_equal(new_discr.min_pt, true_new_min_pt)
    assert all_almost_equal(new_discr.max_pt, new_max_pt)
    assert all_equal(new_discr.shape, discr.shape)
    assert all_almost_equal(new_discr.cell_sides, new_csides)
Exemplo n.º 33
0
def test_nearest_interpolation_1d_variants():
    intv = odl.Interval(0, 1)
    grid = odl.uniform_sampling(intv, 5, as_midp=True)
    # Coordinate vectors are:
    # [0.1, 0.3, 0.5, 0.7, 0.9]

    space = odl.FunctionSpace(intv)
    dspace = odl.Rn(grid.ntotal)

    # 'left' variant
    interp_op = NearestInterpolation(space, grid, dspace, variant='left')
    function = interp_op([0, 1, 2, 3, 4])

    # Testing two midpoints and the extreme values
    pts = np.array([0.4, 0.8, 0.0, 1.0])
    true_arr = [1, 3, 0, 4]
    assert all_equal(function(pts), true_arr)

    # 'right' variant
    interp_op = NearestInterpolation(space, grid, dspace, variant='right')
    function = interp_op([0, 1, 2, 3, 4])

    # Testing two midpoints and the extreme values
    pts = np.array([0.4, 0.8, 0.0, 1.0])
    true_arr = [2, 4, 0, 4]
    assert all_equal(function(pts), true_arr)
Exemplo n.º 34
0
def test_vectorize_1d_lazy():

    # Test vectorization in 1d without data type --> lazy vectorization
    arr = (np.arange(5) - 2)[None, :]
    mg = sparse_meshgrid(np.arange(5) - 3)
    val_1 = -1
    val_2 = 2

    @vectorize
    def simple_func(x):
        return 0 if x < 0 else 1

    true_result_arr = [0, 0, 1, 1, 1]
    true_result_mg = [0, 0, 0, 1, 1]

    # Out-of-place
    out = simple_func(arr)
    assert isinstance(out, np.ndarray)
    assert is_int_dtype(out.dtype)
    assert out.shape == (5,)
    assert all_equal(out, true_result_arr)

    out = simple_func(mg)
    assert isinstance(out, np.ndarray)
    assert out.shape == (5,)
    assert is_int_dtype(out.dtype)
    assert all_equal(out, true_result_mg)

    assert simple_func(val_1) == 0
    assert simple_func(val_2) == 1
Exemplo n.º 35
0
def test_vector_numpy():

    # Rn
    inp = [1.0, 2.0, 3.0]

    x = vector(inp)
    assert isinstance(x, odl.NumpyFnVector)
    assert x.dtype == np.dtype('float64')
    assert all_equal(x, inp)

    x = vector([1.0, 2.0, float('inf')])
    assert x.dtype == np.dtype('float64')
    assert isinstance(x, odl.NumpyFnVector)

    x = vector([1.0, 2.0, float('nan')])
    assert x.dtype == np.dtype('float64')
    assert isinstance(x, odl.NumpyFnVector)

    x = vector([1, 2, 3], dtype='float32')
    assert x.dtype == np.dtype('float32')
    assert isinstance(x, odl.NumpyFnVector)

    # Cn
    inp = [1 + 1j, 2, 3 - 2j]

    x = vector(inp)
    assert isinstance(x, odl.NumpyFnVector)
    assert x.dtype == np.dtype('complex128')
    assert all_equal(x, inp)

    x = vector([1, 2, 3], dtype='complex64')
    assert isinstance(x, odl.NumpyFnVector)

    # Fn
    inp = [1, 2, 3]

    x = vector(inp)
    assert isinstance(x, odl.NumpyNtuplesVector)
    assert x.dtype == np.dtype('int')
    assert all_equal(x, inp)

    # Ntuples
    inp = ['a', 'b', 'c']
    x = vector(inp)
    assert isinstance(x, odl.NumpyNtuplesVector)
    assert np.issubdtype(x.dtype, basestring)
    assert all_equal(x, inp)

    x = vector([1, 2, 'inf'])  # Becomes string type
    assert isinstance(x, odl.NumpyNtuplesVector)
    assert np.issubdtype(x.dtype, basestring)
    assert all_equal(x, ['1', '2', 'inf'])

    # Input not one-dimensional
    x = vector(5.0)  # OK
    assert x.shape == (1,)

    with pytest.raises(ValueError):
        vector([[1, 0], [0, 1]])
Exemplo n.º 36
0
def test_fspace_vector_arithmetic(variant, op):
    if variant == 'sv' and '=' in op:  # makes no sense, quit
        return

    # Setup
    rect, points, mg = _standard_setup_2d()
    point = points.T[0]

    fspace = FunctionSpace(rect)
    a = -1.5
    b = 2.0
    array_out = np.empty((5, ), dtype=float)
    mg_out = np.empty((2, 3), dtype=float)

    # Initialize a bunch of elements
    f_novec = fspace.element(func_2d_novec, vectorized=False)
    f_vec = fspace.element(func_2d_vec_dual, vectorized=True)
    g_novec = fspace.element(other_func_2d_novec, vectorized=False)
    g_vec = fspace.element(other_func_2d_vec_dual, vectorized=True)

    out_novec = fspace.element(vectorized=False)
    out_vec = fspace.element(vectorized=True)

    if variant[0] == 'v':
        true_l_novec = func_2d_novec(point)
        true_l_arr = func_2d_vec_oop(points)
        true_l_mg = func_2d_vec_oop(mg)

        test_l_novec = f_novec
        test_l_vec = f_vec
    else:  # 's'
        true_l_novec = true_l_arr = true_l_mg = a
        test_l_novec = test_l_vec = a

    if variant[1] == 'v':
        true_r_novec = other_func_2d_novec(point)
        true_r_arr = other_func_2d_vec_oop(points)
        true_r_mg = other_func_2d_vec_oop(mg)

        test_r_novec = g_novec
        test_r_vec = g_vec
    else:  # 's'
        true_r_novec = true_r_arr = true_r_mg = b
        test_r_novec = test_r_vec = b

    true_novec = _op(true_l_novec, op, true_r_novec)
    true_arr = _op(true_l_arr, op, true_r_arr)
    true_mg = _op(true_l_mg, op, true_r_mg)

    out_novec = _op(test_l_novec, op, test_r_novec)
    out_vec = _op(test_l_vec, op, test_r_vec)

    assert almost_equal(out_novec(point), true_novec)
    assert all_equal(out_vec(points), true_arr)
    out_vec(points, out=array_out)
    assert all_equal(array_out, true_arr)
    assert all_equal(out_vec(mg), true_mg)
    out_vec(mg, out=mg_out)
    assert all_equal(mg_out, true_mg)
Exemplo n.º 37
0
def test_fspace_vector_arithmetic(variant, op):
    if variant == 'sv' and '=' in op:  # makes no sense, quit
        return

    # Setup
    rect, points, mg = _standard_setup_2d()
    point = points.T[0]

    fspace = FunctionSpace(rect)
    a = -1.5
    b = 2.0
    array_out = np.empty((5,), dtype=float)
    mg_out = np.empty((2, 3), dtype=float)

    # Initialize a bunch of elements
    f_novec = fspace.element(func_2d_novec, vectorized=False)
    f_vec = fspace.element(func_2d_vec_dual, vectorized=True)
    g_novec = fspace.element(other_func_2d_novec, vectorized=False)
    g_vec = fspace.element(other_func_2d_vec_dual, vectorized=True)

    out_novec = fspace.element(vectorized=False)
    out_vec = fspace.element(vectorized=True)

    if variant[0] == 'v':
        true_l_novec = func_2d_novec(point)
        true_l_arr = func_2d_vec_oop(points)
        true_l_mg = func_2d_vec_oop(mg)

        test_l_novec = f_novec
        test_l_vec = f_vec
    else:  # 's'
        true_l_novec = true_l_arr = true_l_mg = a
        test_l_novec = test_l_vec = a

    if variant[1] == 'v':
        true_r_novec = other_func_2d_novec(point)
        true_r_arr = other_func_2d_vec_oop(points)
        true_r_mg = other_func_2d_vec_oop(mg)

        test_r_novec = g_novec
        test_r_vec = g_vec
    else:  # 's'
        true_r_novec = true_r_arr = true_r_mg = b
        test_r_novec = test_r_vec = b

    true_novec = _op(true_l_novec, op, true_r_novec)
    true_arr = _op(true_l_arr, op, true_r_arr)
    true_mg = _op(true_l_mg, op, true_r_mg)

    out_novec = _op(test_l_novec, op, test_r_novec)
    out_vec = _op(test_l_vec, op, test_r_vec)

    assert almost_equal(out_novec(point), true_novec)
    assert all_equal(out_vec(points), true_arr)
    out_vec(points, out=array_out)
    assert all_equal(array_out, true_arr)
    assert all_equal(out_vec(mg), true_mg)
    out_vec(mg, out=mg_out)
    assert all_equal(mg_out, true_mg)
Exemplo n.º 38
0
def test_vector_numpy():

    # Rn
    inp = [1.0, 2.0, 3.0]

    x = vector(inp)
    assert isinstance(x, odl.NumpyFnVector)
    assert x.dtype == np.dtype('float64')
    assert all_equal(x, inp)

    x = vector([1.0, 2.0, float('inf')])
    assert x.dtype == np.dtype('float64')
    assert isinstance(x, odl.NumpyFnVector)

    x = vector([1.0, 2.0, float('nan')])
    assert x.dtype == np.dtype('float64')
    assert isinstance(x, odl.NumpyFnVector)

    x = vector([1, 2, 3], dtype='float32')
    assert x.dtype == np.dtype('float32')
    assert isinstance(x, odl.NumpyFnVector)

    # Cn
    inp = [1 + 1j, 2, 3 - 2j]

    x = vector(inp)
    assert isinstance(x, odl.NumpyFnVector)
    assert x.dtype == np.dtype('complex128')
    assert all_equal(x, inp)

    x = vector([1, 2, 3], dtype='complex64')
    assert isinstance(x, odl.NumpyFnVector)

    # Fn
    inp = [1, 2, 3]

    x = vector(inp)
    assert isinstance(x, odl.NumpyNtuplesVector)
    assert x.dtype == np.dtype('int')
    assert all_equal(x, inp)

    # Ntuples
    inp = ['a', 'b', 'c']
    x = vector(inp)
    assert isinstance(x, odl.NumpyNtuplesVector)
    assert np.issubdtype(x.dtype, basestring)
    assert all_equal(x, inp)

    x = vector([1, 2, 'inf'])  # Becomes string type
    assert isinstance(x, odl.NumpyNtuplesVector)
    assert np.issubdtype(x.dtype, basestring)
    assert all_equal(x, ['1', '2', 'inf'])

    # Input not one-dimensional
    x = vector(5.0)  # OK
    assert x.shape == (1, )

    with pytest.raises(ValueError):
        vector([[1, 0], [0, 1]])
Exemplo n.º 39
0
def test_parallel_3d_single_axis_geometry():
    """General parallel 3D geometries."""

    # Parameters
    full_angle = np.pi
    apart = odl.uniform_partition(0, full_angle, 10)
    dpart = odl.uniform_partition([0, 0], [1, 1], [10, 10])

    # Bad init
    with pytest.raises(TypeError):
        odl.tomo.Parallel3dAxisGeometry([0, 1], dpart)
    with pytest.raises(TypeError):
        odl.tomo.Parallel3dAxisGeometry(apart, [0, 1])

    # Initialize
    geom = odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=[0, 0, 1])

    with pytest.raises(ValueError):
        geom.rotation_matrix(2 * full_angle)

    # rotation of cartesian basis vectors about each other
    coords = np.eye(3)

    geom = odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=[1, 0, 0])
    rot_mat = geom.rotation_matrix(np.pi / 2)
    assert all_almost_equal(rot_mat.dot(coords),
                            [[1, 0, 0], [0, 0, -1], [0, 1, 0]])

    geom = odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=[0, 1, 0])
    rot_mat = geom.rotation_matrix(np.pi / 2)
    assert all_almost_equal(rot_mat.dot(coords),
                            [[0, 0, 1], [0, 1, 0], [-1, 0, 0]])

    geom = odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=[0, 0, 1])
    rot_mat = geom.rotation_matrix(np.pi / 2)
    assert all_almost_equal(rot_mat.dot(coords),
                            [[0, -1, 0], [1, 0, 0], [0, 0, 1]])

    # rotation axis
    geom = odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=[1, 0, 0])
    assert all_equal(geom.axis, np.array([1, 0, 0]))
    geom = odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=[0, 1, 0])
    assert all_equal(geom.axis, np.array([0, 1, 0]))
    geom = odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=[0, 0, 1])
    assert all_equal(geom.axis, np.array([0, 0, 1]))
    geom = odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=[1, 2, 3])
    assert all_equal(geom.axis,
                     np.array([1, 2, 3]) / np.linalg.norm([1, 2, 3]))

    with pytest.raises(ValueError):
        odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=(1, ))
    with pytest.raises(ValueError):
        odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=(1, 2))
    with pytest.raises(ValueError):
        odl.tomo.Parallel3dAxisGeometry(apart, dpart, axis=(1, 2, 3, 4))

    # check str and repr work without crashing and return something
    assert str(geom)
    assert repr(geom)
def test_vector_numpy():

    # Rn
    inp = [[1.0, 2.0, 3.0],
           [4.0, 5.0, 6.0]]

    x = vector(inp)
    assert isinstance(x, NumpyTensor)
    assert x.dtype == np.dtype('float64')
    assert all_equal(x, inp)

    x = vector([1.0, 2.0, float('inf')])
    assert x.dtype == np.dtype('float64')
    assert isinstance(x, NumpyTensor)

    x = vector([1.0, 2.0, float('nan')])
    assert x.dtype == np.dtype('float64')
    assert isinstance(x, NumpyTensor)

    x = vector([1, 2, 3], dtype='float32')
    assert x.dtype == np.dtype('float32')
    assert isinstance(x, NumpyTensor)

    # Cn
    inp = [[1 + 1j, 2, 3 - 2j],
           [4 + 1j, 5, 6 - 1j]]

    x = vector(inp)
    assert isinstance(x, NumpyTensor)
    assert x.dtype == np.dtype('complex128')
    assert all_equal(x, inp)

    x = vector([1, 2, 3], dtype='complex64')
    assert isinstance(x, NumpyTensor)

    # Generic TensorSpace
    inp = [1, 2, 3]
    x = vector(inp)
    assert isinstance(x, NumpyTensor)
    assert x.dtype == np.dtype('int')
    assert all_equal(x, inp)

    inp = ['a', 'b', 'c']
    x = vector(inp)
    assert isinstance(x, NumpyTensor)
    assert np.issubdtype(x.dtype, np.str_)
    assert all_equal(x, inp)

    x = vector([1, 2, 'inf'])  # Becomes string type
    assert isinstance(x, NumpyTensor)
    assert np.issubdtype(x.dtype, np.str_)
    assert all_equal(x, ['1', '2', 'inf'])

    # Scalar or empty input
    x = vector(5.0)  # becomes 1d, size 1
    assert x.shape == (1,)

    x = vector([])  # becomes 1d, size 0
    assert x.shape == (0,)
Exemplo n.º 41
0
def test_conj(fn):
    xarr, x = noise_elements(fn)
    xconj = x.conj()
    assert all_equal(xconj, xarr.conj())
    y = x.copy()
    xconj = x.conj(out=y)
    assert xconj is y
    assert all_equal(y, xarr.conj())
Exemplo n.º 42
0
def test_conj(fn):
    xarr, x = _vectors(fn)
    xconj = x.conj()
    assert all_equal(xconj, xarr.conj())
    y = x.copy()
    xconj = x.conj(out=y)
    assert xconj is y
    assert all_equal(y, xarr.conj())
Exemplo n.º 43
0
def test_conj(fn):
    xarr, x = example_vectors(fn)
    xconj = x.conj()
    assert all_equal(xconj, xarr.conj())
    y = x.copy()
    xconj = x.conj(out=y)
    assert xconj is y
    assert all_equal(y, xarr.conj())
Exemplo n.º 44
0
def test_per_axis_interpolation():
    """Test different interpolation schemes per axis."""
    rect = odl.IntervalProd([0, 0], [1, 1])
    part = odl.uniform_partition_fromintv(rect, [4, 2], nodes_on_bdry=False)
    # Coordinate vectors are:
    # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75]

    fspace = odl.FunctionSpace(rect)
    tspace = odl.rn(part.shape)
    schemes = ['linear', 'nearest']
    variants = [None, 'right']
    interp_op = PerAxisInterpolation(fspace,
                                     part,
                                     tspace,
                                     schemes=schemes,
                                     nn_variants=variants)
    values = np.arange(1, 9, dtype='float64').reshape(part.shape)
    function = interp_op(values)
    rvals = values.reshape([4, 2])

    # Evaluate at single point
    val = function([0.3, 0.5])
    l1 = (0.3 - 0.125) / (0.375 - 0.125)
    # 0.5 equally far from both neighbors -> 'right' chooses 0.75
    true_val = (1 - l1) * rvals[0, 1] + l1 * rvals[1, 1]
    assert val == pytest.approx(true_val)

    # Input array, with and without output array
    pts = np.array([[0.3, 0.6], [0.1, 0.25], [1.0, 1.0]])
    l1 = (0.3 - 0.125) / (0.375 - 0.125)
    true_val_1 = (1 - l1) * rvals[0, 1] + l1 * rvals[1, 1]
    l1 = (0.125 - 0.1) / (0.375 - 0.125)
    true_val_2 = (1 - l1) * rvals[0, 0]  # only lower left contributes
    l1 = (1.0 - 0.875) / (0.875 - 0.625)
    true_val_3 = (1 - l1) * rvals[3, 1]  # lower left only
    true_arr = [true_val_1, true_val_2, true_val_3]
    assert all_equal(function(pts.T), true_arr)

    out = np.empty(3, dtype='float64')
    function(pts.T, out=out)
    assert all_equal(out, true_arr)

    # Input meshgrid, with and without output array
    mg = sparse_meshgrid([0.3, 1.0], [0.4, 0.85])
    # Indices: (1, 3) x (0, 1)
    lx1 = (0.3 - 0.125) / (0.375 - 0.125)
    lx2 = (1.0 - 0.875) / (0.875 - 0.625)
    true_val_11 = (1 - lx1) * rvals[0, 0] + lx1 * rvals[1, 0]
    true_val_12 = ((1 - lx1) * rvals[0, 1] + lx1 * rvals[1, 1])
    true_val_21 = (1 - lx2) * rvals[3, 0]
    true_val_22 = (1 - lx2) * rvals[3, 1]
    true_mg = [[true_val_11, true_val_12], [true_val_21, true_val_22]]
    assert all_equal(function(mg), true_mg)
    out = np.empty((2, 2), dtype='float64')
    function(mg, out=out)
    assert all_equal(out, true_mg)

    assert repr(interp_op) != ''
Exemplo n.º 45
0
def test_discr_part_deriv():
    """Discretized partial derivative."""

    discr_space = Rn(1)
    with pytest.raises(TypeError):
        DiscretePartDeriv(discr_space)

    # phantom data
    data = np.array([[0., 1., 2., 3., 4.],
                     [1., 2., 3., 4., 5.],
                     [2., 3., 4., 5., 6.]])

    # explicit calculation of finite difference
    # axis: 0
    dfe0 = np.zeros_like(data)
    # interior: second-order accurate differences
    dfe0[1:-1, :] = (data[2:, :] - data[:-2, :]) / 2.0
    # boundary: second-order accurate central differences with zero padding
    dfe0[0, :] = data[1, :] / 2.0
    dfe0[-1, :] = -data[-2, :] / 2.0
    # axis: 1
    dfe1 = np.zeros_like(data)
    # interior: second-order accurate differences
    dfe1[:, 1:-1] = (data[:, 2:] - data[:, :-2]) / 2.0
    # boundary: second-order accurate central differences with zero padding
    dfe1[:, 0] = data[:, 1] / 2.0
    dfe1[:, -1] = -data[:, -2] / 2.0

    # assert `dfe0` and `dfe1` do differ
    assert (dfe0 != dfe1).any()

    # discretized space
    discr_space = uniform_discr([0, 0], [2, 1], data.shape)

    # operator
    partial_0 = DiscretePartDeriv(discr_space, axis=0, zero_padding=True)
    partial_1 = DiscretePartDeriv(discr_space, axis=1, zero_padding=True)

    # discretized space vector
    vec = partial_0.domain.element(data)

    # partial derivative
    partial_vec_0 = partial_0(vec)
    partial_vec_1 = partial_1(vec)

    assert partial_vec_0 != partial_vec_1
    assert all_equal(partial_vec_0.asarray(), dfe0)
    assert all_equal(partial_vec_1.asarray(), dfe1)

    # operator
    partial_0 = DiscretePartDeriv(discr_space, axis=1, dx=0.2, edge_order=2,
                                  zero_padding=True)

    # adjoint not implemented
    with pytest.raises(NotImplementedError):
        partial_0.adjoint
Exemplo n.º 46
0
def test_part_deriv_cpu():
    """Discretized partial derivative."""

    with pytest.raises(TypeError):
        PartialDerivative(odl.Rn(1))

    # discretized space
    space = odl.uniform_discr([0, 0], [2, 1], DATA_2D.shape)

    # operator
    partial_0 = PartialDerivative(space, axis=0, method='central',
                                  padding_method='constant')
    partial_1 = PartialDerivative(space, axis=1, method='central',
                                  padding_method='constant')

    # discretized space vector
    vec = partial_0.domain.element(DATA_2D)

    # partial derivative
    partial_vec_0 = partial_0(vec)
    partial_vec_1 = partial_1(vec)

    # explicit calculation of finite difference

    # axis: 0
    diff_0 = np.zeros_like(DATA_2D)
    # interior: second-order accurate differences
    diff_0[1:-1, :] = (DATA_2D[2:, :] - DATA_2D[:-2, :]) / 2.0
    # boundary: second-order accurate central differences with zero padding
    diff_0[0, :] = DATA_2D[1, :] / 2.0
    diff_0[-1, :] = -DATA_2D[-2, :] / 2.0
    diff_0 /= space.cell_sides[0]

    # axis: 1
    diff_1 = np.zeros_like(DATA_2D)
    # interior: second-order accurate differences
    diff_1[:, 1:-1] = (DATA_2D[:, 2:] - DATA_2D[:, :-2]) / 2.0
    # boundary: second-order accurate central differences with zero padding
    diff_1[:, 0] = DATA_2D[:, 1] / 2.0
    diff_1[:, -1] = -DATA_2D[:, -2] / 2.0
    diff_1 /= space.cell_sides[1]

    # assert `dfe0` and `dfe1` do differ
    assert (diff_0 != diff_1).any()

    assert partial_vec_0 != partial_vec_1
    assert all_equal(partial_vec_0.asarray(), diff_0)
    assert all_equal(partial_vec_1.asarray(), diff_1)

    # adjoint operator
    vec1 = space.element(DATA_2D)
    vec2 = space.element(DATA_2D + np.random.rand(*DATA_2D.shape))
    assert almost_equal(partial_0(vec1).inner(vec2),
                        vec1.inner(partial_0.adjoint(vec2)))
    assert almost_equal(partial_1(vec1).inner(vec2),
                        vec1.inner(partial_1.adjoint(vec2)))
Exemplo n.º 47
0
def test_uniform_discr_fromdiscr_two_attrs():
    # Change 2 attributes -> resize and translate

    discr = odl.uniform_discr([0, -1], [1, 1], [10, 5])
    # csides = [0.1, 0.4]

    new_min_pt = [-2, 1]
    new_max_pt = [4, 2]
    true_new_csides = [0.6, 0.2]
    new_discr = odl.uniform_discr_fromdiscr(discr, min_pt=new_min_pt,
                                            max_pt=new_max_pt)
    assert all_almost_equal(new_discr.min_pt, new_min_pt)
    assert all_almost_equal(new_discr.max_pt, new_max_pt)
    assert all_equal(new_discr.shape, discr.shape)
    assert all_almost_equal(new_discr.cell_sides, true_new_csides)

    new_min_pt = [-2, 1]
    new_shape = (5, 20)
    true_new_max_pt = [-1.5, 9]
    new_discr = odl.uniform_discr_fromdiscr(discr, min_pt=new_min_pt,
                                            shape=new_shape)
    assert all_almost_equal(new_discr.min_pt, new_min_pt)
    assert all_almost_equal(new_discr.max_pt, true_new_max_pt)
    assert all_equal(new_discr.shape, new_shape)
    assert all_almost_equal(new_discr.cell_sides, discr.cell_sides)

    new_min_pt = [-2, 1]
    new_csides = [0.6, 0.2]
    true_new_max_pt = [4, 2]
    new_discr = odl.uniform_discr_fromdiscr(discr, min_pt=new_min_pt,
                                            cell_sides=new_csides)
    assert all_almost_equal(new_discr.min_pt, new_min_pt)
    assert all_almost_equal(new_discr.max_pt, true_new_max_pt)
    assert all_equal(new_discr.shape, discr.shape)
    assert all_almost_equal(new_discr.cell_sides, new_csides)

    new_max_pt = [4, 2]
    new_shape = (5, 20)
    true_new_min_pt = [3.5, -6]
    new_discr = odl.uniform_discr_fromdiscr(discr, max_pt=new_max_pt,
                                            shape=new_shape)
    assert all_almost_equal(new_discr.min_pt, true_new_min_pt)
    assert all_almost_equal(new_discr.max_pt, new_max_pt)
    assert all_equal(new_discr.shape, new_shape)
    assert all_almost_equal(new_discr.cell_sides, discr.cell_sides)

    new_max_pt = [4, 2]
    new_csides = [0.6, 0.2]
    true_new_min_pt = [-2, 1]
    new_discr = odl.uniform_discr_fromdiscr(discr, max_pt=new_max_pt,
                                            cell_sides=new_csides)
    assert all_almost_equal(new_discr.min_pt, true_new_min_pt)
    assert all_almost_equal(new_discr.max_pt, new_max_pt)
    assert all_equal(new_discr.shape, discr.shape)
    assert all_almost_equal(new_discr.cell_sides, new_csides)
Exemplo n.º 48
0
def test_per_axis_interpolation():
    rect = odl.Rectangle([0, 0], [1, 1])
    grid = odl.uniform_sampling(rect, [4, 2], as_midp=True)
    # Coordinate vectors are:
    # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75]

    space = odl.FunctionSpace(rect)
    dspace = odl.Rn(grid.ntotal)
    schemes = ['linear', 'nearest']
    variants = [None, 'right']
    interp_op = PerAxisInterpolation(space, grid, dspace, schemes=schemes,
                                     nn_variants=variants)
    values = np.arange(1, 9, dtype='float64')
    function = interp_op(values)
    rvals = values.reshape([4, 2])

    # Evaluate at single point
    val = function([0.3, 0.5])
    l1 = (0.3 - 0.125) / (0.375 - 0.125)
    # 0.5 equally far from both neighbors -> 'right' chooses 0.75
    true_val = (1 - l1) * rvals[0, 1] + l1 * rvals[1, 1]
    assert almost_equal(val, true_val)

    # Input array, with and without output array
    pts = np.array([[0.3, 0.6],
                    [0.1, 0.25],
                    [1.0, 1.0]])
    l1 = (0.3 - 0.125) / (0.375 - 0.125)
    true_val_1 = (1 - l1) * rvals[0, 1] + l1 * rvals[1, 1]
    l1 = (0.125 - 0.1) / (0.375 - 0.125)
    true_val_2 = (1 - l1) * rvals[0, 0]  # only lower left contributes
    l1 = (1.0 - 0.875) / (0.875 - 0.625)
    true_val_3 = (1 - l1) * rvals[3, 1]  # lower left only
    true_arr = [true_val_1, true_val_2, true_val_3]
    assert all_equal(function(pts.T), true_arr)

    out = np.empty(3, dtype='float64')
    function(pts.T, out=out)
    assert all_equal(out, true_arr)

    # Input meshgrid, with and without output array
    mg = sparse_meshgrid([0.3, 1.0], [0.4, 0.85])
    # Indices: (1, 3) x (0, 1)
    lx1 = (0.3 - 0.125) / (0.375 - 0.125)
    lx2 = (1.0 - 0.875) / (0.875 - 0.625)
    true_val_11 = (1 - lx1) * rvals[0, 0] + lx1 * rvals[1, 0]
    true_val_12 = ((1 - lx1) * rvals[0, 1] + lx1 * rvals[1, 1])
    true_val_21 = (1 - lx2) * rvals[3, 0]
    true_val_22 = (1 - lx2) * rvals[3, 1]
    true_mg = [[true_val_11, true_val_12],
               [true_val_21, true_val_22]]
    assert all_equal(function(mg), true_mg)
    out = np.empty((2, 2), dtype='float64')
    function(mg, out=out)
    assert all_equal(out, true_mg)
Exemplo n.º 49
0
def test_linear_interpolation_2d():
    """Test linear interpolation in 2d."""
    coord_vecs = [[0.125, 0.375, 0.625, 0.875], [0.25, 0.75]]
    f = np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype='float64')
    interpolator = linear_interpolator(f, coord_vecs)

    # Evaluate at single point
    val = interpolator([0.3, 0.6])
    l1 = (0.3 - 0.125) / (0.375 - 0.125)
    l2 = (0.6 - 0.25) / (0.75 - 0.25)
    true_val = ((1 - l1) * (1 - l2) * f[0, 0] + (1 - l1) * l2 * f[0, 1] + l1 *
                (1 - l2) * f[1, 0] + l1 * l2 * f[1, 1])
    assert val == pytest.approx(true_val)

    # Input array, with and without output array
    pts = np.array([[0.3, 0.6], [0.1, 0.25], [1.0, 1.0]])
    l1 = (0.3 - 0.125) / (0.375 - 0.125)
    l2 = (0.6 - 0.25) / (0.75 - 0.25)
    true_val_1 = ((1 - l1) * (1 - l2) * f[0, 0] + (1 - l1) * l2 * f[0, 1] +
                  l1 * (1 - l2) * f[1, 0] + l1 * l2 * f[1, 1])
    l1 = (0.125 - 0.1) / (0.375 - 0.125)
    # l2 = 0
    true_val_2 = (1 - l1) * f[0, 0]  # only lower left contributes
    l1 = (1.0 - 0.875) / (0.875 - 0.625)
    l2 = (1.0 - 0.75) / (0.75 - 0.25)
    true_val_3 = (1 - l1) * (1 - l2) * f[3, 1]  # lower left only
    true_arr = [true_val_1, true_val_2, true_val_3]
    assert all_equal(interpolator(pts.T), true_arr)

    out = np.empty(3, dtype='float64')
    interpolator(pts.T, out=out)
    assert all_equal(out, true_arr)

    # Input meshgrid, with and without output array
    mg = sparse_meshgrid([0.3, 1.0], [0.4, 0.75])
    # Indices: (1, 3) x (0, 1)
    lx1 = (0.3 - 0.125) / (0.375 - 0.125)
    lx2 = (1.0 - 0.875) / (0.875 - 0.625)
    ly1 = (0.4 - 0.25) / (0.75 - 0.25)
    # ly2 = 0
    true_val_11 = ((1 - lx1) * (1 - ly1) * f[0, 0] +
                   (1 - lx1) * ly1 * f[0, 1] + lx1 * (1 - ly1) * f[1, 0] +
                   lx1 * ly1 * f[1, 1])
    true_val_12 = ((1 - lx1) * f[0, 1] + lx1 * f[1, 1]  # ly2 = 0
                   )
    true_val_21 = ((1 - lx2) * (1 - ly1) * f[3, 0] +
                   (1 - lx2) * ly1 * f[3, 1]  # high node 1.0, no upper
                   )
    true_val_22 = (1 - lx2) * f[3, 1]  # ly2 = 0, no upper for 1.0
    true_mg = [[true_val_11, true_val_12], [true_val_21, true_val_22]]
    assert all_equal(interpolator(mg), true_mg)
    out = np.empty((2, 2), dtype='float64')
    interpolator(mg, out=out)
    assert all_equal(out, true_mg)
Exemplo n.º 50
0
def test_discrete_gradient():
    """Discretized spatial gradient operator."""

    discr_space = Rn(1)
    with pytest.raises(TypeError):
        DiscreteGradient(discr_space)

    # Check result of operator with explicit summation
    # phantom data
    data = np.array([[0., 1., 2., 3., 4.],
                     [1., 2., 3., 4., 5.],
                     [2., 3., 4., 5., 6.]])

    data = np.array([[0., 1., 2., 3., 4.],
                     [0., 1., 2., 3., 4.],
                     [0., 1., 2., 3., 4.]])

    # DiscreteLp Vector
    discr_space = uniform_discr([0, 0], [6, 2.5], data.shape)
    dom_vec = discr_space.element(data)

    # computation of gradient components with helper function
    dx0, dx1 = discr_space.grid.stride
    df0 = finite_diff(data, axis=0, dx=dx0, zero_padding=True, edge_order=2)
    df1 = finite_diff(data, axis=1, dx=dx1, zero_padding=True, edge_order=2)

    # gradient
    grad = DiscreteGradient(discr_space)
    grad_vec = grad(dom_vec)
    assert len(grad_vec) == data.ndim
    assert all_equal(grad_vec[0].asarray(), df0)
    assert all_equal(grad_vec[1].asarray(), df1)

    # adjoint operator
    ran_vec = grad.range.element([data, data ** 2])
    adj_vec = grad.adjoint(ran_vec)
    lhs = ran_vec.inner(grad_vec)
    rhs = dom_vec.inner(adj_vec)
    assert lhs != 0
    assert rhs != 0
    assert lhs == rhs

    # higher dimensional arrays
    lin_size = 3
    for ndim in range(1, 6):

        # DiscreteLp Vector
        discr_space = uniform_discr([0.] * ndim, [lin_size] * ndim,
                                    [lin_size] * ndim)
        dom_vec = discr_space.element(ndvolume(lin_size, ndim))

        # gradient
        grad = DiscreteGradient(discr_space)
        grad(dom_vec)
Exemplo n.º 51
0
def test_fspace_vector_ufunc():
    intv = odl.IntervalProd(0, 1)
    points = _points(intv, num=5)
    mg = _meshgrid(intv, shape=(5, ))

    fspace = FunctionSpace(intv)
    f_vec = fspace.element(np.sin)

    assert f_vec(0.5) == np.sin(0.5)
    assert all_equal(f_vec(points), np.sin(points.squeeze()))
    assert all_equal(f_vec(mg), np.sin(mg[0]))
Exemplo n.º 52
0
def test_fspace_vector_ufunc():
    intv = odl.Interval(0, 1)
    points = _points(intv, num=5)
    mg = _meshgrid(intv, shape=(5,))

    fspace = FunctionSpace(intv)
    f_vec = fspace.element(np.sin)

    assert f_vec(0.5) == np.sin(0.5)
    assert all_equal(f_vec(points), np.sin(points.squeeze()))
    assert all_equal(f_vec(mg), np.sin(mg[0]))
Exemplo n.º 53
0
def test_pointwise_sum():
    """PointwiseSum currently depends on PointwiseInner, we verify that."""

    fspace = odl.uniform_discr([0, 0], [1, 1], (2, 2))
    vfspace = ProductSpace(fspace, 3, exponent=2)

    # Make sure the code runs and test the properties
    psum = PointwiseSum(vfspace)
    assert isinstance(psum, PointwiseInner)
    assert psum.base_space == fspace
    assert all_equal(psum.weights, [1, 1, 1])
    assert all_equal(psum.vecfield, psum.domain.one())
Exemplo n.º 54
0
def test_getslice():
    discr = odl.uniform_discr(0, 1, 3)
    vec = discr.element([1, 2, 3])

    assert isinstance(vec[:], odl.FnVector)
    assert all_equal(vec[:], [1, 2, 3])

    discr = odl.uniform_discr(0, 1, 3, field=odl.ComplexNumbers())
    vec = discr.element([1 + 2j, 2 - 2j, 3])

    assert isinstance(vec[:], odl.FnVector)
    assert all_equal(vec[:], [1 + 2j, 2 - 2j, 3])
Exemplo n.º 55
0
def test_pointwise_sum():
    """PointwiseSum currently depends on PointwiseInner, we verify that."""

    fspace = odl.uniform_discr([0, 0], [1, 1], (2, 2))
    vfspace = ProductSpace(fspace, 3, exponent=2)

    # Make sure the code runs and test the properties
    psum = PointwiseSum(vfspace)
    assert isinstance(psum, PointwiseInner)
    assert psum.base_space == fspace
    assert all_equal(psum.weights, [1, 1, 1])
    assert all_equal(psum.vecfield, psum.domain.one())
Exemplo n.º 56
0
def test_getslice():
    discr = odl.uniform_discr(0, 1, 3)
    elem = discr.element([1, 2, 3])

    assert isinstance(elem[:], odl.NumpyFnVector)
    assert all_equal(elem[:], [1, 2, 3])

    discr = odl.uniform_discr(0, 1, 3, dtype='complex')
    elem = discr.element([1 + 2j, 2 - 2j, 3])

    assert isinstance(elem[:], odl.NumpyFnVector)
    assert all_equal(elem[:], [1 + 2j, 2 - 2j, 3])
Exemplo n.º 57
0
def test_RxR():
    H = odl.Rn(2)
    HxH = odl.ProductSpace(H, H)
    assert len(HxH) == 2

    v1 = H.element([1, 2])
    v2 = H.element([3, 4])
    v = HxH.element([v1, v2])
    u = HxH.element([[1, 2], [3, 4]])

    assert all_equal([v1, v2], v)
    assert all_equal([v1, v2], u)
Exemplo n.º 58
0
def test_power_RxR():
    H = odl.rn(2)
    HxH = odl.ProductSpace(H, 2)
    assert len(HxH) == 2

    v1 = H.element([1, 2])
    v2 = H.element([3, 4])
    v = HxH.element([v1, v2])
    u = HxH.element([[1, 2], [3, 4]])

    assert all_equal([v1, v2], v)
    assert all_equal([v1, v2], u)
Exemplo n.º 59
0
def test_minpt_maxpt():
    vec1 = np.arange(2, 6)
    vec2 = np.arange(-4, 5, 2)
    vec3 = np.arange(-1, 1)
    scalar = 0.5

    grid = TensorGrid(vec1, vec2, vec3)
    assert all_equal(grid.min_pt, (2, -4, -1))
    assert all_equal(grid.max_pt, (5, 4, 0))

    grid = TensorGrid(vec1, scalar, vec2, scalar)
    assert all_equal(grid.min_pt, (2, 0.5, -4, 0.5))
    assert all_equal(grid.max_pt, (5, 0.5, 4, 0.5))
Exemplo n.º 60
0
def test_pywt_coeff_list_conversion(small_shapes, floating_dtype):
    """Test if converstion flat array <-> coefficient list works."""
    ndim, shapes = small_shapes

    grouped_list, flat_list = _grouped_and_flat_arrays(shapes, dtype=float)

    true_flat_array = np.hstack(flat_list)
    flat_array = pywt_flat_array_from_coeffs(grouped_list)
    assert all_equal(flat_array, true_flat_array)

    coeff_list = pywt_coeffs_from_flat_array(flat_array, shapes)
    true_coeff_list = grouped_list
    assert all_equal(coeff_list, true_coeff_list)