Beispiel #1
0
def as_array_access(ndarray, volatile=False):
    scyjava.start_jvm()
    if ndarray.dtype == np.uint8 or ndarray.dtype == np.int8:
        return _as_array_access(
            ndarray, ByteUnsafe, lambda n: VolatileByteArray(n, True)
            if volatile else ByteArray(n))
    elif ndarray.dtype == np.uint16 or ndarray.dtype == np.int16:
        return _as_array_access(
            ndarray, ShortUnsafe, lambda n: VolatileShortArray(n, True)
            if volatile else ShortArray(n))
    elif ndarray.dtype == np.uint32 or ndarray.dtype == np.int32:
        return _as_array_access(
            ndarray, IntUnsafe, lambda n: VolatileIntArray(n, True)
            if volatile else IntArray(n))
    elif ndarray.dtype == np.uint64 or ndarray.dtype == np.int64:
        return _as_array_access(
            ndarray, LongUnsafe, lambda n: VolatileLongArray(n, True)
            if volatile else LongArray(n))
    elif ndarray.dtype == np.float32:
        return _as_array_access(
            ndarray, FloatUnsafe, lambda n: VolatileFloatArray(n, True)
            if volatile else FloatArray(n))
    elif ndarray.dtype == np.float64:
        return _as_array_access(
            ndarray, DoubleUnsafe, lambda n: VolatileDoubleArray(n, True)
            if volatile else DoubleArray(n))
Beispiel #2
0
def for_np_dtype(dtype, volatile=False):
    scyjava.start_jvm()
    if dtype == np.uint8:
        return VolatileUnsignedByteType() if volatile else UnsignedByteType()
    if dtype == np.int8:
        return VolatileByteType() if volatile else ByteType()

    if dtype == np.uint16:
        return VolatileUnsignedShortType() if volatile else UnsignedShortType()
    if dtype == np.int16:
        return VolatileShortType() if volatile else ShortType()

    if dtype == np.uint32:
        return VolatileUnsignedIntType() if volatile else UnsignedIntType()
    if dtype == np.int32:
        return VolatileIntType() if volatile else IntType()

    if dtype == np.uint64:
        return VolatileUnsignedLongType() if volatile else UnsignedLongType()
    if dtype == np.int64:
        return VolatileLongType() if volatile else LongType()

    if dtype == np.float32:
        return VolatileFloatType() if volatile else FloatType()
    if dtype == np.float64:
        return VolatileDoubleType() if volatile else DoubleType()
Beispiel #3
0
def sj_fixture(request):
    """
    Start the JVM through scyjava once for the whole test environment
    :param request: Pytest variable passed in to fixtures
    """
    scyjava.start_jvm()

    yield scyjava
Beispiel #4
0
def get_address(rai):
    scyjava.start_jvm()
    class_name = util.Helpers.classNameSimple(rai)
    class_name_full = util.Helpers.className(rai)
    if class_name in ('ArrayImg', 'UnsafeImg'):
        access = jpype.JObject(class_name_full, rai).update(None)
        access_type = util.Helpers.className(access)

        if 'basictypelongaccess.unsafe' in access_type:
            return jpype.JObject(access_type, access).getAddress()
        else:
            raise ValueError("Excpected unsafe access but got {}".format(access_type))

    else:
        raise ValueError("Excpected ArrayImg or UnsafeImg but got {}".format(class_name))
Beispiel #5
0
def as_cell_img(array,
                chunk_shape,
                cache,
                *,
                access_type='native',
                chunk_as_array=identity,
                **kwargs):
    """
    Wrap an arbitrary ndarray-like object as an ImgLib2 cached cell img.

    :param array: The arbitrary ndarray-like object to be wrapped
    :param chunk_shape: The shape of `array`. In many cases, this is just `array.shape`.
    :param cache: Can be `int` or an ImgLib2 `LoaderCache`. If `int` (recommended), use a
                :py:data:`imglyb.caches.BoundedSoftRefLoaderCache` that is bounded to `cache` elements.
                `LoaderCache`s are available in :py:mod:`imglyb.caches`.
    :param access_type: Can be either `'native'` or `'array'`. If `'native'`, use the native memory of the contiguous
                ndarray of a chunk directly. If `'array'`, copy the native memory into a Java array and use the Java
                array as access.
    :param chunk_as_array: Defines conversion of a chunk created by slicing into a :py:class:`numpy.ndarray`.
    :param kwargs: Optional arguments that may depend on the value passed for `access_type`, e.g `use_volatile_access`
                is relevant only for `access_type == 'array'`.
    :return: A tuple that holds the wrapped image at `0` and a reference store at `1` to ensure that Python references
                are not being garbage collected while still in use in the JVM. the reference store should stay in scope
                as long as the wrapped image is intended to be used.
    """
    scyjava.start_jvm()

    access_type_function_mapping = {
        'array': as_cell_img_with_array_accesses,
        'native': as_cell_img_with_native_accesses
    }

    if access_type not in access_type_function_mapping:
        raise Exception(
            f'Invalid access type: `{access_type}\'. Choose one of {access_type_function_mapping.keys()}'
        )

    cache = caches.BoundedSoftRefLoaderCache(cache) if isinstance(
        cache, int) else cache

    return access_type_function_mapping[access_type](array, chunk_shape,
                                                     chunk_as_array, cache,
                                                     **kwargs)
Beispiel #6
0
def as_cell_img_with_array_accesses(array,
                                    chunk_shape,
                                    chunk_as_array,
                                    cache,
                                    *,
                                    use_volatile_access=True,
                                    **kwargs):
    scyjava.start_jvm()

    access_generator = MakeAccessFunction(
        lambda index: _get_chunk_access_array(array,
                                              chunk_shape,
                                              index,
                                              chunk_as_array,
                                              use_volatile_access=
                                              use_volatile_access))
    reference_store = ReferenceStore()
    reference_store.add_reference_with_new_id(access_generator)

    shape = array.shape[::-1]
    chunk_shape = chunk_shape[::-1]

    # TODO use imgFromFunc instead of imgWithCellLoaderFromFunct here
    img = PythonHelpers.imgWithCellLoaderFromFunc(
        shape,
        chunk_shape,
        access_generator,
        types.for_np_dtype(array.dtype, volatile=False),
        # TODO do not load first block here, just create a length-one access
        accesses.as_array_access(_get_chunk(array,
                                            chunk_shape,
                                            0,
                                            chunk_as_array=chunk_as_array),
                                 volatile=use_volatile_access),
        cache)

    return img, reference_store
Beispiel #7
0
def as_cell_img_with_native_accesses(array, chunk_shape, chunk_as_array, cache,
                                     **kwargs):
    scyjava.start_jvm()

    reference_store = ReferenceStore()
    access_generator = MakeAccessFunction(
        lambda index: _get_chunk_access_unsafe(
            array, chunk_shape, index, chunk_as_array, reference_store))
    reference_store.add_reference_with_new_id(access_generator)

    shape = array.shape[::-1]
    chunk_shape = chunk_shape[::-1]

    try:
        img = PythonHelpers.imgFromFunc(
            shape, chunk_shape, access_generator,
            types.for_np_dtype(array.dtype, volatile=False),
            _access_factory_for(array.dtype, owning=False)(1, None), cache)

    except JException as e:
        _logger.error(jstacktrace(e))
        raise e

    return img, reference_store
Beispiel #8
0
def to_imglib_argb(source):
    scyjava.start_jvm()
    return ReferenceGuardingRandomAccessibleInterval(_to_imglib_argb(source),
                                                     ReferenceGuard(source))
Beispiel #9
0
def to_numpy(source):
    scyjava.start_jvm()
    return _ImgLibReferenceGuard(source)
Beispiel #10
0
import imglyb
import numpy as np
import scyjava

scyjava.start_jvm()

Views = imglyb.util.Views

shape = (3, 5)
data = np.arange(np.prod(shape)).reshape(shape)
block_size = (2, 2)
img, _ = imglyb.as_cell_img(data, block_size, access_type='native', cache=1)

print(data)
print(img.toString())
cursor = Views.flatIterable(img).cursor()

print('Cell Img')
while cursor.hasNext():
    print(cursor.next().toString())

print()
print('ndarray')
for d in data.flat:
    print(d)
print(data)

print()
print('cells')
cursor = img.getCells().cursor()
cellIdx = 0