def test_dspace_type_cuda():
    # Plain function set -> Ntuples-like
    fset = odl.FunctionSet(odl.Interval(0, 1), odl.Strings(2))
    assert dspace_type(fset, 'cuda') == odl.CudaNtuples
    assert dspace_type(fset, 'cuda', np.int) == odl.CudaNtuples

    # Real space
    rspc = odl.FunctionSpace(odl.Interval(0, 1), field=odl.RealNumbers())
    assert dspace_type(rspc, 'cuda') == odl.CudaRn
    assert dspace_type(rspc, 'cuda', np.float32) == odl.CudaRn
    assert dspace_type(rspc, 'cuda', np.int) == odl.CudaFn
    with pytest.raises(TypeError):
        dspace_type(rspc, 'cuda', np.complex)
    with pytest.raises(TypeError):
        dspace_type(rspc, 'cuda', np.dtype('<U2'))

    # Complex space (not implemented)
    cspc = odl.FunctionSpace(odl.Interval(0, 1), field=odl.ComplexNumbers())
    with pytest.raises(NotImplementedError):
        dspace_type(cspc, 'cuda')
    with pytest.raises(NotImplementedError):
        dspace_type(cspc, 'cuda', np.complex64)
    with pytest.raises(TypeError):
        dspace_type(cspc, 'cuda', np.float)
    with pytest.raises(TypeError):
        assert dspace_type(cspc, 'cuda', np.int)
def test_dspace_type_numpy():
    # Plain function set -> Ntuples-like
    fset = odl.FunctionSet(odl.Interval(0, 1), odl.Strings(2))
    assert dspace_type(fset, 'numpy') == odl.Ntuples
    assert dspace_type(fset, 'numpy', np.int) == odl.Ntuples

    # Real space
    rspc = odl.FunctionSpace(odl.Interval(0, 1), field=odl.RealNumbers())
    assert dspace_type(rspc, 'numpy') == odl.Rn
    assert dspace_type(rspc, 'numpy', np.float32) == odl.Rn
    assert dspace_type(rspc, 'numpy', np.int) == odl.Fn
    with pytest.raises(TypeError):
        dspace_type(rspc, 'numpy', np.complex)
    with pytest.raises(TypeError):
        dspace_type(rspc, 'numpy', np.dtype('<U2'))

    # Complex space
    cspc = odl.FunctionSpace(odl.Interval(0, 1), field=odl.ComplexNumbers())
    assert dspace_type(cspc, 'numpy') == odl.Cn
    assert dspace_type(cspc, 'numpy', np.complex64) == odl.Cn
    with pytest.raises(TypeError):
        dspace_type(cspc, 'numpy', np.float)
    with pytest.raises(TypeError):
        assert dspace_type(cspc, 'numpy', np.int)
    with pytest.raises(TypeError):
        dspace_type(cspc, 'numpy', np.dtype('<U2'))
Exemple #3
0
def uniform_discr_fromspace(fspace, nsamples, exponent=2.0, interp='nearest',
                            impl='numpy', **kwargs):
    """Discretize an Lp function space by uniform sampling.

    Parameters
    ----------
    fspace : `FunctionSpace`
        Continuous function space. Its domain must be an
        `IntervalProd` instance.
    nsamples : `int` or `tuple` of `int`
        Number of samples per axis. For dimension >= 2, a tuple is
        required.
    exponent : positive `float`, optional
        The parameter :math:`p` in :math:`L^p`. If the exponent is not
        equal to the default 2.0, the space has no inner product.
    interp : `str`, optional
            Interpolation type to be used for discretization.

            'nearest' : use nearest-neighbor interpolation (default)

            'linear' : use linear interpolation (not implemented)
    impl : {'numpy', 'cuda'}
        Implementation of the data storage arrays
    kwargs : {'order', 'dtype', 'weighting'}
            'order' : {'C', 'F'}  (Default: 'C')
                Axis ordering in the data storage
            'dtype' : dtype
                Data type for the discretized space

                Default for 'numpy': 'float64' / 'complex128'
                Default for 'cuda': 'float32' / TODO
            'weighting' : {'simple', 'consistent'}
                Weighting of the discretized space functions.

                'simple': weight is a constant (cell volume)

                'consistent': weight is a matrix depending on the
                interpolation type

    Returns
    -------
    discr : `DiscreteLp`
        The uniformly discretized function space

    Examples
    --------
    >>> from odl import Interval, FunctionSpace
    >>> I = Interval(0, 1)
    >>> X = FunctionSpace(I)
    >>> uniform_discr_fromspace(X, 10)
    uniform_discr([0.0], [1.0], [10])

    See also
    --------
    uniform_discr
    """
    if not isinstance(fspace, FunctionSpace):
        raise TypeError('space {!r} is not a `FunctionSpace` instance.'
                        ''.format(fspace))
    if not isinstance(fspace.domain, IntervalProd):
        raise TypeError('domain {!r} of the function space is not an '
                        '`IntervalProd` instance.'.format(fspace.domain))

    if impl == 'cuda' and not CUDA_AVAILABLE:
        raise ValueError('CUDA not available.')

    dtype = kwargs.pop('dtype', None)
    ds_type = dspace_type(fspace, impl, dtype)

    grid = uniform_sampling(fspace.domain, nsamples, as_midp=True)

    weighting = kwargs.pop('weighting', 'simple')
    weighting_ = weighting.lower()
    if weighting_ not in ('simple', 'consistent'):
        raise ValueError('weighting {!r} not understood.'.format(weighting))

    if weighting_ == 'simple':
        csize = grid.stride
        idcs = np.where(csize == 0)
        csize[idcs] = fspace.domain.size[idcs]
        weight = np.prod(csize)
    else:  # weighting_ == 'consistent'
        # TODO: implement
        raise NotImplementedError

    if dtype is not None:
        dspace = ds_type(grid.ntotal, dtype=dtype, weight=weight,
                         exponent=exponent)
    else:
        dspace = ds_type(grid.ntotal, weight=weight, exponent=exponent)

    order = kwargs.pop('order', 'C')

    return DiscreteLp(fspace, grid, dspace, exponent=exponent, interp=interp,
                      order=order)
Exemple #4
0
def uniform_discr_frompartition(partition, exponent=2.0, interp='nearest',
                                impl='numpy', **kwargs):
    """Discretize an Lp function space given a uniform partition.

    Parameters
    ----------
    partition : `RectPartition`
        Regular (uniform) partition to be used for discretization
    exponent : positive `float`, optional
        The parameter ``p`` in ``L^p``. If the exponent is not
        equal to the default 2.0, the space has no inner product.
    interp : `str` or `sequence` of `str`, optional
        Interpolation type to be used for discretization.
        A sequence is interpreted as interpolation scheme per axis.

            'nearest' : use nearest-neighbor interpolation

            'linear' : use linear interpolation

    impl : {'numpy', 'cuda'}, optional
        Implementation of the data storage arrays

    Other Parameters
    ----------------
    order : {'C', 'F'}, optional
        Axis ordering in the data storage. Default: 'C'
    dtype : dtype
        Data type for the discretized space

            Default for 'numpy': 'float64' / 'complex128'

            Default for 'cuda': 'float32'

    weighting : {'const', 'none'}, optional
        Weighting of the discretized space functions.

            'const' : weight is a constant, the cell volume (default)

            'none' : no weighting

    Returns
    -------
    discr : `DiscreteLp`
        The uniformly discretized function space

    Examples
    --------
    >>> from odl import uniform_partition
    >>> part = uniform_partition(0, 1, 10)
    >>> uniform_discr_frompartition(part)
    uniform_discr(0.0, 1.0, 10)

    See also
    --------
    uniform_discr : implicit uniform Lp discretization
    uniform_discr_fromspace : uniform Lp discretization from an existing
        function space
    odl.discr.partition.uniform_partition :
        partition of the function domain
    """
    if not isinstance(partition, RectPartition):
        raise TypeError('partition {!r} is not a RectPartition instance.'
                        ''.format(partition))
    if not partition.is_regular:
        raise ValueError('partition is not regular.')

    impl, impl_in = str(impl).lower(), impl
    if impl == 'numpy':
        dtype = np.dtype(kwargs.pop('dtype', 'float64'))
    elif impl == 'cuda':
        if not CUDA_AVAILABLE:
            raise ValueError('CUDA not available.')
        dtype = np.dtype(kwargs.pop('dtype', 'float32'))
    else:
        raise ValueError("implementation '{}' not understood.".format(impl_in))

    fspace = FunctionSpace(partition.set, out_dtype=dtype)
    ds_type = dspace_type(fspace, impl, dtype)

    order = kwargs.pop('order', 'C')

    weighting = kwargs.pop('weighting', 'const')
    weighting, weighting_in = str(weighting).lower(), weighting
    if weighting == 'none' or float(exponent) == float('inf'):
        weight = None
    elif weighting == 'const':
        weight = partition.cell_volume
    else:
        raise ValueError("weighting '{}' not understood.".format(weighting_in))

    if dtype is not None:
        dspace = ds_type(partition.size, dtype=dtype, weight=weight,
                         exponent=exponent)
    else:
        dspace = ds_type(partition.size, weight=weight, exponent=exponent)

    return DiscreteLp(fspace, partition, dspace, exponent, interp, order=order)
Exemple #5
0
def test_dspace_type_cuda():
    # Plain function set -> Ntuples-like
    fset = odl.FunctionSet(odl.Interval(0, 1), odl.Strings(2))
    assert dspace_type(fset, 'cuda') == odl.CudaNtuples
    assert dspace_type(fset, 'cuda', np.int) == odl.CudaNtuples

    # Real space
    rspc = odl.FunctionSpace(odl.Interval(0, 1), field=odl.RealNumbers())
    assert dspace_type(rspc, 'cuda') == odl.CudaFn
    assert dspace_type(rspc, 'cuda', np.float64) == odl.CudaFn
    assert dspace_type(rspc, 'cuda', np.int) == odl.CudaFn
    with pytest.raises(TypeError):
        dspace_type(rspc, 'cuda', np.complex)
    with pytest.raises(TypeError):
        dspace_type(rspc, 'cuda', np.dtype('<U2'))

    # Complex space (not implemented)
    cspc = odl.FunctionSpace(odl.Interval(0, 1), field=odl.ComplexNumbers())
    with pytest.raises(NotImplementedError):
        dspace_type(cspc, 'cuda')
    with pytest.raises(NotImplementedError):
        dspace_type(cspc, 'cuda', np.complex64)
    with pytest.raises(TypeError):
        dspace_type(cspc, 'cuda', np.float)
    with pytest.raises(TypeError):
        assert dspace_type(cspc, 'cuda', np.int)
Exemple #6
0
def test_dspace_type_numpy():
    # Plain function set -> Ntuples-like
    fset = odl.FunctionSet(odl.Interval(0, 1), odl.Strings(2))
    assert dspace_type(fset, 'numpy') == odl.Ntuples, None
    assert dspace_type(fset, 'numpy', np.int) == odl.Ntuples

    # Real space
    rspc = odl.FunctionSpace(odl.Interval(0, 1), field=odl.RealNumbers())
    assert dspace_type(rspc, 'numpy') == odl.Fn
    assert dspace_type(rspc, 'numpy', np.float32) == odl.Fn
    assert dspace_type(rspc, 'numpy', np.int) == odl.Fn
    with pytest.raises(TypeError):
        dspace_type(rspc, 'numpy', np.complex)
    with pytest.raises(TypeError):
        dspace_type(rspc, 'numpy', np.dtype('<U2'))

    # Complex space
    cspc = odl.FunctionSpace(odl.Interval(0, 1), field=odl.ComplexNumbers())
    assert dspace_type(cspc, 'numpy') == odl.Fn
    assert dspace_type(cspc, 'numpy', np.complex64) == odl.Fn
    with pytest.raises(TypeError):
        dspace_type(cspc, 'numpy', np.float)
    with pytest.raises(TypeError):
        assert dspace_type(cspc, 'numpy', np.int)
    with pytest.raises(TypeError):
        dspace_type(cspc, 'numpy', np.dtype('<U2'))