Esempio n. 1
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())

    cn = odl.cn(10, exponent=exponent)
    odl.DiscreteLp(complex_space, part, cn, exponent=exponent)

    space = odl.FunctionSpace(odl.IntervalProd([0, 0], [1, 1]))
    part = odl.uniform_partition_fromintv(space.domain, (10, 10))
    rn = odl.rn(100, exponent=exponent)
    odl.DiscreteLp(space, part, rn, exponent=exponent,
                   interp=['nearest', 'linear'])

    # Real space should not work with complex
    with pytest.raises(ValueError):
        odl.DiscreteLp(space, part, cn)

    # Complex space should not work with reals
    with pytest.raises(ValueError):
        odl.DiscreteLp(complex_space, part, rn)

    # Wrong size of underlying space
    rn_wrong_size = odl.rn(20)
    with pytest.raises(ValueError):
        odl.DiscreteLp(space, part, rn_wrong_size)
Esempio n. 2
0
def test_partition_insert():
    vec11 = [2, 4, 5, 7]
    vec12 = [-4, -3, 0, 1, 4]
    begin1 = [1, -4]
    end1 = [7, 5]
    grid1 = odl.TensorGrid(vec11, vec12)
    intv1 = odl.IntervalProd(begin1, end1)
    part1 = odl.RectPartition(intv1, grid1)

    vec21 = [-2, 0, 3]
    vec22 = [0]
    begin2 = [-2, -2]
    end2 = [4, 0]
    grid2 = odl.TensorGrid(vec21, vec22)
    intv2 = odl.IntervalProd(begin2, end2)
    part2 = odl.RectPartition(intv2, grid2)

    part = part1.insert(0, part2)
    assert all_equal(part.begin, [-2, -2, 1, -4])
    assert all_equal(part.end, [4, 0, 7, 5])
    assert all_equal(part.grid.min_pt, [-2, 0, 2, -4])
    assert all_equal(part.grid.max_pt, [3, 0, 7, 4])

    part = part1.insert(1, part2)
    assert all_equal(part.begin, [1, -2, -2, -4])
    assert all_equal(part.end, [7, 4, 0, 5])
    assert all_equal(part.grid.min_pt, [2, -2, 0, -4])
    assert all_equal(part.grid.max_pt, [7, 3, 0, 4])
Esempio n. 3
0
def test_resizing_op_mixed_uni_nonuni():
    """Check if resizing along uniform axes in mixed discretizations works."""
    nonuni_part = odl.nonuniform_partition([0, 1, 4])
    uni_part = odl.uniform_partition(-1, 1, 4)
    part = uni_part.append(nonuni_part, uni_part, nonuni_part)
    fspace = odl.FunctionSpace(odl.IntervalProd(part.min_pt, part.max_pt))
    tspace = odl.rn(part.shape)
    space = odl.DiscreteLp(fspace, part, tspace)

    # Keep non-uniform axes fixed
    res_op = odl.ResizingOperator(space, ran_shp=(6, 3, 6, 3))

    assert res_op.axes == (0, 2)
    assert res_op.offset == (1, 0, 1, 0)

    # Evaluation test with a simpler case
    part = uni_part.append(nonuni_part)
    fspace = odl.FunctionSpace(odl.IntervalProd(part.min_pt, part.max_pt))
    tspace = odl.rn(part.shape)
    space = odl.DiscreteLp(fspace, part, tspace)
    res_op = odl.ResizingOperator(space, ran_shp=(6, 3))
    result = res_op(space.one())
    true_result = [[0, 0, 0], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1],
                   [0, 0, 0]]
    assert np.array_equal(result, true_result)

    # Test adjoint
    elem = noise_element(space)
    res_elem = noise_element(res_op.range)
    inner1 = res_op(elem).inner(res_elem)
    inner2 = elem.inner(res_op.adjoint(res_elem))
    assert almost_equal(inner1, inner2)
Esempio n. 4
0
def test_partition_init_raise():
    # Check different error scenarios
    vec1 = np.array([2, 4, 5, 7])
    vec2 = np.array([-4, -3, 0, 1, 4])
    grid = odl.TensorGrid(vec1, vec2)
    begin = [2, -5]
    end = [10, 4]

    beg_toolarge = (2, -3.5)
    end_toosmall = (7, 1)
    beg_badshape = (-1, 2, 0)
    end_badshape = (2, )

    with pytest.raises(ValueError):
        odl.RectPartition(odl.IntervalProd(beg_toolarge, end), grid)

    with pytest.raises(ValueError):
        odl.RectPartition(odl.IntervalProd(begin, end_toosmall), grid)

    with pytest.raises(ValueError):
        odl.RectPartition(odl.IntervalProd(beg_badshape, end_badshape), grid)

    with pytest.raises(TypeError):
        odl.RectPartition(None, grid)

    with pytest.raises(TypeError):
        odl.RectPartition(odl.IntervalProd(beg_toolarge, end), None)
Esempio n. 5
0
def test_partition_insert():
    vec11 = [2, 4, 5, 7]
    vec12 = [-4, -3, 0, 1, 4]
    min_pt1 = [1, -4]
    max_pt1 = [7, 5]
    grid1 = odl.RectGrid(vec11, vec12)
    intv1 = odl.IntervalProd(min_pt1, max_pt1)
    part1 = odl.RectPartition(intv1, grid1)

    vec21 = [-2, 0, 3]
    vec22 = [0]
    min_pt2 = [-2, -2]
    max_pt2 = [4, 0]
    grid2 = odl.RectGrid(vec21, vec22)
    intv2 = odl.IntervalProd(min_pt2, max_pt2)
    part2 = odl.RectPartition(intv2, grid2)

    part = part1.insert(0, part2)
    assert all_equal(part.min_pt, [-2, -2, 1, -4])
    assert all_equal(part.max_pt, [4, 0, 7, 5])
    assert all_equal(part.grid.min_pt, [-2, 0, 2, -4])
    assert all_equal(part.grid.max_pt, [3, 0, 7, 4])

    part = part1.insert(1, part2)
    assert all_equal(part.min_pt, [1, -2, -2, -4])
    assert all_equal(part.max_pt, [7, 4, 0, 5])
    assert all_equal(part.grid.min_pt, [2, -2, 0, -4])
    assert all_equal(part.grid.max_pt, [7, 3, 0, 4])
Esempio n. 6
0
def test_empty_partition():
    """Check if empty partitions behave as expected and all methods work."""
    part = odl.RectPartition(odl.IntervalProd([], []),
                             odl.uniform_grid([], [], ()))

    assert part.cell_boundary_vecs == ()
    assert part.nodes_on_bdry is True
    assert part.nodes_on_bdry_byaxis == ()
    assert part.has_isotropic_cells
    assert part.boundary_cell_fractions == ()
    assert part.cell_sizes_vecs == ()
    assert np.array_equal(part.cell_sides, [])
    assert part.cell_volume == 0

    same = odl.RectPartition(odl.IntervalProd([], []),
                             odl.uniform_grid([], [], ()))
    assert part == same
    assert hash(part) == hash(same)
    other = odl.uniform_partition(0, 1, 4)
    assert part != other

    assert part[[]] == part
    assert part.insert(0, other) == other
    assert other.insert(0, part) == other
    assert other.insert(1, part) == other
    assert part.squeeze() == part
    assert part.index([]) == ()
    part.byaxis
    assert part == odl.uniform_partition([], [], ())
    repr(part)
Esempio n. 7
0
def test_fspace_vector_init():
    # 1d, real
    intv = odl.IntervalProd(0, 1)
    fspace = FunctionSpace(intv)
    fspace.element(func_1d_oop)
    fspace.element(func_1d_oop, vectorized=False)
    fspace.element(func_1d_oop, vectorized=True)
    fspace.element(func_1d_ip, vectorized=True)
    fspace.element(func_1d_dual, vectorized=True)

    # 2d, real
    rect = odl.IntervalProd([0, 0], [1, 2])
    fspace = FunctionSpace(rect)
    fspace.element(func_2d_novec, vectorized=False)
    fspace.element(func_2d_vec_oop)
    fspace.element(func_2d_vec_oop, vectorized=True)
    fspace.element(func_2d_vec_ip, vectorized=True)
    fspace.element(func_2d_vec_dual, vectorized=True)

    # 2d, complex
    fspace = FunctionSpace(rect, field=odl.ComplexNumbers())
    fspace.element(cfunc_2d_novec, vectorized=False)
    fspace.element(cfunc_2d_vec_oop)
    fspace.element(cfunc_2d_vec_oop, vectorized=True)
    fspace.element(cfunc_2d_vec_ip, vectorized=True)
    fspace.element(cfunc_2d_vec_dual, vectorized=True)
Esempio n. 8
0
def test_uniform_partition_fromgrid():
    vec1 = np.array([2, 4, 5, 7])
    vec2 = np.array([-4, -3, 0, 1, 4])
    begin = [0, -4]
    end = [7, 8]
    beg_calc = [2 - (4 - 2) / 2, -4 - (-3 + 4) / 2]
    end_calc = [7 + (7 - 5) / 2, 4 + (4 - 1) / 2]

    # Default case
    grid = odl.TensorGrid(vec1, vec2)
    part = odl.uniform_partition_fromgrid(grid)
    assert part.set == odl.IntervalProd(beg_calc, end_calc)

    # Explicit begin / end, full vectors
    part = odl.uniform_partition_fromgrid(grid, begin=begin)
    assert part.set == odl.IntervalProd(begin, end_calc)
    part = odl.uniform_partition_fromgrid(grid, end=end)
    assert part.set == odl.IntervalProd(beg_calc, end)

    # begin / end as dictionaries
    beg_dict = {0: 0.5}
    end_dict = {-1: 8}
    part = odl.uniform_partition_fromgrid(grid, begin=beg_dict, end=end_dict)
    true_beg = [0.5, beg_calc[1]]
    true_end = [end_calc[0], 8]
    assert part.set == odl.IntervalProd(true_beg, true_end)

    # Degenerate dimension, needs both explicit begin and end
    grid = odl.TensorGrid(vec1, [1.0])
    with pytest.raises(ValueError):
        odl.uniform_partition_fromgrid(grid)
    with pytest.raises(ValueError):
        odl.uniform_partition_fromgrid(grid, begin=begin)
    with pytest.raises(ValueError):
        odl.uniform_partition_fromgrid(grid, end=end)
Esempio n. 9
0
def test_partition_init_raise():
    # Check different error scenarios
    vec1 = np.array([2, 4, 5, 7])
    vec2 = np.array([-4, -3, 0, 1, 4])
    grid = odl.RectGrid(vec1, vec2)
    min_pt = [2, -5]
    max_pt = [10, 4]

    min_pt_toolarge = (2, -3.5)
    max_pt_toosmall = (7, 1)
    min_pt_badshape = (-1, 2, 0)
    max_pt_badshape = (2, )

    with pytest.raises(ValueError):
        odl.RectPartition(odl.IntervalProd(min_pt_toolarge, max_pt), grid)

    with pytest.raises(ValueError):
        odl.RectPartition(odl.IntervalProd(min_pt, max_pt_toosmall), grid)

    with pytest.raises(ValueError):
        odl.RectPartition(odl.IntervalProd(min_pt_badshape, max_pt_badshape),
                          grid)

    with pytest.raises(TypeError):
        odl.RectPartition(None, grid)

    with pytest.raises(TypeError):
        odl.RectPartition(odl.IntervalProd(min_pt_toolarge, max_pt), None)
Esempio n. 10
0
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)
    assert discr.fspace == fspace
    assert discr.tspace == tspace
    assert discr.partition == part
    assert discr.interp == 'nearest'
    assert discr.interp_byaxis == ('nearest', 'nearest')
    assert discr.exponent == tspace.exponent
    assert discr.axis_labels == ('$x$', '$y$')
    assert discr.is_real

    discr = DiscreteLp(fspace, part, tspace, interp='linear')
    assert discr.interp == 'linear'
    assert discr.interp_byaxis == ('linear', 'linear')

    discr = DiscreteLp(fspace, part, tspace, interp=['nearest', 'linear'])
    assert discr.interp == ('nearest', 'linear')
    assert discr.interp_byaxis == ('nearest', 'linear')

    # Complex space
    fspace_c = odl.FunctionSpace(odl.IntervalProd([0, 0], [1, 1]),
                                 out_dtype=complex)
    tspace_c = odl.cn(part.shape)
    discr = DiscreteLp(fspace_c, part, tspace_c)
    assert discr.is_complex

    # Make sure repr shows something
    assert repr(discr)

    # Error scenarios
    with pytest.raises(ValueError):
        DiscreteLp(fspace, part, tspace_c)  # mixes real & complex

    with pytest.raises(ValueError):
        DiscreteLp(fspace_c, part, tspace)  # mixes complex & real

    part_1d = odl.uniform_partition(0, 1, 2)
    with pytest.raises(ValueError):
        DiscreteLp(fspace, part_1d, tspace)  # wrong dimensionality

    part_diffshp = odl.uniform_partition_fromintv(fspace.domain, (3, 4))
    with pytest.raises(ValueError):
        DiscreteLp(fspace, part_diffshp, tspace)  # shape mismatch
Esempio n. 11
0
def test_partition_set():
    vec1 = np.array([2, 4, 5, 7])
    vec2 = np.array([-4, -3, 0, 1, 4])
    grid = odl.RectGrid(vec1, vec2)

    min_pt = [1, -4]
    max_pt = [10, 5]
    intv = odl.IntervalProd(min_pt, max_pt)

    part = odl.RectPartition(intv, grid)
    assert part.set == odl.IntervalProd(min_pt, max_pt)
    assert all_equal(part.min_pt, min_pt)
    assert all_equal(part.min(), min_pt)
    assert all_equal(part.max_pt, max_pt)
    assert all_equal(part.max(), max_pt)
Esempio n. 12
0
def test_equals():
    """Test equality check and hash."""
    intv = odl.IntervalProd(0, 1)
    intv2 = odl.IntervalProd(-1, 1)
    fspace = FunctionSpace(intv)
    fspace_r = FunctionSpace(intv, field=odl.RealNumbers())
    fspace_c = FunctionSpace(intv, field=odl.ComplexNumbers())
    fspace_intv2 = FunctionSpace(intv2)

    _test_eq(fspace, fspace)
    _test_eq(fspace, fspace_r)
    _test_eq(fspace_c, fspace_c)

    _test_neq(fspace, fspace_c)
    _test_neq(fspace, fspace_intv2)
Esempio n. 13
0
def test_partition_set():
    vec1 = np.array([2, 4, 5, 7])
    vec2 = np.array([-4, -3, 0, 1, 4])
    grid = odl.TensorGrid(vec1, vec2)

    begin = [1, -4]
    end = [10, 5]
    intv = odl.IntervalProd(begin, end)

    part = odl.RectPartition(intv, grid)
    assert part.set == odl.IntervalProd(begin, end)
    assert all_equal(part.begin, begin)
    assert all_equal(part.min(), begin)
    assert all_equal(part.end, end)
    assert all_equal(part.max(), end)
Esempio n. 14
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) != ''
Esempio n. 15
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))
Esempio n. 16
0
def test_fspace_elem_copy(out_shape):
    """Check copying of fspace elements."""
    fspace = FunctionSpace(odl.IntervalProd(0, 1),
                           out_dtype=(float, out_shape))

    ndim = len(out_shape)
    if ndim == 0:
        f_oop = fspace.element(func_nd_oop)
        f_ip = fspace.element(func_nd_ip)
        f_dual = fspace.element(func_nd_dual)
    elif ndim == 1:
        f_oop = fspace.element(func_vec_nd_oop)
        f_ip = fspace.element(func_vec_nd_ip)
        f_dual = fspace.element(func_vec_nd_dual)
    elif ndim == 2:
        f_oop = fspace.element(func_tens_oop)
        f_ip = fspace.element(func_tens_ip)
        f_dual = fspace.element(func_tens_dual)
    else:
        assert False

    f_out = f_oop.copy()
    assert f_out == f_oop

    f_out = f_ip.copy()
    assert f_out == f_ip

    f_out = f_dual.copy()
    assert f_out == f_dual
Esempio n. 17
0
def test_collocation_interpolation_identity():
    # Check if interpolation followed by collocation on the same grid
    # is the identity
    rect = odl.IntervalProd([0, 0], [1, 1])
    part = odl.uniform_partition_fromintv(rect, [4, 2])
    space = odl.FunctionSpace(rect)
    dspace = odl.rn(part.size)

    coll_op_c = PointCollocation(space, part, dspace, order='C')
    coll_op_f = PointCollocation(space, part, dspace, order='F')
    interp_ops_c = [
        NearestInterpolation(space, part, dspace, variant='left', order='C'),
        NearestInterpolation(space, part, dspace, variant='right', order='C'),
        LinearInterpolation(space, part, dspace, order='C'),
        PerAxisInterpolation(space, part, dspace, order='C',
                             schemes=['linear', 'nearest'])]
    interp_ops_f = [
        NearestInterpolation(space, part, dspace, variant='left', order='F'),
        NearestInterpolation(space, part, dspace, variant='right', order='F'),
        LinearInterpolation(space, part, dspace, order='F'),
        PerAxisInterpolation(space, part, dspace, order='F',
                             schemes=['linear', 'nearest'])]

    values = np.arange(1, 9, dtype='float64')

    for interp_op_c in interp_ops_c:
        ident_values = coll_op_c(interp_op_c(values))
        assert all_almost_equal(ident_values, values)

    for interp_op_f in interp_ops_f:
        ident_values = coll_op_f(interp_op_f(values))
        assert all_almost_equal(ident_values, values)
Esempio n. 18
0
def test_fspace_elem_power(power, out_shape):
    """Check taking powers of fspace elements."""
    # Make sure test functions don't take negative values
    intv = odl.IntervalProd([1, 0], [2, 1])
    fspace = FunctionSpace(intv, out_dtype=(float, out_shape))
    points = _points(fspace.domain, 4)

    ndim = len(out_shape)
    with np.errstate(all='ignore'):
        if ndim == 0:
            f_elem = fspace.element(func_nd_oop)
            true_result = func_nd_ref(points)**power
        elif ndim == 1:
            f_elem = fspace.element(func_vec_nd_oop)
            true_result = func_vec_nd_ref(points)**power
        elif ndim == 2:
            f_elem = fspace.element(func_tens_oop)
            true_result = func_tens_ref(points)**power
        else:
            assert False

        # Out-of-place power
        f_elem_pow = f_elem**power
        assert all_almost_equal(f_elem_pow(points), true_result)
        out_arr = np.empty(out_shape + (4, ))
        f_elem_pow(points, out_arr)
        assert all_almost_equal(out_arr, true_result)

        # In-place power
        f_elem_pow = f_elem.copy()
        f_elem_pow **= power
        assert all_almost_equal(f_elem_pow(points), true_result)
        out_arr = np.empty(out_shape + (4, ))
        f_elem_pow(points, out_arr)
        assert all_almost_equal(out_arr, true_result)
Esempio n. 19
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)
Esempio n. 20
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) != ''
Esempio n. 21
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)
Esempio n. 22
0
def test_fspace_vector_equality():
    rect = odl.IntervalProd([0, 0], [1, 2])
    fspace = FunctionSpace(rect)

    f_novec = fspace.element(func_2d_novec, vectorized=False)

    f_vec_oop = fspace.element(func_2d_vec_oop, vectorized=True)
    f_vec_oop_2 = fspace.element(func_2d_vec_oop, vectorized=True)

    f_vec_ip = fspace.element(func_2d_vec_ip, vectorized=True)
    f_vec_ip_2 = fspace.element(func_2d_vec_ip, vectorized=True)

    f_vec_dual = fspace.element(func_2d_vec_dual, vectorized=True)
    f_vec_dual_2 = fspace.element(func_2d_vec_dual, vectorized=True)

    assert f_novec == f_novec
    assert f_novec != f_vec_oop
    assert f_novec != f_vec_ip
    assert f_novec != f_vec_dual

    assert f_vec_oop == f_vec_oop
    assert f_vec_oop == f_vec_oop_2
    assert f_vec_oop != f_vec_ip
    assert f_vec_oop != f_vec_dual

    assert f_vec_ip == f_vec_ip
    assert f_vec_ip == f_vec_ip_2
    assert f_vec_ip != f_vec_dual

    assert f_vec_dual == f_vec_dual
    assert f_vec_dual == f_vec_dual_2
Esempio n. 23
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) != ''
Esempio n. 24
0
def test_partition_init():
    vec1 = np.array([2, 4, 5, 7])
    vec2 = np.array([-4, -3, 0, 1, 4])
    min_pt = [2, -5]
    max_pt = [10, 4]

    # Simply test if code runs
    odl.RectPartition(odl.IntervalProd(min_pt, max_pt),
                      odl.RectGrid(vec1, vec2))
    odl.RectPartition(odl.IntervalProd(min_pt[0], max_pt[0]),
                      odl.RectGrid(vec1))

    # Degenerate dimensions should work, too
    vec2 = np.array([1.0])
    odl.RectPartition(odl.IntervalProd(min_pt, max_pt),
                      odl.RectGrid(vec1, vec2))
Esempio n. 25
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)
Esempio n. 26
0
def test_collocation_interpolation_identity():
    """Check if collocation is left-inverse to interpolation."""
    # Interpolation followed by collocation on the same grid should be
    # the identity
    rect = odl.IntervalProd([0, 0], [1, 1])
    part = odl.uniform_partition_fromintv(rect, [4, 2])
    space = odl.FunctionSpace(rect)
    tspace = odl.rn(part.shape)

    coll_op = PointCollocation(space, part, tspace)
    interp_ops = [
        NearestInterpolation(space, part, tspace, variant='left'),
        NearestInterpolation(space, part, tspace, variant='right'),
        LinearInterpolation(space, part, tspace),
        PerAxisInterpolation(space,
                             part,
                             tspace,
                             schemes=['linear', 'nearest'])
    ]

    values = np.arange(1, 9, dtype='float64').reshape(tspace.shape)

    for interp_op in interp_ops:
        ident_values = coll_op(interp_op(values))
        assert all_almost_equal(ident_values, values)
Esempio n. 27
0
def test_fspace_elem_real_imag_conj(out_shape):
    """Check taking real/imaginary parts of fspace elements."""
    fspace = FunctionSpace(odl.IntervalProd(0, 1),
                           out_dtype=(complex, out_shape))

    ndim = len(out_shape)
    if ndim == 0:
        f_elem = fspace.element(func_complex_nd_oop)
    elif ndim == 1:
        f_elem = fspace.element(func_vec_complex_nd_oop)
    elif ndim == 2:
        f_elem = fspace.element(func_tens_complex_oop)
    else:
        assert False

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

    result_points = f_elem(points)
    result_point = f_elem(point)
    result_mesh = f_elem(mesh)

    assert all_almost_equal(f_elem.real(points), result_points.real)
    assert all_almost_equal(f_elem.real(point), result_point.real)
    assert all_almost_equal(f_elem.real(mesh), result_mesh.real)
    assert all_almost_equal(f_elem.imag(points), result_points.imag)
    assert all_almost_equal(f_elem.imag(point), result_point.imag)
    assert all_almost_equal(f_elem.imag(mesh), result_mesh.imag)
    assert all_almost_equal(f_elem.conj()(points), result_points.conj())
    assert all_almost_equal(f_elem.conj()(point), np.conj(result_point))
    assert all_almost_equal(f_elem.conj()(mesh), result_mesh.conj())

    out_points = np.empty(values_points_shape, dtype=float)
    out_mesh = np.empty(values_mesh_shape, dtype=float)

    f_elem.real(points, out=out_points)
    f_elem.real(mesh, out=out_mesh)

    assert all_almost_equal(out_points, result_points.real)
    assert all_almost_equal(out_mesh, result_mesh.real)

    f_elem.imag(points, out=out_points)
    f_elem.imag(mesh, out=out_mesh)

    assert all_almost_equal(out_points, result_points.imag)
    assert all_almost_equal(out_mesh, result_mesh.imag)

    out_points = np.empty(values_points_shape, dtype=complex)
    out_mesh = np.empty(values_mesh_shape, dtype=complex)

    f_elem.conj()(points, out=out_points)
    f_elem.conj()(mesh, out=out_mesh)

    assert all_almost_equal(out_points, result_points.conj())
    assert all_almost_equal(out_mesh, result_mesh.conj())
Esempio n. 28
0
def test_equals():
    """Test equality check and hash."""
    intv = odl.IntervalProd(0, 1)
    intv2 = odl.IntervalProd(-1, 1)
    fspace = FunctionSpace(intv)
    fspace_r = FunctionSpace(intv, out_dtype=float)
    fspace_c = FunctionSpace(intv, out_dtype=complex)
    fspace_intv2 = FunctionSpace(intv2)
    fspace_vec = FunctionSpace(intv, out_dtype=(float, (2, )))

    _test_eq(fspace, fspace)
    _test_eq(fspace, fspace_r)
    _test_eq(fspace_c, fspace_c)

    _test_neq(fspace, fspace_c)
    _test_neq(fspace, fspace_intv2)
    _test_neq(fspace_r, fspace_vec)
Esempio n. 29
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) != ''
Esempio n. 30
0
def test_fspace_astype():
    """Check that converting function spaces to new out_dtype works."""
    rspace = FunctionSpace(odl.IntervalProd(0, 1))
    cspace = FunctionSpace(odl.IntervalProd(0, 1), out_dtype=complex)
    rspace_s = FunctionSpace(odl.IntervalProd(0, 1), out_dtype='float32')
    cspace_s = FunctionSpace(odl.IntervalProd(0, 1), out_dtype='complex64')

    assert rspace.astype('complex64') == cspace_s
    assert rspace.astype('complex128') == cspace
    assert rspace.astype('complex128') is rspace.complex_space
    assert rspace.astype('float32') == rspace_s
    assert rspace.astype('float64') is rspace.real_space

    assert cspace.astype('float32') == rspace_s
    assert cspace.astype('float64') == rspace
    assert cspace.astype('float64') is cspace.real_space
    assert cspace.astype('complex64') == cspace_s
    assert cspace.astype('complex128') is cspace.complex_space