Ejemplo n.º 1
0
def test_quantize():
    qpath = 'file:///tmp/removeme/quantized/'

    delete_layer()
    delete_layer(qpath)

    cf, _ = create_layer(size=(256,256,128,3), offset=(0,0,0), layer_type="affinities")
    cv = CloudVolume(cf.cloudpath)

    shape = (128, 128, 64)
    slices = np.s_[ :shape[0], :shape[1], :shape[2], :1 ]

    data = cv[slices]
    data *= 255.0
    data = data.astype(np.uint8)

    task = partial(QuantizeTask,
        source_layer_path=cf.cloudpath,
        dest_layer_path=qpath,
        shape=shape,
        offset=(0,0,0),
        mip=0,
    )

    info = create_quantized_affinity_info(
        cf.cloudpath, qpath, shape, 
        mip=0, chunk_size=[64,64,64], encoding='raw'
    )
    qcv = CloudVolume(qpath, info=info)
    qcv.commit_info()

    create_downsample_scales(qpath, mip=0, ds_shape=shape)

    task()

    qcv.mip = 0

    qdata = qcv[slices]

    assert np.all(data.shape == qdata.shape)
    assert np.all(data == qdata)
    assert data.dtype == np.uint8
Ejemplo n.º 2
0
def create_transfer_tasks(
    src_layer_path: str,
    dest_layer_path: str,
    chunk_size: ShapeType = None,
    shape: ShapeType = None,
    fill_missing: bool = False,
    translate: ShapeType = None,
    bounds: Optional[Bbox] = None,
    mip: int = 0,
    preserve_chunk_size: bool = True,
    encoding=None,
    skip_downsamples: bool = False,
    delete_black_uploads: bool = False,
    background_color: int = 0,
    agglomerate: bool = False,
    timestamp: Optional[int] = None,
    compress: Union[str, bool] = 'gzip',
    factor: ShapeType = None,
    sparse: bool = False,
    dest_voxel_offset: ShapeType = None,
    memory_target: int = MEMORY_TARGET,
    max_mips: int = 5,
    clean_info: bool = False,
    no_src_update: bool = False,
    bounds_mip: int = 0,
) -> Iterator:
    """
  Transfer data to a new data layer. You can use this operation
  to make changes to the dataset representation as well. For 
  example, you can change the chunk size, compression, bounds,
  and offset.

  Downsamples will be automatically generated while transferring
  unless skip_downsamples is set. The number of downsamples will
  be determined by the chunk size and the task shape.

  bounds: Bbox specified in terms of the destination image and its
    highest resolution.
  translate: Vec3 pointing from source bounds to dest bounds
    and is in terms of the highest resolution of the source image.
    This allows you to compensate for differing voxel offsets
    or enables you to move part of the image to a new location.
  dest_voxel_offset: When creating a new image, move the 
    global coordinate origin to this point. This is commonly
    used to "zero" a newly aligned image (e.g. (0,0,0)) 

  background_color: Designates which color should be considered background.
  chunk_size: (overrides preserve_chunk_size) force chunk size for new layers to be this.
  clean_info: scrub additional fields from the info file that might interfere
    with later processing (e.g. mesh and skeleton related info).
  compress: None, 'gzip', or 'br' Determines which compression algorithm to use 
    for new uploaded files.
  delete_black_uploads: issue delete commands instead of upload chunks
    that are all background.
  encoding: "raw", "jpeg", "compressed_segmentation", "compresso", "fpzip", or "kempressed"
    depending on which kind of data you're dealing with. raw works for everything (no compression) 
    but you might get better compression with another encoding. You can think of encoding as the
    image type-specific first stage of compression and the "compress" flag as the data
    agnostic second stage compressor. For example, compressed_segmentation and gzip work
    well together, but not jpeg and gzip.
  factor: (overrides axis) can manually specify what each downsampling round is
    supposed to do: e.g. (2,2,1), (2,2,2), etc
  fill_missing: Treat missing image tiles as zeroed for both src and dest.
  max_mips: (pairs with memory_target) maximum number of downsamples to generate even
    if the memory budget is large enough for more.
  memory_target: given a task size in bytes, pick the task shape that will produce the 
    maximum number of downsamples. Only works for (2,2,1) or (2,2,2).
  no_src_update: don't update the source's provenance file
  preserve_chunk_size: if true, maintain chunk size of starting mip, else, find the closest
    evenly divisible chunk size to 64,64,64 for this shape and use that. The latter can be
    useful when mip 0 uses huge chunks and you want to simply visualize the upper mips.
  shape: (overrides memory_target) The 3d size of each task. Choose a shape that meets 
    the following criteria unless you're doing something out of the ordinary.
    (a) 2^n multiple of destination chunk size (b) doesn't consume too much memory
    (c) n is related to the downsample factor for each axis, so for a factor of (2,2,1) (default)
      z only needs to be a single chunk, but x and y should be 2, 4, 8,or 16 times the chunk size.
    Remember to multiply 4/3 * shape.x * shape.y * shape.z * data_type to estimate how much memory 
    each task will require. If downsamples are off, you can skip the 4/3. In the future, if chunk
    sizes match we might be able to do a simple file transfer. The problem can be formulated as 
    producing the largest number of downsamples within a given memory target.

    EXAMPLE: destination is uint64 with chunk size (128, 128, 64) with a memory target of
      at most 3GB per task and a downsample factor of (2,2,1).

      The largest number of downsamples is 4 using 2048 * 2048 * 64 sized tasks which will
      use 2.9 GB of memory. The next size up would use 11.5GB and is too big. 

  sparse: When downsampling segmentation, if true, don't count black pixels when computing
    the mode. Useful for e.g. synapses and point labels.

  agglomerate: (graphene only) remap the watershed layer to a proofread segmentation.
  timestamp: (graphene only) integer UNIX timestamp indicating the proofreading state
    to represent.
  """
    src_vol = CloudVolume(src_layer_path, mip=mip)

    if dest_voxel_offset:
        dest_voxel_offset = Vec(*dest_voxel_offset, dtype=int)
    else:
        dest_voxel_offset = src_vol.voxel_offset.clone()

    if factor is None:
        factor = (2, 2, 1)

    if skip_downsamples:
        factor = (1, 1, 1)

    if not chunk_size:
        chunk_size = src_vol.info['scales'][mip]['chunk_sizes'][0]
    chunk_size = Vec(*chunk_size)

    try:
        dest_vol = CloudVolume(dest_layer_path, mip=mip)
    except cloudvolume.exceptions.InfoUnavailableError:
        info = copy.deepcopy(src_vol.info)
        dest_vol = CloudVolume(dest_layer_path, info=info, mip=mip)
        dest_vol.commit_info()

    if dest_voxel_offset is not None:
        dest_vol.scale["voxel_offset"] = dest_voxel_offset

    # If translate is not set, but dest_voxel_offset is then it should naturally be
    # only be the difference between datasets.
    if translate is None:
        translate = dest_vol.voxel_offset - src_vol.voxel_offset  # vector pointing from src to dest
    else:
        translate = Vec(*translate) // src_vol.downsample_ratio

    if encoding is not None:
        dest_vol.info['scales'][mip]['encoding'] = encoding
        if encoding == 'compressed_segmentation' and 'compressed_segmentation_block_size' not in dest_vol.info[
                'scales'][mip]:
            dest_vol.info['scales'][mip][
                'compressed_segmentation_block_size'] = (8, 8, 8)
    dest_vol.info['scales'] = dest_vol.info['scales'][:mip + 1]
    dest_vol.info['scales'][mip]['chunk_sizes'] = [chunk_size.tolist()]

    if clean_info:
        dest_vol.info = clean_xfer_info(dest_vol.info)

    dest_vol.commit_info()

    if shape is None:
        if memory_target is not None:
            shape = downsample_scales.downsample_shape_from_memory_target(
                np.dtype(src_vol.dtype).itemsize, dest_vol.chunk_size.x,
                dest_vol.chunk_size.y, dest_vol.chunk_size.z, factor,
                memory_target, max_mips)
        else:
            raise ValueError(
                "Either shape or memory_target must be specified.")

    shape = Vec(*shape)

    if factor[2] == 1:
        shape.z = int(dest_vol.chunk_size.z *
                      round(shape.z / dest_vol.chunk_size.z))

    if not skip_downsamples:
        downsample_scales.create_downsample_scales(
            dest_layer_path,
            mip=mip,
            ds_shape=shape,
            preserve_chunk_size=preserve_chunk_size,
            encoding=encoding)

    dest_bounds = get_bounds(dest_vol,
                             bounds,
                             mip,
                             bounds_mip=bounds_mip,
                             chunk_size=chunk_size)

    class TransferTaskIterator(FinelyDividedTaskIterator):
        def task(self, shape, offset):
            return partial(
                TransferTask,
                src_path=src_layer_path,
                dest_path=dest_layer_path,
                shape=shape.clone(),
                offset=offset.clone(),
                fill_missing=fill_missing,
                translate=translate,
                mip=mip,
                skip_downsamples=skip_downsamples,
                delete_black_uploads=bool(delete_black_uploads),
                background_color=background_color,
                agglomerate=agglomerate,
                timestamp=timestamp,
                compress=compress,
                factor=factor,
                sparse=sparse,
            )

        def on_finish(self):
            job_details = {
                'method': {
                    'task':
                    'TransferTask',
                    'src':
                    src_layer_path,
                    'dest':
                    dest_layer_path,
                    'shape':
                    list(map(int, shape)),
                    'fill_missing':
                    fill_missing,
                    'translate':
                    list(map(int, translate)),
                    'skip_downsamples':
                    skip_downsamples,
                    'delete_black_uploads':
                    bool(delete_black_uploads),
                    'background_color':
                    background_color,
                    'bounds':
                    [dest_bounds.minpt.tolist(),
                     dest_bounds.maxpt.tolist()],
                    'mip':
                    mip,
                    'agglomerate':
                    bool(agglomerate),
                    'timestamp':
                    timestamp,
                    'compress':
                    compress,
                    'encoding':
                    encoding,
                    'memory_target':
                    memory_target,
                    'factor': (tuple(factor) if factor else None),
                    'sparse':
                    bool(sparse),
                },
                'by': operator_contact(),
                'date': strftime('%Y-%m-%d %H:%M %Z'),
            }

            dest_vol = CloudVolume(dest_layer_path)
            dest_vol.provenance.sources = [src_layer_path]
            dest_vol.provenance.processing.append(job_details)
            dest_vol.commit_provenance()

            if not no_src_update and src_vol.meta.path.protocol in ('gs', 's3',
                                                                    'file'):
                src_vol.provenance.processing.append(job_details)
                src_vol.commit_provenance()

    return TransferTaskIterator(dest_bounds, shape)
Ejemplo n.º 3
0
def create_contrast_normalization_tasks(src_path,
                                        dest_path,
                                        levels_path=None,
                                        shape=None,
                                        mip=0,
                                        clip_fraction=0.01,
                                        fill_missing=False,
                                        translate=(0, 0, 0),
                                        minval=None,
                                        maxval=None,
                                        bounds=None,
                                        bounds_mip=0):
    """
  Use the output of luminence levels to contrast
  correct the image by stretching the histogram
  to cover the full range of the data type.
  """
    srcvol = CloudVolume(src_path, mip=mip)

    try:
        dvol = CloudVolume(dest_path, mip=mip)
    except Exception:  # no info file
        info = copy.deepcopy(srcvol.info)
        dvol = CloudVolume(dest_path, mip=mip, info=info)
        dvol.info['scales'] = dvol.info['scales'][:mip + 1]
        dvol.commit_info()

    if bounds is None:
        bounds = srcvol.bounds.clone()

    if shape is None:
        shape = Bbox((0, 0, 0), (2048, 2048, 64))
        shape = shape.shrink_to_chunk_size(dvol.underlying).size3()
        shape = Vec.clamp(shape, (1, 1, 1), bounds.size3())

    shape = Vec(*shape)

    downsample_scales.create_downsample_scales(dest_path,
                                               mip=mip,
                                               ds_shape=shape,
                                               preserve_chunk_size=True)
    dvol.refresh_info()

    bounds = get_bounds(srcvol, bounds, mip, bounds_mip=bounds_mip)

    class ContrastNormalizationTaskIterator(FinelyDividedTaskIterator):
        def task(self, shape, offset):
            return ContrastNormalizationTask(
                src_path=src_path,
                dest_path=dest_path,
                levels_path=levels_path,
                shape=shape.clone(),
                offset=offset.clone(),
                clip_fraction=clip_fraction,
                mip=mip,
                fill_missing=fill_missing,
                translate=translate,
                minval=minval,
                maxval=maxval,
            )

        def on_finish(self):
            dvol.provenance.processing.append({
                'method': {
                    'task': 'ContrastNormalizationTask',
                    'src_path': src_path,
                    'dest_path': dest_path,
                    'shape': Vec(*shape).tolist(),
                    'clip_fraction': clip_fraction,
                    'mip': mip,
                    'translate': Vec(*translate).tolist(),
                    'minval': minval,
                    'maxval': maxval,
                    'bounds': [bounds.minpt.tolist(),
                               bounds.maxpt.tolist()],
                },
                'by':
                operator_contact(),
                'date':
                strftime('%Y-%m-%d %H:%M %Z'),
            })
            dvol.commit_provenance()

    return ContrastNormalizationTaskIterator(bounds, shape)
Ejemplo n.º 4
0
def create_downsampling_tasks(layer_path,
                              mip=0,
                              fill_missing=False,
                              axis='z',
                              num_mips=5,
                              preserve_chunk_size=True,
                              sparse=False,
                              bounds=None,
                              chunk_size=None,
                              encoding=None,
                              delete_black_uploads=False,
                              background_color=0,
                              dest_path=None,
                              compress=None,
                              factor=None,
                              bounds_mip=0):
    """
    mip: Download this mip level, writes to mip levels greater than this one.
    fill_missing: interpret missing chunks as black instead of issuing an EmptyVolumeException
    axis: technically 'x' and 'y' are supported, but no one uses them.
    num_mips: download a block chunk * 2**num_mips size and generate num_mips mips. If you have
      memory problems, try reducing this number.
    preserve_chunk_size: if true, maintain chunk size of starting mip, else, find the closest
      evenly divisible chunk size to 64,64,64 for this shape and use that. The latter can be
      useful when mip 0 uses huge chunks and you want to simply visualize the upper mips.
    chunk_size: (overrides preserve_chunk_size) force chunk size for new layers to be this.
    sparse: When downsampling segmentation, if true, don't count black pixels when computing
      the mode. Useful for e.g. synapses and point labels.
    bounds: By default, downsample everything, but you can specify restricted bounding boxes
      instead. The bounding box will be expanded to the nearest chunk. Bbox is specifed in mip 0
      coordinates.
    delete_black_uploads: issue delete commands instead of upload chunks
      that are all background.
    background_color: Designates which color should be considered background.
    dest_path: (optional) instead of writing downsamples to the existing 
      volume, write them somewhere else. This can be useful e.g. if someone 
      doesn't want you to touch the existing info file.
    compress: None, 'gzip', or 'br' Determines which compression algorithm to use 
      for new uploaded files.
    factor: (overrides axis) can manually specify what each downsampling round is
      supposed to do: e.g. (2,2,1), (2,2,2), etc
    """
    def ds_shape(mip, chunk_size=None, factor=None):
        if chunk_size:
            shape = Vec(*chunk_size)
        else:
            shape = vol.meta.chunk_size(mip)[:3]

        if factor is None:
            factor = downsample_scales.axis_to_factor(axis)

        shape.x *= factor[0]**num_mips
        shape.y *= factor[1]**num_mips
        shape.z *= factor[2]**num_mips
        return shape

    vol = CloudVolume(layer_path, mip=mip)
    shape = ds_shape(mip, chunk_size, factor)

    vol = downsample_scales.create_downsample_scales(
        layer_path,
        mip,
        shape,
        preserve_chunk_size=preserve_chunk_size,
        chunk_size=chunk_size,
        encoding=encoding,
        factor=factor)

    if not preserve_chunk_size or chunk_size:
        shape = ds_shape(mip + 1, chunk_size, factor)

    bounds = get_bounds(
        vol,
        bounds,
        mip,
        bounds_mip=bounds_mip,
        chunk_size=vol.chunk_size,
    )

    class DownsampleTaskIterator(FinelyDividedTaskIterator):
        def task(self, shape, offset):
            return partial(
                DownsampleTask,
                layer_path=layer_path,
                mip=vol.mip,
                shape=shape.clone(),
                offset=offset.clone(),
                axis=axis,
                fill_missing=fill_missing,
                sparse=sparse,
                delete_black_uploads=delete_black_uploads,
                background_color=background_color,
                dest_path=dest_path,
                compress=compress,
                factor=factor,
            )

        def on_finish(self):
            vol.provenance.processing.append({
                'method': {
                    'task':
                    'DownsampleTask',
                    'mip':
                    mip,
                    'num_mips':
                    num_mips,
                    'shape':
                    shape.tolist(),
                    'axis':
                    axis,
                    'method':
                    'downsample_with_averaging' if vol.layer_type == 'image'
                    else 'downsample_segmentation',
                    'sparse':
                    sparse,
                    'bounds':
                    str(bounds),
                    'chunk_size': (list(chunk_size) if chunk_size else None),
                    'preserve_chunk_size':
                    preserve_chunk_size,
                    'encoding':
                    encoding,
                    'fill_missing':
                    bool(fill_missing),
                    'delete_black_uploads':
                    bool(delete_black_uploads),
                    'background_color':
                    background_color,
                    'dest_path':
                    dest_path,
                    'compress':
                    compress,
                    'factor': (tuple(factor) if factor else None),
                },
                'by':
                operator_contact(),
                'date':
                strftime('%Y-%m-%d %H:%M %Z'),
            })
            vol.commit_provenance()

    return DownsampleTaskIterator(bounds, shape)