Exemple #1
0
    def __init__(self,
                 output_path: str,
                 output_format: str,
                 mip: int = None,
                 voxel_size: tuple = (1, 1, 1),
                 simplification_factor: int = 100,
                 max_simplification_error: int = 8,
                 manifest: bool = False,
                 shard: bool = False,
                 name: str = 'mesh'):
        """
        Parameters
        ------------
        output_path:
            path to store mesh files
        output_format:
            format of output {'ply', 'obj', 'precomputed'}
        voxel_size:
            size of voxels
        simplification_factor:
            mesh simplification factor.
        max_simplification_error:
            maximum tolerance error of meshing.
        manifest:
            create manifest files or not. This should 
            not be True if you are only doing meshing for a segmentation chunk.
        name: 
            operator name.

        Note that some functions are adopted from igneous.
        """
        super().__init__(name=name)
        self.simplification_factor = simplification_factor
        self.max_simplification_error = max_simplification_error
        # zmesh use fortran order, translate zyx to xyz
        self.output_path = output_path
        self.output_format = output_format
        self.manifest = manifest
        self.shard = shard

        if manifest:
            assert output_format == 'precomputed'

        if output_format == 'precomputed':
            # adjust the mesh path according to info
            vol = CloudVolume(self.output_path, mip)
            info = vol.info
            if 'mesh' not in info:
                # add mesh to info and update it
                info['mesh'] = 'mesh_err_{}'.format(max_simplification_error)
                vol.info = info
                vol.commit_info()
            self.mesh_path = os.path.join(output_path, info['mesh'])
            self.voxel_size = vol.resolution[::-1]
            self.mesher = Mesher( vol.resolution )
        else: 
            self.mesh_path = output_path
            self.mesher = Mesher(voxel_size[::-1])

        self.storage = CloudFiles(self.mesh_path)
Exemple #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)
Exemple #3
0
    def __init__(self,
                 output_path: str,
                 output_format: str,
                 mip: int = None,
                 voxel_size: tuple = None,
                 simplification_factor: int = 100,
                 max_simplification_error: int = 8,
                 dust_threshold: int = None,
                 ids: set = None,
                 manifest: bool = False,
                 name: str = 'meshing',
                 verbose: bool = True):
        """
        Parameters
        ------------
        output_path: 
            path to store mesh files
        output_format: 
            format of output {'ply', 'obj', 'precomputed'}
        voxel_size:
            size of voxels
        simplification_factor:
            mesh simplification factor.
        max_simplification_error:
            maximum tolerance error of meshing.
        dust_threshold:
            do not mesh tiny objects with voxel number less than threshold
        ids:
            only mesh the selected segmentation ids, other segments will not be meshed.
        manifest:
            create manifest files or not. This should 
            not be True if you are only doing meshing for a segmentation chunk.
        name: 
            operator name.
        verbose:
            print out informations or not.

        Note that some functions are adopted from igneous.
        """
        super().__init__(name=name, verbose=verbose)
        self.simplification_factor = simplification_factor
        self.max_simplification_error = max_simplification_error
        # zmesh use fortran order, translate zyx to xyz
        self.output_path = output_path
        self.output_format = output_format
        self.dust_threshold = dust_threshold
        self.ids = ids
        self.manifest = manifest

        if manifest:
            assert output_format == 'precomputed'

        mesh_path = output_path

        if output_format == 'precomputed':
            # adjust the mesh path according to info
            vol = CloudVolume(self.output_path, mip)
            info = vol.info
            if 'mesh' not in info:
                # add mesh to info and update it
                info['mesh'] = 'mesh_err_{}'.format(max_simplification_error)
                vol.info = info
                vol.commit_info()
            mesh_path = os.path.join(output_path, info['mesh'])
            self.voxel_size = vol.resolution[::-1]
            self.mesher = Mesher(vol.resolution)
        else:
            self.mesher = Mesher(voxel_size[::-1])

        self.storage = Storage(mesh_path)
Exemple #4
0
def create_image_shard_transfer_tasks(
        src_layer_path: str,
        dst_layer_path: str,
        mip: int = 0,
        chunk_size: Optional[ShapeType] = None,
        encoding: bool = None,
        bounds: Optional[Bbox] = None,
        bounds_mip: int = 0,
        fill_missing: bool = False,
        translate: ShapeType = (0, 0, 0),
        dest_voxel_offset: Optional[ShapeType] = None,
        agglomerate: bool = False,
        timestamp: int = None,
        memory_target: int = MEMORY_TARGET,
        clean_info: bool = False):
    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 not chunk_size:
        chunk_size = src_vol.info['scales'][mip]['chunk_sizes'][0]
    chunk_size = Vec(*chunk_size)

    try:
        dest_vol = CloudVolume(dst_layer_path, mip=mip)
    except cloudvolume.exceptions.InfoUnavailableError:
        info = copy.deepcopy(src_vol.info)
        dest_vol = CloudVolume(dst_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()]

    spec = create_sharded_image_info(
        dataset_size=dest_vol.scale["size"],
        chunk_size=dest_vol.scale["chunk_sizes"][0],
        encoding=dest_vol.scale["encoding"],
        dtype=dest_vol.dtype,
        uncompressed_shard_bytesize=memory_target,
    )
    dest_vol.scale["sharding"] = spec
    if clean_info:
        dest_vol.info = clean_xfer_info(dest_vol.info)
    dest_vol.commit_info()

    shape = image_shard_shape_from_spec(spec, dest_vol.scale["size"],
                                        chunk_size)

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

    class ImageShardTransferTaskIterator(FinelyDividedTaskIterator):
        def task(self, shape, offset):
            return partial(
                ImageShardTransferTask,
                src_layer_path,
                dst_layer_path,
                shape=shape,
                offset=offset,
                fill_missing=fill_missing,
                translate=translate,
                mip=mip,
                agglomerate=agglomerate,
                timestamp=timestamp,
            )

        def on_finish(self):
            job_details = {
                "method": {
                    "task": "ImageShardTransferTask",
                    "src": src_layer_path,
                    "dest": dst_layer_path,
                    "shape": list(map(int, shape)),
                    "fill_missing": fill_missing,
                    "translate": list(map(int, translate)),
                    "bounds": [bounds.minpt.tolist(),
                               bounds.maxpt.tolist()],
                    "mip": mip,
                },
                "by": operator_contact(),
                "date": strftime("%Y-%m-%d %H:%M %Z"),
            }

            dvol = CloudVolume(dst_layer_path)
            dvol.provenance.sources = [src_layer_path]
            dvol.provenance.processing.append(job_details)
            dvol.commit_provenance()

    return ImageShardTransferTaskIterator(bounds, shape)