diff --git a/README.md b/README.md index 663d51c0..e0a0dcbe 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ # CloudVolume: IO for Neuroglancer Datasets ```python -from cloudvolume import CloudVolume +from cloudvolume import CloudVolume, from_cloudpath, Bbox vol = CloudVolume('gs://mylab/mouse/image', parallel=True, progress=True) image = vol[:,:,:] # Download a whole image stack into a numpy array from the cloud @@ -12,6 +12,9 @@ vol[:,:,:] = image # Upload an entire image stack from a numpy array to the clou label = 1 mesh = vol.mesh.get(label) skel = vol.skeleton.get(label) + +asrc = from_cloudpath("gs://mylab/mouse/annotation/synapses") +annotations = asrc.get(label) ``` CloudVolume is a serverless Python client for random access reading and writing of [Neuroglancer](https://github.com/google/neuroglancer/) volumes in "[Precomputed](https://github.com/google/neuroglancer/tree/master/src/datasource/precomputed#readme)" format, a set of representations for arbitrarily large volumetric images, meshes, and skeletons. CloudVolume is typically paired with [Igneous](https://github.com/seung-lab/igneous), a Kubernetes compatible system for generating image hierarchies, meshes, skeletons, and other dependency free jobs that can be applied to petavoxel scale images. @@ -344,6 +347,22 @@ skel = skel.average_smoothing(3) # rolling average, n=3 skel1 == skel2 # check if contents of internal arrays match Skeleton.equivalent(skel1, skel2) # ...even if there are differences like differently numbered edges +# Annotations +import cloudvolume + +asrc = cloudvolume.from_cloudpath("gs://mybucket/retina/annotations", cache=True, progress=True, mip=3) + +print(asrc.summary()) # get basic info about annotation set + +annotations = asrc.get([1,2,3,]) # tries to interpret input to mean get_by_id or get_by_bbox +annotations = asrc.get_by_id([1,2,3,]) +annotations = asrc.get(bbox, mip=3) +annotations = asrc.get_all() +annotations = asrc.get_by_bbox(bbox, mip=3) +annotations = asrc[bbox] # can use slice notation +annotations = asrc.get_by_relationship("synapses", 1231) +ids = asrc.ids() + # Parallel Operation vol = CloudVolume('gs://mybucket/retina/image', parallel=True) # Use all cores vol.parallel = 4 # e.g. any number > 1, use this many cores @@ -709,7 +728,7 @@ Python 2.7 is no longer supported by CloudVolume. Updated versions of `pip` will Thank you to everyone that has contributed past or current to CloudVolume or the ecosystem it serves. We love you! -Jeremy Maitin-Shepard created [Neuroglancer](https://github.com/google/neuroglancer) and defined the Precomputed format. Yann Leprince provided a [pure Python codec](https://github.com/HumanBrainProject/neuroglancer-scripts) for the compressed_segmentation format. Jeremy Maitin-Shepard and Stephen Plaza created C++ code defining the compression and decompression (respectively) protocol for [compressed_segmentation](https://github.com/janelia-flyem/compressedseg). Peter Lindstrom et al. created [the fpzip algorithm](https://computation.llnl.gov/projects/floating-point-compression), and contributed a C++ implementation and advice. Nico Kemnitz adapted our data to fpzip using the "Kempression" protocol (we named it, not him). Dan Bumbarger contributed code and information helpful for getting CloudVolume working on Windows. Fredrik Kihlander's [pure python implementation](https://github.com/wc-duck/pymmh3) of murmurhash3 and [Austin Appleby](https://github.com/aappleby/smhasher) developed murmurhash3 which is necessary for the sharded format. Ben Falk advocated for and did the bulk of the work on brotli compression. Some of the ideas in CloudVolume are based on work by Jingpeng Wu in [BigArrays.jl](https://github.com/seung-lab/BigArrays.jl). Sven Dorkenwald, Manuel Castro, and Akhilesh Halageri contributed advice and code towards implementing the graphene interface. Oluwaseun Ogedengbe contributed documentation for the sharded format. Eric Perlman wrote the reader for Neuroglancer Multi-LOD meshes. Ignacio Tartavull and William Silversmith wrote the initial version of CloudVolume. +Jeremy Maitin-Shepard created [Neuroglancer](https://github.com/google/neuroglancer) and defined the Precomputed format. Yann Leprince provided a [pure Python codec](https://github.com/HumanBrainProject/neuroglancer-scripts) for the compressed_segmentation format. Jeremy Maitin-Shepard and Stephen Plaza created C++ code defining the compression and decompression (respectively) protocol for [compressed_segmentation](https://github.com/janelia-flyem/compressedseg). Peter Lindstrom et al. created [the fpzip algorithm](https://computation.llnl.gov/projects/floating-point-compression), and contributed a C++ implementation and advice. Nico Kemnitz adapted our data to fpzip using the "Kempression" protocol (we named it, not him). Dan Bumbarger contributed code and information helpful for getting CloudVolume working on Windows. Fredrik Kihlander's [pure python implementation](https://github.com/wc-duck/pymmh3) of murmurhash3 and [Austin Appleby](https://github.com/aappleby/smhasher) developed murmurhash3 which is necessary for the sharded format. Ben Falk advocated for and did the bulk of the work on brotli compression. Some of the ideas in CloudVolume are based on work by Jingpeng Wu in [BigArrays.jl](https://github.com/seung-lab/BigArrays.jl). Sven Dorkenwald, Manuel Castro, and Akhilesh Halageri contributed advice and code towards implementing the graphene interface. Oluwaseun Ogedengbe contributed documentation for the sharded format. Eric Perlman wrote the reader for Neuroglancer Multi-LOD meshes. Forrest Collman and Jeremy Maitin-Shepard both wrote the versions of the annotations service that was then adapted to CloudVolume by William Silversmith. Ignacio Tartavull and William Silversmith wrote the initial version of CloudVolume. ## Citation Please cite the Igneous paper if you used this package in your research: diff --git a/cloudvolume/__init__.py b/cloudvolume/__init__.py index ae99ffe8..74e21cbc 100644 --- a/cloudvolume/__init__.py +++ b/cloudvolume/__init__.py @@ -46,7 +46,7 @@ skel = vol.skeletons.get(label) """ -from .cloudvolume import CloudVolume, register_plugin +from .cloudvolume import CloudVolume, from_cloudpath, register_plugin from .connectionpools import ConnectionPool from .lib import Bbox, Vec @@ -68,7 +68,10 @@ __version__ = '12.8.0' # Register plugins -from .datasource.precomputed import register as register_precomputed +from .datasource.precomputed import ( + register as register_precomputed, + register_annotation as register_precomputed_annotation, +) from .datasource.graphene import register as register_graphene from .datasource.n5 import register as register_n5 from .datasource.zarr import register as register_zarr @@ -76,7 +79,9 @@ from .datasource.zarr3 import register as register_zarr3 register_precomputed() +register_precomputed_annotation() register_graphene() + register_n5() register_zarr() register_zarr2() diff --git a/cloudvolume/cloudvolume.py b/cloudvolume/cloudvolume.py index 4492a612..b3dc8355 100644 --- a/cloudvolume/cloudvolume.py +++ b/cloudvolume/cloudvolume.py @@ -1,11 +1,12 @@ import sys import time -from typing import Optional, Union, Tuple +from typing import Optional, Union, Tuple, Any import multiprocessing as mp import numpy as np from tqdm import tqdm +from cloudfiles import CloudFiles from cloudfiles.paths import normalize from .exceptions import UnsupportedFormatError, DimensionError, InfoUnavailableError @@ -21,9 +22,13 @@ except AttributeError: INTERACTIVE = bool(sys.flags.interactive) -REGISTERED_PLUGINS = {} +REGISTERED_IMAGE_PLUGINS = {} def register_plugin(key, creation_function): - REGISTERED_PLUGINS[key.lower()] = creation_function + REGISTERED_IMAGE_PLUGINS[key.lower()] = creation_function + +REGISTERED_ANNOTATION_PLUGINS = {} +def register_annotation_plugin(key, creation_function): + REGISTERED_ANNOTATION_PLUGINS[key.lower()] = creation_function def compute_num_threads(num_threads:ParallelType) -> int: if isinstance(num_threads, bool): @@ -268,9 +273,9 @@ def __new__(cls, def init(cloudpath): path = strict_extract(cloudpath) - if path.format in REGISTERED_PLUGINS: + if path.format in REGISTERED_IMAGE_PLUGINS: kwargs["cloudpath"] = normalize(cloudpath) - return REGISTERED_PLUGINS[path.format](**kwargs) + return REGISTERED_IMAGE_PLUGINS[path.format](**kwargs) else: raise UnsupportedFormatError( "Unknown format {}".format(path.format) @@ -287,7 +292,6 @@ def init(cloudpath): else: raise err - @classmethod def create_new_info(cls, *args, **kwargs): from .frontends import CloudVolumePrecomputed @@ -413,3 +417,19 @@ def from_numpy(cls, # save the numpy array vol[:,:,:] = arr return vol + +def from_cloudpath(cloudpath:str, *args, **kwargs) -> Any: + """Create the appropriate object for the given cloudpath.""" + path = strict_extract(cloudpath) + + if path.format != "precomputed": + return CloudVolume(cloudpath, *args, **kwargs) + + info = CloudFiles(cloudpath).get_json("info") + kwargs["info"] = info + + if info["@type"] == "neuroglancer_annotations_v1": + return REGISTERED_ANNOTATION_PLUGINS['precomputed'](cloudpath, *args, **kwargs) + + return CloudVolume(cloudpath, *args, **kwargs) + diff --git a/cloudvolume/datasource/graphene/mesh/sharded.py b/cloudvolume/datasource/graphene/mesh/sharded.py index d85e2929..57802547 100644 --- a/cloudvolume/datasource/graphene/mesh/sharded.py +++ b/cloudvolume/datasource/graphene/mesh/sharded.py @@ -27,7 +27,7 @@ def __init__(self, mesh_meta, cache, config, readonly): self.readers = {} for level, sharding in self.meta.info['sharding'].items(): # { level: std sharding, ... } spec = ShardingSpecification.from_dict(sharding) - self.readers[int(level)] = GrapheneShardReader(self.meta, self.cache, spec) + self.readers[int(level)] = GrapheneShardReader(self.meta.cloudpath, self.cache, spec) def initial_path(self, level): return self.meta.join(self.meta.mesh_path, self.meta.sharded_mesh_dir, str(level)) diff --git a/cloudvolume/datasource/precomputed/__init__.py b/cloudvolume/datasource/precomputed/__init__.py index 58109d46..59b81147 100644 --- a/cloudvolume/datasource/precomputed/__init__.py +++ b/cloudvolume/datasource/precomputed/__init__.py @@ -1,5 +1,6 @@ from typing import Optional, Union +from .annotation import PrecomputedAnnotationSource from .image import PrecomputedImageSource from .metadata import PrecomputedMetadata from .mesh import PrecomputedMeshSource @@ -7,7 +8,8 @@ from .. import get_cache_path from ...cloudvolume import ( - register_plugin, SharedConfiguration, + register_plugin, register_annotation_plugin, + SharedConfiguration, CompressType, ParallelType, CacheType, SecretsType ) @@ -116,6 +118,31 @@ def create_precomputed( return cv +def create_precomputed_annotation( + cloudpath:str, + cache:CacheType = False, + info:Optional[dict] = None, + mip:int = -1, + progress:bool = False, + secrets:SecretsType = None, + use_https:bool = False, +) -> PrecomputedAnnotationSource: + """ + Note: for annotations, mips are coarsest to finest, so -1 + means pick the finest (i.e. the scientifically useful one). + """ + return PrecomputedAnnotationSource( + cloudpath, + cache=cache, + info=info, + mip=mip, + progress=progress, + secrets=secrets, + use_https=use_https, + ) + +def register_annotation(): + register_annotation_plugin('precomputed', create_precomputed_annotation) def register(): register_plugin('precomputed', create_precomputed) \ No newline at end of file diff --git a/cloudvolume/datasource/precomputed/annotation/LICENSE_NEUROGLANCER b/cloudvolume/datasource/precomputed/annotation/LICENSE_NEUROGLANCER new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/cloudvolume/datasource/precomputed/annotation/LICENSE_NEUROGLANCER @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/cloudvolume/datasource/precomputed/annotation/LICENSE_PRECOMPUTED_PYTHON b/cloudvolume/datasource/precomputed/annotation/LICENSE_PRECOMPUTED_PYTHON new file mode 100644 index 00000000..ce517bf0 --- /dev/null +++ b/cloudvolume/datasource/precomputed/annotation/LICENSE_PRECOMPUTED_PYTHON @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Forrest Collman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/cloudvolume/datasource/precomputed/annotation/__init__.py b/cloudvolume/datasource/precomputed/annotation/__init__.py new file mode 100644 index 00000000..5e4f1fde --- /dev/null +++ b/cloudvolume/datasource/precomputed/annotation/__init__.py @@ -0,0 +1,119 @@ +from typing import Optional, Union, Iterable +from dataclasses import dataclass + +import os +import posixpath + +from cloudfiles import CloudFiles +import numpy as np +import numpy.typing as npt + +from .metadata import PrecomputedAnnotationMetadata + +from ....cacheservice import CacheService +from ....paths import strict_extract +from ....cloudvolume import SharedConfiguration + +from ....types import SecretsType +from ....lib import Bbox, BboxLikeType, toiter +from ....paths import strict_extract, to_https_protocol, ascloudpath +from ..common import compressed_morton_code +from ..sharding import ShardReader, ShardingSpecification + +from .metadata import ( + PrecomputedAnnotationMetadata, + AnnotationType, + MultiLabelAnnotation, + LabelAnnotation, +) +from .reader import PrecomputedAnnotationReader + +class PrecomputedAnnotationSource: + def __init__( + self, + cloudpath:str, + cache:Optional[str] = None, + cache_locking:bool = True, + info:Optional[dict] = None, + progress:bool = False, + readonly:bool = False, + secrets:SecretsType = None, + use_https:bool = False, + mip:int = -1, + ): + from .. import get_cache_path + + path = strict_extract(cloudpath) + if use_https: + path = to_https_protocol(path) + cloudpath = ascloudpath(path) + + config = SharedConfiguration( + cdn_cache=False, + compress=False, + compress_level=5, + green=False, + mip=mip, + parallel=1, + progress=progress, + secrets=secrets, + spatial_index_db=None, + cache_locking=cache_locking, + codec_threads=1, + ) + + self.path = path + self.meta = PrecomputedAnnotationMetadata( + cloudpath, cache, config, + info=info, readonly=readonly + ) + self.cloudpath = cloudpath + self.cache = CacheService( + cloudpath=get_cache_path(cache, cloudpath), + enabled=bool(cache), + config=config, + compress=True, + meta=self.meta, + ) + self.config = config + self.readonly = bool(readonly) + self.reader = PrecomputedAnnotationReader(self.meta, self.cache, self.config) + + def ids(self) -> npt.NDArray[np.uint64]: + """Get all annotation IDs.""" + return self.reader.ids() + + def get_by_bbox(self, query:BboxLikeType, mip:Optional[int] = None) -> MultiLabelAnnotation: + """Get all annotations within a bounding box.""" + if mip is None: + mip = self.config.mip + return self.reader.get_by_bbox(query, mip=mip) + + def get_by_id(self, query:list[int]) -> LabelAnnotation: + """Get all annotations by ID.""" + return self.reader.get_by_id(query) + + def get_by_relationship(self, relationship:str, labels:Union[int, Iterable[int]]) -> MultiLabelAnnotation: + """Get annotations by relationship.""" + return self.reader.get_by_relationship(relationship, labels) + + def get_all(self, mip:int = -1) -> MultiLabelAnnotation: + """Get all annotations using the most efficient method available.""" + return self.reader.get_all(mip=mip) + + def summary(self) -> dict: + return { + "type": self.reader.meta.annotation_type, + "bounds": self.reader.meta.bounds, + "path": self.reader.meta.cloudpath, + "dimensions": list(self.reader.meta.dimensions.keys()), + "by_id": self.reader.meta.info["by_id"] is not None, + "spatial_query": self.reader.meta.info["spatial"] is not None, + "relationships": list(self.reader.meta.relationships.keys()), + "properties": self.reader.meta.properties_summary, + } + + def __getitem__(self, slcs): + return self.get_by_bbox(slcs, mip=self.config.mip) + + diff --git a/cloudvolume/datasource/precomputed/annotation/metadata.py b/cloudvolume/datasource/precomputed/annotation/metadata.py new file mode 100644 index 00000000..cea3dda8 --- /dev/null +++ b/cloudvolume/datasource/precomputed/annotation/metadata.py @@ -0,0 +1,480 @@ +from typing import Literal, NamedTuple, Optional, Union, Any, cast, Iterable + +from collections import OrderedDict +from dataclasses import dataclass + +import posixpath +import os + +from cloudfiles import CloudFiles + +import numpy as np +import numpy.typing as npt + +from ....types import CacheType, StrEnum +from ....lib import Bbox +from ....paths import strict_extract, to_https_protocol + +class AnnotationType(StrEnum): + POINT = "POINT" + LINE = "LINE" + AXIS_ALIGNED_BOUNDING_BOX = "AXIS_ALIGNED_BOUNDING_BOX" + ELLIPSOID = "ELLIPSOID" + POLYLINE = "POLYLINE" + +ANNOTATION_INFO_TYPE = "neuroglancer_annotations_v1" + +_PROPERTY_DTYPES: dict[ + str, tuple[Union[tuple[str], tuple[str, tuple[int, ...]]], int] +] = { + "uint8": (("|u1",), 1), + "uint16": ((" npt.NDArray[bool]: + lower_bound = np.array(bbox.minpt) + upper_bound = np.array(bbox.maxpt) + + if type == AnnotationType.POINT: + points = geometry + return np.all(points >= lower_bound, axis=1) & np.all( + points <= upper_bound, axis=1 + ) + elif type == "line": + # Combine point_a and point_b into a single 2D array for vectorized comparison + points_a = geometry[:,:,0] + points_b = geometry[:,:,1] + return ( + np.all(points_a >= lower_bound, axis=1) + & np.all(points_a <= upper_bound, axis=1) + ) | ( + np.all(points_b >= lower_bound, axis=1) + & np.all(points_b <= upper_bound, axis=1) + ) + elif type == AnnotationType.AXIS_ALIGNED_BOUNDING_BOX: + # Combine point_a and point_b into a single 2D array for vectorized comparison + points_a = geometry[:,:,0] + points_b = geometry[:,:,1] + return ( + ( + np.all(points_a >= lower_bound, axis=1) + & np.all(points_a <= upper_bound, axis=1) + ) + | ( + np.all(points_b >= lower_bound, axis=1) + & np.all(points_b <= upper_bound, axis=1) + ) + | ( + np.all(points_a <= lower_bound, axis=1) + & np.all(points_b >= upper_bound, axis=1) + ) + | ( + np.all(points_b <= lower_bound, axis=1) + & np.all(points_a >= upper_bound, axis=1) + ) + ) + elif type == AnnotationType.ELLIPSOID: + # Combine center into a single 2D array for vectorized comparison + center = geometry[:,:,0] + return np.all(center >= lower_bound, axis=1) & np.all( + center <= upper_bound, axis=1 + ) + else: + raise TypeError(f"{type} is not supported by crop.") + +@dataclass +class LabelAnnotation: + id: int + type: AnnotationType + geometry: npt.NDArray[np.float32] + properties: dict[str, np.ndarray] + relationships: dict[str, npt.NDArray[np.uint64]] + properties_enum: Optional[dict[str, dict[int,str]]] + dimensions: Optional[list[str]] + + def __len__(self) -> int: + return self.geometry.shape[0] + + def tobytes(self) -> bytes: + raise NotImplementedError() + + def pandas(self): + import pandas as pd + data = {} + data.update(self.properties) + for i in range(self.geometry.shape[1]): + axis = f"axis_{i}" + if i < len(self.dimensions): + axis = self.dimensions[i] + data[axis] = self.geometry[:,i] + + df = pd.DataFrame(data) + + if isinstance(self.properties_enum, dict): + for name, enum_dict in self.properties_enum.items(): + df[name] = df[name].map(enum_dict).astype('category') + + return df + + def crop(self, bbox:Bbox) -> "LabelAnnotation": + mask = _crop_mask(self.type, self.geometry, bbox) + return LabelAnnotation( + id=self.id, + type=self.type, + geometry=self.geometry[mask], + properties={ + k: v[mask] + for k,v in self.properties.items() + }, + relationships=self.relationships, + properties_enum=self.properties_enum, + dimensions=self.dimensions, + ) + +class SpecificLabelAnnotation(LabelAnnotation): + type: AnnotationType = AnnotationType.POINT + def __init__(self, id, *args, **kwargs): + super().__init__(id, self.type, *args, **kwargs) + +class PointAnnotation(SpecificLabelAnnotation): + type: AnnotationType = AnnotationType.POINT + @property + def points(self) -> npt.NDArray[np.float32]: + return self.geometry + + def viewer(self): + """View as point cloud.""" + import microviewer + microviewer.objects([ self.points ]) + +class LineAnnotation(SpecificLabelAnnotation): + type: AnnotationType = AnnotationType.LINE + +class AxisAlignedBoundingBoxAnnotation(SpecificLabelAnnotation): + type: AnnotationType = AnnotationType.AXIS_ALIGNED_BOUNDING_BOX + + def bbox(self, i:int) -> Bbox: + return Bbox.from_list(*self.geometry[i,:]) + + def bboxes(self) -> list[Bbox]: + return [ + Bbox.from_list(self.geometry[i,:]) + for i in range(len(self.geometry)) + ] + + def viewer(self): + """View as point cloud.""" + import microviewer + microviewer.objects(self.bboxes()) + +class EllipsoidAnnotation(SpecificLabelAnnotation): + type: AnnotationType = AnnotationType.ELLIPSOID + @property + def radii(self): + return self.geometry[:,:,1] + @property + def centers(self): + return self.geometry[:,:,0] + +class PolyLineAnnotation(SpecificLabelAnnotation): + type: AnnotationType = AnnotationType.POLYLINE + +ANNOTATION_CLASS = { + AnnotationType.POINT: PointAnnotation, + AnnotationType.LINE: LineAnnotation, + AnnotationType.ELLIPSOID: EllipsoidAnnotation, + AnnotationType.AXIS_ALIGNED_BOUNDING_BOX: AxisAlignedBoundingBoxAnnotation, + AnnotationType.POLYLINE: PolyLineAnnotation, +} + +def get_annotation_class(type:AnnotationType): + return ANNOTATION_CLASS[type] + +@dataclass +class MultiLabelAnnotation: + type: AnnotationType + geometry: npt.NDArray[np.float32] + ids: npt.NDArray[np.uint64] + properties: dict[str, np.ndarray] + properties_enum: Optional[dict[str, dict[int,str]]] + dimensions: Optional[list[str]] + + def __len__(self) -> int: + return len(self.geometry) + + def pandas(self): + import pandas as pd + data = { "ID": self.ids } + data.update(self.properties) + + if len(self.geometry.shape) > 2 and self.geometry.shape[2] > 1: + for j in range(self.geometry.shape[2]): + for i in range(self.geometry.shape[1]): + axis = f"axis_{j}_{i}" + if i < len(self.dimensions): + axis = f"axis{j}_{self.dimensions[i]}" + data[axis] = self.geometry[:,i,j] + else: + for i in range(self.geometry.shape[1]): + axis = f"axis_{i}" + if i < len(self.dimensions): + axis = self.dimensions[i] + data[axis] = self.geometry[:,i] + + df = pd.DataFrame(data) + + if isinstance(self.properties_enum, dict): + for name, enum_dict in self.properties_enum.items(): + df[name] = df[name].map(enum_dict).astype('category') + + df.set_index("ID", inplace=True) + return df + + def split_by_id(self) -> dict[int,LabelAnnotation]: + all_labels = np.unique(self.ids) + + AnnotationClass = get_annotation_class(self.type) + + out = {} + for label in all_labels: + mask = self.ids == label + properties = { + name: arr[mask] + for name, arr in self.properties.items() + } + label = int(label) + out[label] = AnnotationClass( + label, + self.geometry[mask], + properties, + relationships={}, + properties_enum=self.properties_enum, + dimensions=self.dimensions, + ) + return out + + def crop(self, bbox:Bbox) -> "MultiLabelAnnotation": + mask = _crop_mask(self.type, self.geometry, bbox) + return MultiLabelAnnotation( + type=self.type, + geometry=self.geometry[mask], + ids=self.ids[mask], + properties={ + k: v[mask] + for k,v in self.properties.items() + }, + properties_enum=self.properties_enum, + dimensions=self.dimensions, + ) + + def viewer(self): + if self.type != AnnotationType.POINT: + raise ValueError(f"Type {self.type} not supported.") + + import microviewer + microviewer.objects([ self.geometry ]) + +class PrecomputedAnnotationMetadata: + def __init__( + self, + cloudpath:str, + cache:CacheType, + config:Optional["SharedConfiguration"] = None, + info:Optional[dict] = None, + readonly:bool = False, + use_https:bool = False, + ): + + path = strict_extract(cloudpath) + if use_https: + cloudpath = to_https_protocol(path) + + self.path = path + self.cloudpath = cloudpath + self.cache = cache + self.config = config + self.readonly = readonly + + if info: + self.info = info + else: + self.info = self.fetch_info() + + typ = self.info.get("@type", "") + + if typ != ANNOTATION_INFO_TYPE: + raise ValueError(f"info @type must be {ANNOTATION_INFO_TYPE}. Got: {typ}") + + def join(self, *paths): + if self.path.protocol == 'file': + return os.path.join(*paths) + else: + return posixpath.join(*paths) + + def has_id_index(self) -> bool: + return self.info.get("by_id", None) is not None + + def has_spatial_index(self) -> bool: + return self.info.get("spatial", None) is not None + + def fetch_info(self): + return CloudFiles(self.cloudpath, secrets=self.config.secrets).get_json('info') + + def default_info(self): + return { + "@type": ANNOTATION_INFO_TYPE, + "dimensions": [], # e.g. [[ 32.0, "nm" ], ... ] + "lower_bound": [], + "upper_bound": [], + "annotation_type": AnnotationType.POINT, + "properties": [{ + # "id": "class_label" + # "type": "int32" + # "description": "" + # "enum_labels": [0,1,2,3,4,5000], + # "enum_values": ["axon", "dendrite", "astrocyte", "soma", ...] + }], + # e.g. [ { "id": , "key": ..., "sharding": ... } ] + "relationships": [], + # e.g. [ { "key": ..., "sharding": ... } ] + "by_id": [], + # e.g. [ { "key", "sharding", "grid_shape", "chunk_size", "limit" } ] + } + + @property + def dimensions(self) -> list[list]: + return OrderedDict(self.info["dimensions"]) + + @property + def ndim(self) -> int: + return len(self.info["dimensions"]) + + @property + def rank(self) -> int: + """Alias for ndim.""" + return self.ndim + + @property + def properties(self) -> dict: + return self.info.get("properties", []) + + @property + def properties_enum(self) -> dict[str, dict[int, str]]: + enums = {} + for p in self.properties: + if "enum_labels" in p: + enums[p['id']] = { + k: v for k, v in zip(p["enum_values"], p["enum_labels"]) + } + + return enums + + @property + def properties_summary(self) -> dict[str, dict[int, str]]: + enums = {} + for p in self.properties: + if "enum_labels" in p: + enums[p['id']] = { + k: v for k, v in zip(p["enum_values"], p["enum_labels"]) + } + elif "enum_values" in p: + enums[p['id']] = np.asarray(p["enum_values"]) + else: + enums[p['id']] = p["type"] + + return enums + + @property + def relationships(self) -> dict[str, dict[str, Any]]: + if "relationships" not in self.info.keys(): + raise ValueError("No relationships found in the info file.") + return { r["id"]: r for r in self.info["relationships"] } + + @property + def property_names(self) -> list[str]: + """Get the properties of the annotations. + + Returns: + list: A list of property names. + """ + if "properties" not in self.info.keys(): + raise ValueError("No properties found in the info file.") + return [ p["id"] for p in self.info["properties"] ] + + def annotation_dtype(self, binary:bytes) -> np.dtype: + prop_dtypes = _get_dtype_for_properties(self.properties) + + # Derived from Neuroglancer Python code + if self.annotation_type == AnnotationType.POLYLINE: + num_pts = np.frombuffer(encoded, dtype=" Bbox: + # assumes all dimensions are 1 unit and same + unit = next(iter(self.dimensions.values()))[1] + return Bbox(self.info["lower_bound"], self.info["upper_bound"], unit=unit) + + def chunk_size(self, mip:int) -> np.ndarray: + return np.array(self.info["spatial"][mip]["chunk_size"], dtype=int) + + def grid_shape(self, mip:int) -> np.ndarray: + return np.array(self.info["spatial"][mip]["grid_shape"], dtype=int) + + @property + def annotation_type(self) -> AnnotationType: + return AnnotationType(self.info["annotation_type"]) + + def is_id_index_sharded(self) -> bool: + if "by_id" not in self.info: + return False + + index = self.info["by_id"] + return index.get("sharding", None) is not None diff --git a/cloudvolume/datasource/precomputed/annotation/reader.py b/cloudvolume/datasource/precomputed/annotation/reader.py new file mode 100644 index 00000000..b84cf0d6 --- /dev/null +++ b/cloudvolume/datasource/precomputed/annotation/reader.py @@ -0,0 +1,354 @@ +""" +Precomputed Annotation Reader code adapted from +a mixture of these two repositories: + +https://github.com/fcollman/precomputed_python +https://github.com/google/neuroglancer/ +""" + +from typing import Optional, Union, Iterable + +import os +import posixpath + +from cloudfiles import CloudFiles +import numpy as np +import numpy.typing as npt + +from tqdm import tqdm + +from .metadata import ( + PrecomputedAnnotationMetadata, + MultiLabelAnnotation, + LabelAnnotation, + get_annotation_class, +) + +from ....cacheservice import CacheService +from ....paths import strict_extract +from ....cloudvolume import SharedConfiguration + +from ....types import SecretsType +from ....lib import Bbox, BboxLikeType, toiter +from ....paths import strict_extract, to_https_protocol, ascloudpath +from ..common import compressed_morton_code +from ..sharding import ShardReader, ShardingSpecification + +from .metadata import PrecomputedAnnotationMetadata, AnnotationType + +# sharded example +# https://neuroglancer-demo.appspot.com/#!%7B%22dimensions%22:%7B%22x%22:%5B6.4e-8%2C%22m%22%5D%2C%22y%22:%5B6.4e-8%2C%22m%22%5D%2C%22z%22:%5B6.6e-8%2C%22m%22%5D%7D%2C%22position%22:%5B34724.5%2C23270.5%2C584.5%5D%2C%22crossSectionScale%22:1%2C%22projectionOrientation%22:%5B-0.09734609723091125%2C-0.26029738783836365%2C-0.0020852696616202593%2C0.9606063961982727%5D%2C%22projectionScale%22:20037.381619627573%2C%22layers%22:%5B%7B%22type%22:%22segmentation%22%2C%22source%22:%22gs://h01-release/data/20210601/c2/subcompartments/%7Cneuroglancer-precomputed:%22%2C%22tab%22:%22source%22%2C%22segments%22:%5B%22%21103%22%5D%2C%22name%22:%22subcompartments%22%2C%22visible%22:false%7D%2C%7B%22type%22:%22annotation%22%2C%22source%22:%22gs://h01-release/data/20210601/c2/subcompartments/annotations/%7Cneuroglancer-precomputed:%22%2C%22tab%22:%22source%22%2C%22name%22:%22new%20layer%22%7D%5D%2C%22selectedLayer%22:%7B%22visible%22:true%2C%22layer%22:%22new%20layer%22%7D%2C%22layout%22:%22xy-3d%22%7D + +class PrecomputedAnnotationReader: + def __init__( + self, + meta:PrecomputedAnnotationMetadata, + cache:CacheService, + config:SharedConfiguration, + readonly:bool = False, + secrets:SecretsType = None, + info:Optional[dict] = None, + use_https:bool = False, + ): + self.meta = meta + self.cache = cache + self.config = config + self.readonly = bool(readonly) + + def ids(self) -> npt.NDArray[np.uint64]: + """Get all annotation IDs from the kv store. + + Returns: + np.array: An array of all annotation IDs. + """ + if "by_id" not in self.meta.info: + raise ValueError("No by_id information found in the info file.") + + cf = CloudFiles(self.meta.cloudpath) + + by_id = self.meta.info["by_id"] + + key = by_id["key"] + if not key.endswith(cf.sep): + key += cf.sep + + cache_key = os.path.join(key, "_ids.npy") + cache_path = os.path.join(self.cache.path.replace("file://", ""), cache_key) + + if self.cache.enabled: + if self.cache.has(cache_key): + return np.load(cache_path, allow_pickle=False) + + if self.meta.is_id_index_sharded(): + shard_filenames = [ + x for x in cf.list(prefix=key, flat=True) + if x.endswith('.shard') + ] + spec = ShardingSpecification.from_dict(by_id["sharding"]) + reader = ShardReader(self.meta.cloudpath, self.cache, spec) + + all_ids = [] + for fname in tqdm(shard_filenames, disable=(not self.config.progress), desc="Downloading Labels"): + all_ids.append( + reader.list_labels(fname, path=key) + ) + all_ids = np.concatenate(all_ids, dtype=np.uint64) + all_ids.sort() + else: + cf = CloudFiles(self.cloudpath) + all_ids = ( int(x) for x in cf.list(prefix=key, flat=True) ) + all_ids = np.fromiter(all_ids, dtype=np.uint64) + + if self.cache.enabled: + np.save(cache_path, all_ids) + + return all_ids + + def _decode_single_annotation(self, binary:bytes): + ndim = self.meta.ndim + offset = 0 + + decoded = np.frombuffer( + binary, + offset=offset, + count=1, + dtype=self.meta.annotation_dtype(binary), + ) + geometry = decoded["_pt1"] + if "_pt2" in decoded.dtype.names: + geometry = np.hstack(geometry, decoded["_pt2"]) + + offset += decoded.nbytes + + properties = {} + for prop in self.meta.properties: + properties[prop["id"]] = decoded[prop["id"]] + + relationships = {} + for relation in self.meta.info["relationships"]: + num_obj = int.from_bytes(binary[offset:offset+4], 'little') + offset += 4 + object_ids = np.frombuffer(binary, offset=offset, count=num_obj, dtype=np.uint64) + offset += object_ids.nbytes + relationships[relation["key"]] = object_ids + + assert offset == len(binary) + + return (geometry, properties, relationships) + + def _decode_label_annotation(self, segid:int, binary:bytes) -> LabelAnnotation: + (geometry, properties, relationships) = self._decode_single_annotation(binary) + AnnotationClass = get_annotation_class(self.meta.annotation_type) + dims = list(self.meta.dimensions.keys()) + return AnnotationClass( + segid, + geometry, + properties, + relationships, + properties_enum=self.meta.properties_enum, + dimensions=dims, + ) + + def _decode_annotations(self, binary:bytes) -> tuple[np.ndarray, np.ndarray, dict[str, np.ndarray]]: + ndim = self.meta.ndim + num_points = int.from_bytes(binary[:8], 'little') + offset = 8 + + decoded = np.frombuffer( + binary, + offset=offset, + count=num_points, + dtype=self.meta.annotation_dtype(binary), + ) + geometry = decoded["_pt1"] + if "_pt2" in decoded.dtype.names: + geometry = np.hstack(geometry, decoded["_pt2"]) + offset += decoded.nbytes + + properties = {} + for prop in self.meta.properties: + properties[prop["id"]] = decoded[prop["id"]] + + ids = np.frombuffer( + binary, + offset=offset, + count=num_points, + dtype=" dict[int, LabelAnnotation]: + """Retrieve all annotations.""" + if self.meta.has_spatial_index(): + slcs = tuple([ slice(None) for i in range(self.meta.ndim) ]) + return self.get_by_bbox(slcs, mip=mip) + else: + # This branch could be radically sped up if needed + # by pulling the shards and disassembling them directly + return self.get_by_id(self.ids()) + + def get_by_id(self, labels:Union[int, list[int]]) -> Union[LabelAnnotation, dict[int, LabelAnnotation]]: + """ + Retrieve annotations by one or more IDs. + """ + labels, return_multiple = toiter(labels, is_iter=True) + by_id = self.meta.info["by_id"] + + if self.meta.is_id_index_sharded(): + spec = ShardingSpecification.from_dict(by_id["sharding"]) + reader = ShardReader(self.meta.cloudpath, self.cache, spec) + result = reader.get_data(labels, path=by_id["key"]) + annos = { + segid: self._decode_label_annotation(segid, binary) + for segid, binary in result.items() + } + else: + filenames = [ + self.meta.join(by_id["key"], str(segid)) + for segid in labels + ] + annotations = self.cache.download(filenames) + + annos = {} + for path, binary in annotations.items(): + segid = int(os.path.basename(path)) + annos[segid] = self._decode_label_annotation(segid, binary) + + if return_multiple: + return annos + return annos[labels[0]] + + def get_by_bbox(self, bbox:BboxLikeType, mip:int = -1) -> MultiLabelAnnotation: + """ + Query for all annotations in the given bounding box. + Bounds are inclusive on both sides. + + Note: for annotations, mips are coarsest to finest, + the opposite of images. By default, we pick the finest + mip because that is the one that is scientifically useful. + """ + spatial = self.meta.info["spatial"][mip] + key = spatial["key"] + + spatial_path = self.meta.join(self.meta.cloudpath, key) + + realized_bbox = Bbox.create(bbox, self.meta.bounds) + orig_bbox = realized_bbox.clone() + realized_bbox = realized_bbox.expand_to_chunk_size( + self.meta.chunk_size(mip), + offset=self.meta.bounds.minpt, + ) + realized_bbox = Bbox.clamp(realized_bbox, self.meta.bounds) + realized_bbox -= self.meta.bounds.minpt + realized_bbox /= self.meta.chunk_size(mip) + + grid_box = Bbox([0,0,0], self.meta.grid_shape(mip)) + realized_bbox = Bbox.clamp(realized_bbox, grid_box) + grid = np.mgrid[realized_bbox.to_slices()] + grid = np.stack(grid, axis=-1).reshape(-1, 3) + + if spatial.get("sharding", None) is not None: + codes = compressed_morton_code(grid, self.meta.grid_shape(mip)) + spec = ShardingSpecification.from_dict(spatial["sharding"]) + reader = ShardReader(self.meta.cloudpath, self.cache, spec) + annotations = reader.get_data(codes, path=key) + annotations = [ binary for binary in annotations.values() if binary is not None ] + else: + filenames = [ + self.meta.join( + key, + "_".join([ str(x) for x in pt ]) + ) + for pt in grid + ] + annotations = self.cache.download(filenames) + annotations = [ binary for binary in annotations.values() ] + + all_geo = [] + ids = [] + properties = {} + for binary in annotations: + geometry, annotation_ids, props = self._decode_annotations(binary) + all_geo.append(geometry) + ids.append(annotation_ids) + + for prop in props.keys(): + if prop not in properties: + properties[prop] = props[prop] + else: + properties[prop] = np.concatenate([properties[prop], props[prop]]) + + if len(all_geo): + all_geo = np.concatenate(all_geo, axis=0) + else: + all_geo = np.zeros([0, self.meta.ndim ], dtype=np.float32) + + if len(ids): + ids = np.concatenate(ids) + else: + ids = np.zeros([0,], dtype=np.uint64) + + annotation = MultiLabelAnnotation( + type=self.meta.annotation_type, + geometry=all_geo, + ids=ids, + properties=properties, + properties_enum=self.meta.properties_enum, + dimensions=list(self.meta.dimensions.keys()), + ) + + if realized_bbox == grid_box: + return annotation + else: + return annotation.crop(orig_bbox) + + def get_by_relationship(self, relationship:str, labels:Union[int, Iterable[int]]) -> Union[dict[int, MultiLabelAnnotation], MultiLabelAnnotation]: + """ + Get the annotations corresponding to the relationship type. + """ + labels, return_multiple = toiter(labels, is_iter=True) + + rels = self.meta.relationships + + if relationship not in rels: + raise ValueError(f"Relationship {relationship} not found. Available: {','.join(rels.keys())}") + + rel = rels[relationship] + + if 'sharding' in rel and rel.get("sharding", None) is not None: + spec = ShardingSpecification.from_dict(rel["sharding"]) + reader = ShardReader(self.meta.cloudpath, self.cache, spec) + binaries = reader.get_data(labels, path=rel["key"]) + else: + filenames = [ self.meta.join(rel["key"], str(segid)) for segid in labels ] + binaries = self.cache.download(filenames) + binaries = { + int(os.path.basename(path)): binary + for path, binary in binaries.items() + } + + ret = {} + + dims = list(self.meta.dimensions.keys()) + + for label, binary in binaries.items(): + if binary is None: + raise ValueError(f"Binary for {label} using relationship {relationship} was not found.") + + geometry, ids, properties = self._decode_annotations(binary) + ret[label] = MultiLabelAnnotation( + type=self.meta.annotation_type, + geometry=geometry, + ids=ids, + properties=properties, + properties_enum=self.meta.properties_enum, + dimensions=dims, + ) + + if return_multiple: + return ret + + return ret[next(iter(ret.keys()))] diff --git a/cloudvolume/datasource/precomputed/common.py b/cloudvolume/datasource/precomputed/common.py index 00ca01fc..bbdcf109 100644 --- a/cloudvolume/datasource/precomputed/common.py +++ b/cloudvolume/datasource/precomputed/common.py @@ -1,3 +1,9 @@ +import math + +import numpy as np + +from ...lib import Vec, Bbox + def content_type(encoding): if encoding == 'jpeg': return 'image/jpeg' @@ -41,3 +47,74 @@ def cdn_cache_control(val): return 'max-age={}, s-max-age={}'.format(val, val) else: raise NotImplementedError(type(val) + ' is not a supported cache_control setting.') + +def compressed_morton_code(gridpt, grid_size): + if hasattr(gridpt, "__len__") and len(gridpt) == 0: # generators don't have len + return np.zeros((0,), dtype=np.uint32) + + gridpt = np.asarray(gridpt, dtype=np.uint32) + single_input = False + if gridpt.ndim == 1: + gridpt = np.atleast_2d(gridpt) + single_input = True + + code = np.zeros((gridpt.shape[0],), dtype=np.uint64) + num_bits = [ math.ceil(math.log2(size)) for size in grid_size ] + j = np.uint64(0) + one = np.uint64(1) + + if sum(num_bits) > 64: + raise ValueError(f"Unable to represent grids that require more than 64 bits. Grid size {grid_size} requires {num_bits} bits.") + + max_coords = np.max(gridpt, axis=0) + if np.any(max_coords >= grid_size): + raise ValueError(f"Unable to represent grid points larger than the grid. Grid size: {grid_size} Grid points: {gridpt}") + + for i in range(max(num_bits)): + for dim in range(3): + if 2 ** i < grid_size[dim]: + bit = (((np.uint64(gridpt[:, dim]) >> np.uint64(i)) & one) << j) + code |= bit + j += one + + if single_input: + return code[0] + return code + +def morton_code_to_bbox(code, volume_bbox, chunk_size): + chunk_size = Vec(*chunk_size) + + grid_size = np.ceil(volume_bbox.size3() / chunk_size).astype(np.int64) + + gridpt = morton_code_to_gridpt(code, grid_size) + + bbox = Bbox(gridpt, gridpt + 1) + bbox *= chunk_size + bbox += volume_bbox.minpt + return bbox + +def morton_code_to_gridpt(code, grid_size): + gridpt = np.zeros([3,], dtype=int) + + num_bits = [ math.ceil(math.log2(size)) for size in grid_size ] + j = np.uint64(0) + one = np.uint64(1) + + if sum(num_bits) > 64: + raise ValueError(f"Unable to represent grids that require more than 64 bits. Grid size {grid_size} requires {num_bits} bits.") + + max_coords = np.max(gridpt, axis=0) + if np.any(max_coords >= grid_size): + raise ValueError(f"Unable to represent grid points larger than the grid. Grid size: {grid_size} Grid points: {gridpt}") + + code = np.uint64(code) + + for i in range(max(num_bits)): + for dim in range(3): + i = np.uint64(i) + if 2 ** i < grid_size[dim]: + bit = np.uint64((code >> j) & one) + gridpt[dim] += (bit << i) + j += one + + return gridpt \ No newline at end of file diff --git a/cloudvolume/datasource/precomputed/image/__init__.py b/cloudvolume/datasource/precomputed/image/__init__.py index 9c643fce..b1722bde 100644 --- a/cloudvolume/datasource/precomputed/image/__init__.py +++ b/cloudvolume/datasource/precomputed/image/__init__.py @@ -29,7 +29,8 @@ from ... import autocropfn, readonlyguard, ImageSourceInterface from .. import sharding -from .common import chunknames, gridpoints, compressed_morton_code, morton_code_to_bbox +from ..common import compressed_morton_code, morton_code_to_bbox +from .common import chunknames, gridpoints from . import tx, rx, xfer class PrecomputedImageSource(ImageSourceInterface): @@ -675,7 +676,7 @@ def shard_reader(self, mip=None): mip = mip if mip is not None else self.config.mip scale = self.meta.scale(mip) spec = sharding.ShardingSpecification.from_dict(scale['sharding']) - return sharding.ShardReader(self.meta, self.cache, spec) + return sharding.ShardReader(self.meta.cloudpath, self.cache, spec) def shard_spec(self, mip, spec=None): if spec is None: @@ -721,7 +722,7 @@ def morton_codes( grid_size = self.grid_size(mip) chunk_size = self.meta.chunk_size(mip) - reader = sharding.ShardReader(self.meta, self.cache, spec) + reader = sharding.ShardReader(self.meta.cloudpath, self.cache, spec) # 3. Gridpoints all within this one shard gpts = list(gridpoints(aligned_bbox, self.meta.bounds(mip), chunk_size)) diff --git a/cloudvolume/datasource/precomputed/image/common.py b/cloudvolume/datasource/precomputed/image/common.py index 5250308f..5b1bed18 100644 --- a/cloudvolume/datasource/precomputed/image/common.py +++ b/cloudvolume/datasource/precomputed/image/common.py @@ -174,78 +174,6 @@ def gridpoints(bbox, volume_bbox, chunk_size): for x,y,z in xyzrange( grid_cutout.minpt, grid_cutout.maxpt, (1,1,1) ): yield Vec(x,y,z) -def compressed_morton_code(gridpt, grid_size): - if hasattr(gridpt, "__len__") and len(gridpt) == 0: # generators don't have len - return np.zeros((0,), dtype=np.uint32) - - gridpt = np.asarray(gridpt, dtype=np.uint32) - single_input = False - if gridpt.ndim == 1: - gridpt = np.atleast_2d(gridpt) - single_input = True - - code = np.zeros((gridpt.shape[0],), dtype=np.uint64) - num_bits = [ math.ceil(math.log2(size)) for size in grid_size ] - j = np.uint64(0) - one = np.uint64(1) - - if sum(num_bits) > 64: - raise ValueError(f"Unable to represent grids that require more than 64 bits. Grid size {grid_size} requires {num_bits} bits.") - - max_coords = np.max(gridpt, axis=0) - if np.any(max_coords >= grid_size): - raise ValueError(f"Unable to represent grid points larger than the grid. Grid size: {grid_size} Grid points: {gridpt}") - - for i in range(max(num_bits)): - for dim in range(3): - if 2 ** i < grid_size[dim]: - bit = (((np.uint64(gridpt[:, dim]) >> np.uint64(i)) & one) << j) - code |= bit - j += one - - if single_input: - return code[0] - return code - -def morton_code_to_bbox(code, volume_bbox, chunk_size): - chunk_size = Vec(*chunk_size) - - grid_size = np.ceil(volume_bbox.size3() / chunk_size).astype(np.int64) - - gridpt = morton_code_to_gridpt(code, grid_size) - - bbox = Bbox(gridpt, gridpt + 1) - bbox *= chunk_size - bbox += volume_bbox.minpt - return bbox - -def morton_code_to_gridpt(code, grid_size): - gridpt = np.zeros([3,], dtype=int) - - num_bits = [ math.ceil(math.log2(size)) for size in grid_size ] - j = np.uint64(0) - one = np.uint64(1) - - if sum(num_bits) > 64: - raise ValueError(f"Unable to represent grids that require more than 64 bits. Grid size {grid_size} requires {num_bits} bits.") - - max_coords = np.max(gridpt, axis=0) - if np.any(max_coords >= grid_size): - raise ValueError(f"Unable to represent grid points larger than the grid. Grid size: {grid_size} Grid points: {gridpt}") - - code = np.uint64(code) - - for i in range(max(num_bits)): - for dim in range(3): - i = np.uint64(i) - if 2 ** i < grid_size[dim]: - bit = np.uint64((code >> j) & one) - gridpt[dim] += (bit << i) - j += one - - return gridpt - - def shade(dest_img, dest_bbox, src_img, src_bbox, channel=None): """ Shade dest_img at coordinates dest_bbox using the diff --git a/cloudvolume/datasource/precomputed/image/rx.py b/cloudvolume/datasource/precomputed/image/rx.py index fdd5004a..f421797e 100644 --- a/cloudvolume/datasource/precomputed/image/rx.py +++ b/cloudvolume/datasource/precomputed/image/rx.py @@ -25,11 +25,10 @@ import cloudvolume.sharedmemory as shm -from ..common import should_compress, content_type +from ..common import should_compress, content_type, compressed_morton_code from .common import ( parallel_execution, chunknames, shade, gridpoints, - compressed_morton_code ) from .. import sharding @@ -67,7 +66,7 @@ def download_sharded( chunk_size = meta.chunk_size(mip) grid_size = np.ceil(meta.bounds(mip).size3() / chunk_size).astype(np.uint32) - reader = sharding.ShardReader(meta, cache, spec) + reader = sharding.ShardReader(meta.cloudpath, cache, spec) bounds = meta.bounds(mip) gpts = list(gridpoints(full_bbox, bounds, chunk_size)) @@ -168,7 +167,7 @@ def download_raw_sharded( chunk_size = meta.chunk_size(mip) grid_size = np.ceil(meta.bounds(mip).size3() / chunk_size).astype(np.uint32) - reader = sharding.ShardReader(meta, cache, spec) + reader = sharding.ShardReader(meta.cloudpath, cache, spec) bounds = meta.bounds(mip) gpts = list(gridpoints(full_bbox, bounds, chunk_size)) @@ -981,7 +980,7 @@ def unique_sharded( chunk_size = meta.chunk_size(mip) grid_size = np.ceil(meta.bounds(mip).size3() / chunk_size).astype(np.uint32) - reader = sharding.ShardReader(meta, cache, spec) + reader = sharding.ShardReader(meta.cloudpath, cache, spec) bounds = meta.bounds(mip) all_gpts = list(gridpoints(full_bbox, bounds, chunk_size)) diff --git a/cloudvolume/datasource/precomputed/image/xfer.py b/cloudvolume/datasource/precomputed/image/xfer.py index 08e3c7c3..29fd179d 100644 --- a/cloudvolume/datasource/precomputed/image/xfer.py +++ b/cloudvolume/datasource/precomputed/image/xfer.py @@ -13,7 +13,8 @@ from ... import autocropfn, readonlyguard, ImageSourceInterface from .. import sharding -from .common import chunknames, gridpoints, compressed_morton_code, morton_code_to_bbox +from ..common import compressed_morton_code, morton_code_to_bbox +from .common import chunknames, gridpoints from . import tx def create_destination(source, cloudpath, mip, encoding): @@ -259,7 +260,7 @@ def transfer_sharded_to_sharded( grid_size = np.ceil(source.meta.bounds(mip).size3() / chunk_size).astype(np.uint32) - reader = sharding.ShardReader(source.meta, source.cache, spec) + reader = sharding.ShardReader(source.meta.cloudpath, source.cache, spec) bounds = source.meta.bounds(mip) gpts, morton_codes = source.morton_codes( diff --git a/cloudvolume/datasource/precomputed/sharding.py b/cloudvolume/datasource/precomputed/sharding.py index cdbe6c82..37380721 100644 --- a/cloudvolume/datasource/precomputed/sharding.py +++ b/cloudvolume/datasource/precomputed/sharding.py @@ -7,7 +7,9 @@ import math import operator from operator import itemgetter +import os from os.path import basename +import posixpath import struct import numpy as np @@ -16,6 +18,7 @@ from cloudfiles import CloudFiles from . import mmh3 +from ...paths import strict_extract from ... import compression from ...lib import jsonify, toiter, first, Vec, Bbox from ...lru import LRU @@ -271,12 +274,15 @@ def compute_shape_bits(): def __str__(self): return "ShardingSpecification::" + str(self.to_dict()) -class ShardReader(object): +class ShardReader: def __init__( - self, meta, cache, spec, - shard_index_cache_size=512, - minishard_index_cache_size=128, - green=False + self, + cloudpath:Optional[str], + cache:"CacheService", + spec:ShardingSpecification, + shard_index_cache_size:int = 512, + minishard_index_cache_size:int = 128, + green:bool = False, ): """ Reads standard Precomputed shard files. @@ -288,7 +294,13 @@ def __init__( shard_index_cache_size: size of LRU cache for fixed indices minishard_index_cache_size: size of LRU cache for minishard indices """ - self.meta = meta + self.cloudpath = cloudpath + + if cloudpath is not None: + self._path = strict_extract(cloudpath) + else: + self._path = None + self.cache = cache self.spec = spec self.green = green @@ -296,6 +308,12 @@ def __init__( self.shard_index_cache = LRU(shard_index_cache_size) self.minishard_index_cache = LRU(minishard_index_cache_size) + def join(self, *paths): + if self._path.protocol == 'file': + return os.path.join(*paths) + else: + return posixpath.join(*paths) + def get_filename(self, label): return self.compute_shard_location(label)[0] @@ -334,7 +352,7 @@ def get_indices(self, filenames, path="", progress=None): } """ filenames = toiter(filenames) - filenames = [ self.meta.join(path, fname) for fname in filenames ] + filenames = [ self.join(path, fname) for fname in filenames ] fufilled = { fname: self.shard_index_cache[fname] \ for fname in filenames \ @@ -446,7 +464,7 @@ def get_minishard_indices_for_files(self, requests, path="", progress=None): for msn, start, end in pending_requests: msn_map[(basename(filename), start, end)] = msn - filepath = self.meta.join(path, filename) + filepath = self.join(path, filename) download_requests.append({ 'path': filepath, @@ -492,7 +510,7 @@ def compute_minishard_index_requests(self, filename, index, minishard_nos, path= bytes_start, bytes_end = int(bytes_start), int(bytes_end) byte_ranges[msn] = (bytes_start, bytes_end) - full_path = self.meta.join(self.meta.cloudpath, path) + full_path = self.join(self.cloudpath, path) pending_requests = [] for msn, (bytes_start, bytes_end) in byte_ranges.items(): @@ -545,7 +563,7 @@ def exists(self, labels, path="", return_byte_range=False, progress=None): results = {} for filename, file_minishards in all_minishards.items(): - filepath = self.meta.join(path, filename) + filepath = self.join(path, filename) for mini_no, msi in file_minishards.items(): labels = to_labels[(filename, mini_no)] @@ -593,8 +611,11 @@ def disassemble_shard(self, shard): return shattered def get_data( - self, label:int, path:str = "", - progress:Optional[bool] = None, parallel:int = 1, + self, + label:int, + path:str = "", + progress:Optional[bool] = None, + parallel:int = 1, raw:bool = False ): """Fetches data from shards. @@ -622,7 +643,7 @@ def get_data( cached = {} if self.cache.enabled: cached = self.cache.get([ - self.meta.join(path, str(lbl)) for lbl in label + self.join(path, str(lbl)) for lbl in label ], progress=progress) results = {} @@ -660,12 +681,12 @@ def get_data( bundles[-1]['end'] = chunk['end'] bundles[-1]['subranges'].append({ - 'start': chunk['start'], - 'length': chunk['end'] - chunk['start'], - 'slices': slice(chunk['start'] - bundles[-1]['start'], chunk['end'] - bundles[-1]['start']) + 'start': chunk['start'], + 'length': chunk['end'] - chunk['start'], + 'slices': slice(chunk['start'] - bundles[-1]['start'], chunk['end'] - bundles[-1]['start']) }) - full_path = self.meta.join(self.meta.cloudpath, path) + full_path = self.join(self.cloudpath, path) bundles_resp = CloudFiles( full_path, progress=("Downloading Bundles" if progress else False), @@ -700,7 +721,7 @@ def get_data( if self.cache.enabled: self.cache.put([ - (self.meta.join(path, str(filepath)), binary) for filepath, binary in binaries.items() + (self.join(path, str(filepath)), binary) for filepath, binary in binaries.items() ], progress=progress) results.update(binaries) @@ -731,7 +752,8 @@ def list_labels(self, filename, path="", size=False): labels = np.concatenate([ msi[:,0] for msi in minishard_indices ]) - return np.sort(labels) + labels.sort() + return labels else: labels = np.concatenate([ msi[:,:] diff --git a/cloudvolume/datasource/precomputed/skeleton/sharded.py b/cloudvolume/datasource/precomputed/skeleton/sharded.py index 5417f0bb..e548e146 100644 --- a/cloudvolume/datasource/precomputed/skeleton/sharded.py +++ b/cloudvolume/datasource/precomputed/skeleton/sharded.py @@ -18,7 +18,7 @@ def __init__(self, meta, cache, config, readonly=False): self.readonly = bool(readonly) spec = ShardingSpecification.from_dict(self.meta.info['sharding']) - self.reader = ShardReader(meta, cache, spec) + self.reader = ShardReader(meta.cloudpath, cache, spec) self.spatial_index = None if self.meta.spatial_index: diff --git a/cloudvolume/lib.py b/cloudvolume/lib.py index 0d31232f..808a49ae 100644 --- a/cloudvolume/lib.py +++ b/cloudvolume/lib.py @@ -544,9 +544,14 @@ def from_slices(cls, slices, context=None, bounded=False, autocrop=False): if slc.step not in (None, 1): raise ValueError("Non-unitary steps are unsupported. Got: " + str(slc.step)) + unit = 'vx' + if context: + unit = context.unit + return Bbox( [ slc.start for slc in slices ], - [ (slc.start if slc.stop < slc.start else slc.stop) for slc in slices ] + [ (slc.start if slc.stop < slc.start else slc.stop) for slc in slices ], + unit=unit, ) @classmethod diff --git a/cloudvolume/provenance.py b/cloudvolume/provenance.py index 35f5788e..eb82c063 100644 --- a/cloudvolume/provenance.py +++ b/cloudvolume/provenance.py @@ -1,9 +1,7 @@ import python_jsonschema_objects as pjs -import json +import orjson import json5 -__all__ = [ 'DatasetProvenance', 'DataLayerProvenance' ] - dataset_provenance_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "id": "DatasetProvenance", @@ -108,7 +106,7 @@ def validate(self): DataLayerProvenanceValidation(**self).validate() def serialize(self): - return json.dumps(self) + return orjson.dumps(self).decode("utf8") def from_json(self, data): data = json5.loads(data) @@ -148,7 +146,9 @@ def sources(self, val): self['sources'] = val - +__all__ = [ + DataLayerProvenance +] diff --git a/cloudvolume/types.py b/cloudvolume/types.py index 2c04cf10..a6d0596e 100644 --- a/cloudvolume/types.py +++ b/cloudvolume/types.py @@ -6,4 +6,12 @@ SecretsType = Optional[Union[str,dict]] MipType = Union[int, List[int]] ShapeType = Tuple[int,int,int] -ProgressType = Union[bool,str] \ No newline at end of file +ProgressType = Union[bool,str] + + +try: + from enum import StrEnum +except ImportError: + import enum + class StrEnum(str, enum.Enum): + pass \ No newline at end of file diff --git a/test/test_annotations.py b/test/test_annotations.py new file mode 100644 index 00000000..cd3163e1 --- /dev/null +++ b/test/test_annotations.py @@ -0,0 +1,37 @@ +import pytest + +import os + +import numpy as np + +import cloudvolume + +@pytest.fixture +def asrc(): + test_dir = os.path.dirname(os.path.abspath(__file__)) + test_dir = os.path.join(test_dir, "test_precomputed_annotation") + return cloudvolume.from_cloudpath("file://" + test_dir) + + +def test_annotation(asrc): + assert asrc.meta.info["@type"] == "neuroglancer_annotations_v1" + + elem = asrc.get_by_id(3867588737) + ans = np.array([[1.937760e+06, 1.318752e+06, 9.692100e+04]], dtype=np.float32) + assert np.all(np.isclose(elem.geometry, ans)) + + elem = asrc.get_by_relationship("skeleton_id", 243895108) + assert elem.geometry.shape[0] == 4 + + pd = elem.pandas() + assert set(pd["class_label"]) == {'axon'} + + all_pts = asrc.get_all(mip=0) + assert str(all_pts.type) == "POINT" + assert all_pts.geometry.shape == (10043,3) + + pd = all_pts.pandas() + assert len(set(pd["class_label"])) == 7 + + annos = all_pts.split_by_id() + assert len(annos) == 10043 \ No newline at end of file diff --git a/test/test_precomputed_annotation/README.md b/test/test_precomputed_annotation/README.md new file mode 100644 index 00000000..08565ed7 --- /dev/null +++ b/test/test_precomputed_annotation/README.md @@ -0,0 +1,7 @@ +Note: example taken and modified from the H01 dataset. + +gs://h01-release/data/20210601/c2/subcompartments/annotations/ + +https://h01-release.storage.googleapis.com/data.html + +Which is licensed under https://creativecommons.org/licenses/by/4.0/ \ No newline at end of file diff --git a/test/test_precomputed_annotation/by_id/3867588737.gz b/test/test_precomputed_annotation/by_id/3867588737.gz new file mode 100644 index 00000000..320a2351 Binary files /dev/null and b/test/test_precomputed_annotation/by_id/3867588737.gz differ diff --git a/test/test_precomputed_annotation/info b/test/test_precomputed_annotation/info new file mode 100644 index 00000000..ae05acc6 --- /dev/null +++ b/test/test_precomputed_annotation/info @@ -0,0 +1 @@ +{"@type": "neuroglancer_annotations_v1", "annotation_type": "POINT", "by_id": {"key": "by_id"}, "dimensions": {"x": [1, "nm"], "y": [1, "nm"], "z": [1, "nm"]}, "lower_bound": [517248, 314944, 2145], "properties": [{"id": "class_label", "type": "int32", "enum_values": [0, 1, 2, 3, 4, 5, 1000, 1001, 1002, 1003, 1004, 1005], "enum_labels": ["axon", "dendrite", "astrocyte", "soma", "cilium", "AIS", "myelinated axon", "myelinated axon", "myelinated fragment", "myelinated fragment", "myelinated fragment", "myelinated fragment"]}], "relationships": [{"id": "skeleton_id", "key": "skeleton_id" }], "spatial": [{"chunk_size": [3362817, 2057249, 170380], "grid_shape": [1, 1, 1], "key": "spatial0", "limit": 10000}, {"chunk_size": [1681408.5, 2057249, 170380], "grid_shape": [2, 1, 1], "key": "spatial1", "limit": 10000, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 0, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 0}}, {"chunk_size": [840704.25, 1028624.5, 170380], "grid_shape": [4, 2, 1], "key": "spatial2", "limit": 10000, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 0, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 0}}, {"chunk_size": [420352.125, 514312.25, 170380], "grid_shape": [8, 4, 1], "key": "spatial3", "limit": 10000, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 0, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 0}}, {"chunk_size": [210176.0625, 257156.125, 170380], "grid_shape": [16, 8, 1], "key": "spatial4", "limit": 10000, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 0, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 0}}, {"chunk_size": [105088.03125, 128578.0625, 170380], "grid_shape": [32, 16, 1], "key": "spatial5", "limit": 10000, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 0, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 0}}, {"chunk_size": [105088.03125, 64289.03125, 85190], "grid_shape": [32, 32, 2], "key": "spatial6", "limit": 10000, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 2, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 0}}, {"chunk_size": [52544.015625, 64289.03125, 42595], "grid_shape": [64, 32, 4], "key": "spatial7", "limit": 10000, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 2, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 2}}, {"chunk_size": [26272.0078125, 32144.515625, 42595], "grid_shape": [128, 64, 4], "key": "spatial8", "limit": 10000, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 2, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 4}}, {"chunk_size": [26272.0078125, 16072.2578125, 21297.5], "grid_shape": [128, 128, 8], "key": "spatial9", "limit": 10000, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 2, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 6}}, {"chunk_size": [13136.00390625, 16072.2578125, 10648.75], "grid_shape": [256, 128, 16], "key": "spatial10", "limit": 10000, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 3, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 7}}, {"chunk_size": [6568.001953125, 8036.12890625, 10648.75], "grid_shape": [512, 256, 16], "key": "spatial11", "limit": 2107, "sharding": {"@type": "neuroglancer_uint64_sharded_v1", "data_encoding": "gzip", "hash": "identity", "minishard_bits": 5, "minishard_index_encoding": "gzip", "preshift_bits": 10, "shard_bits": 7}}], "upper_bound": [3880065, 2372193, 172525]} \ No newline at end of file diff --git a/test/test_precomputed_annotation/skeleton_id/243895108.gz b/test/test_precomputed_annotation/skeleton_id/243895108.gz new file mode 100644 index 00000000..01016431 Binary files /dev/null and b/test/test_precomputed_annotation/skeleton_id/243895108.gz differ diff --git a/test/test_precomputed_annotation/spatial0/0_0_0.gz b/test/test_precomputed_annotation/spatial0/0_0_0.gz new file mode 100644 index 00000000..dd4e668e Binary files /dev/null and b/test/test_precomputed_annotation/spatial0/0_0_0.gz differ diff --git a/test/test_sharding.py b/test/test_sharding.py index e0edca33..461fe74e 100644 --- a/test/test_sharding.py +++ b/test/test_sharding.py @@ -6,7 +6,10 @@ from cloudvolume import CloudVolume, Skeleton from cloudvolume.storage import SimpleStorage from cloudvolume.datasource.precomputed.image.common import ( - gridpoints, compressed_morton_code + gridpoints +) +from cloudvolume.datasource.precomputed.common import ( + compressed_morton_code ) from cloudvolume.datasource.precomputed.sharding import ( ShardingSpecification,