Unable to save subsetted Xenium sdata to .zarr #821

Description

@christinedien

The bug can be reproduced using one of the spatialdata example datasets: I had used the Xenium Aligned Breast Cancer dataset

Describe the bug
After subsetting a spatialdata object using sdata.query.bounding_box(...), attempting to save the new subset as a .zarr sometimes results in an irregular chunking error. This occurs after a sdata.write(...) command

To Reproduce
Code to reproduce the behavior:

import spatialdata as sd
import spatialdata_io
import squidpy as sq
import spatialdata_plot
sdata = sd.read_zarr("/path/to/data_aligned.zarr/")

The following subset calls DO NOT result in an error

subset = sdata.query.bounding_box(
axes=["x", "y"],
min_coordinate=[0,0],
max_coordinate=[15000,13000],
target_coordinate_system="global",
)
subset.write(f'../data/xenium/subset_test/subset.zarr', overwrite=True)
subset3 = sdata.query.bounding_box(
axes=["x", "y"],
min_coordinate=[0,0],
max_coordinate=[20000,13000],
target_coordinate_system="global",
)
subset3.write(f'../data/xenium/subset_test/subset3.zarr', overwrite=True)

The following subsetting examples DO result in an error:

subset2 = sdata.query.bounding_box(
axes=["x", "y"],
min_coordinate=[15000,0],
max_coordinate=[35000,13000],
target_coordinate_system="global",
)
subset2.write(f'../data/xenium/subset_test/subset2.zarr', overwrite=True)
subset4 = sdata.query.bounding_box(
axes=["x", "y"],
min_coordinate=[10000,0],
max_coordinate=[30000,13000],
target_coordinate_system="global",
)
subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)

I initially thought maybe the subset size may have something to do with the irregular chunking. In this case the query size (20,000 x 13,000) in subset2 and subset4 resulted in an error but subset3 has the same query size and was able to be saved.

In my private dataset, only 1/12 of my queries is savable

Expected behavior
I would have expected the subsetted spatialdata object to be savable to a .zarr

Screenshots

Image

sdata
Image

subset3 (no error)
Image

subset4 (error)
Image

Desktop (optional):
OS: Red Hat Enterprise Linux release 8.8 (Ootpa)

Additional context
This bug was briefly discussed in a thread of this PR

The bug results in the following traceback:

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[48], line 1
----> 1 subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
<conda_env_loc>
File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1186](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1185), in SpatialData.write(self, file_path, overwrite, consolidate_metadata, format)
1183 store.close()
1185 for element_type, element_name, element in self.gen_elements():
-> 1186 self._write_element(
1187 element=element,
1188 zarr_container_path=file_path,
1189 element_type=element_type,
1190 element_name=element_name,
1191 overwrite=False,
1192 format=format,
1193 )
1195 if self.path != file_path:
1196 old_path = self.path
File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1230](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1229), in SpatialData._write_element(self, element, zarr_container_path, element_type, element_name, overwrite, format)
1227 parsed = _parse_formats(formats=format)
1229 if element_type == "images":
-> 1230 write_image(image=element, group=element_type_group, name=element_name, format=parsed["raster"])
1231 elif element_type == "labels":
1232 write_labels(labels=element, group=root_group, name=element_name, format=parsed["raster"])
File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:242](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=241), in write_image(image, group, name, format, storage_options, **metadata)
234 def write_image(
235 image: DataArray | DataTree,
236 group: zarr.Group,
(...)
240 **metadata: str | JSONDict | list[JSONDict],
241 ) -> None:
--> 242 _write_raster(
243 raster_type="image",
244 raster_data=image,
245 group=group,
246 name=name,
247 format=format,
248 storage_options=storage_options,
249 **metadata,
250 )
File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:202](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=201), in _write_raster(raster_type, raster_data, group, name, format, storage_options, label_metadata, **metadata)
200 parsed_axes = _get_valid_axes(axes=list(input_axes), fmt=format)
201 storage_options = [{"chunks": chunk} for chunk in chunks]
--> 202 dask_delayed = write_multi_scale_ngff(
203 pyramid=data,
204 group=group_data,
205 fmt=format,
206 axes=parsed_axes,
207 coordinate_transformations=None,
208 storage_options=storage_options,
209 **metadata,
210 compute=False,
211 )
212 # Compute all pyramid levels at once to allow Dask to optimize the computational graph.
213 da.compute(*dask_delayed)
File [<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py:253](<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py#line=252), in write_multiscale(pyramid, group, chunks, fmt, axes, coordinate_transformations, storage_options, name, compute, **metadata)
251 data = da.array(data).rechunk(chunks=chunks_opt)
252 options["chunks"] = chunks_opt
--> 253 da_delayed = da.to_zarr(
254 arr=data,
255 url=group.store,
256 component=str(Path(group.path, str(path))),
257 storage_options=options,
258 compressor=options.get("compressor", zarr.storage.default_compressor),
259 dimension_separator=group._store._dimension_separator,
260 compute=compute,
261 )
263 if not compute:
264 dask_delayed.append(da_delayed)
File [<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py:3875](<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py#line=3874), in to_zarr(arr, url, component, storage_options, overwrite, region, compute, return_stored, **kwargs)
3872 raise ValueError("Cannot use `region` keyword when url is not a `zarr.Array`.")
3874 if not _check_regular_chunks(arr.chunks):
-> 3875 raise ValueError(
3876 "Attempt to save array to zarr with irregular "
3877 "chunking, please call `arr.rechunk(...)` first."
3878 )
3880 storage_options = storage_options or {}
3882 if storage_options:
ValueError: Attempt to save array to zarr with irregular chunking, please call `arr.rechunk(...)` first.
Click to add a cell.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      , 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
       blocks
      (function() {
      function addCopyButtons() {
      document.querySelectorAll('pre code').forEach(function(codeBlock) {
      if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
      codeBlock.parentElement.setAttribute('data-copy-added', 'true');
      var btn = document.createElement('button');
      btn.textContent = 'Copy';
      btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
      btn.onmouseover = function() { this.style.opacity = '1'; };
      btn.onmouseout = function() { this.style.opacity = '0.7'; };
      btn.onclick = function() {
      navigator.clipboard.writeText(codeBlock.textContent).then(function() {
      btn.textContent = 'Copied!';
      setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
      });
      };
      codeBlock.parentElement.style.position = 'relative';
      codeBlock.parentElement.appendChild(btn);
      });
      }
      addCopyButtons();
      // Re-run on dynamic content
      var observer = new MutationObserver(addCopyButtons);
      observer.observe(document.body, { childList: true, subtree: true });
      })();
      }
      } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
      })();
      (function(){
      try {
      var __m = "github.com";
      var __re = new RegExp('^' + "github\\.com" + '
      
      Skip to content

      Unable to save subsetted Xenium sdata to .zarr #821

      Description

      @christinedien

      The bug can be reproduced using one of the spatialdata example datasets: I had used the Xenium Aligned Breast Cancer dataset

      Describe the bug
      After subsetting a spatialdata object using sdata.query.bounding_box(...), attempting to save the new subset as a .zarr sometimes results in an irregular chunking error. This occurs after a sdata.write(...) command

      To Reproduce
      Code to reproduce the behavior:

      import spatialdata as sd
      import spatialdata_io
      import squidpy as sq
      import spatialdata_plot
      
      sdata = sd.read_zarr("/path/to/data_aligned.zarr/")
      

      The following subset calls DO NOT result in an error

      subset = sdata.query.bounding_box(
      axes=["x", "y"],
      min_coordinate=[0,0],
      max_coordinate=[15000,13000],
      target_coordinate_system="global",
      )
      subset.write(f'../data/xenium/subset_test/subset.zarr', overwrite=True)
      
      subset3 = sdata.query.bounding_box(
      axes=["x", "y"],
      min_coordinate=[0,0],
      max_coordinate=[20000,13000],
      target_coordinate_system="global",
      )
      subset3.write(f'../data/xenium/subset_test/subset3.zarr', overwrite=True)
      

      The following subsetting examples DO result in an error:

      subset2 = sdata.query.bounding_box(
      axes=["x", "y"],
      min_coordinate=[15000,0],
      max_coordinate=[35000,13000],
      target_coordinate_system="global",
      )
      subset2.write(f'../data/xenium/subset_test/subset2.zarr', overwrite=True)
      
      subset4 = sdata.query.bounding_box(
      axes=["x", "y"],
      min_coordinate=[10000,0],
      max_coordinate=[30000,13000],
      target_coordinate_system="global",
      )
      subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
      

      I initially thought maybe the subset size may have something to do with the irregular chunking. In this case the query size (20,000 x 13,000) in subset2 and subset4 resulted in an error but subset3 has the same query size and was able to be saved.

      In my private dataset, only 1/12 of my queries is savable

      Expected behavior
      I would have expected the subsetted spatialdata object to be savable to a .zarr

      Screenshots

      Image

      sdata
      Image

      subset3 (no error)
      Image

      subset4 (error)
      Image

      Desktop (optional):
      OS: Red Hat Enterprise Linux release 8.8 (Ootpa)

      Additional context
      This bug was briefly discussed in a thread of this PR

      The bug results in the following traceback:

      ---------------------------------------------------------------------------
      ValueError Traceback (most recent call last)
      Cell In[48], line 1
      ----> 1 subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
      <conda_env_loc>
      File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1186](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1185), in SpatialData.write(self, file_path, overwrite, consolidate_metadata, format)
      1183 store.close()
      1185 for element_type, element_name, element in self.gen_elements():
      -> 1186 self._write_element(
      1187 element=element,
      1188 zarr_container_path=file_path,
      1189 element_type=element_type,
      1190 element_name=element_name,
      1191 overwrite=False,
      1192 format=format,
      1193 )
      1195 if self.path != file_path:
      1196 old_path = self.path
      File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1230](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1229), in SpatialData._write_element(self, element, zarr_container_path, element_type, element_name, overwrite, format)
      1227 parsed = _parse_formats(formats=format)
      1229 if element_type == "images":
      -> 1230 write_image(image=element, group=element_type_group, name=element_name, format=parsed["raster"])
      1231 elif element_type == "labels":
      1232 write_labels(labels=element, group=root_group, name=element_name, format=parsed["raster"])
      File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:242](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=241), in write_image(image, group, name, format, storage_options, **metadata)
      234 def write_image(
      235 image: DataArray | DataTree,
      236 group: zarr.Group,
      (...)
      240 **metadata: str | JSONDict | list[JSONDict],
      241 ) -> None:
      --> 242 _write_raster(
      243 raster_type="image",
      244 raster_data=image,
      245 group=group,
      246 name=name,
      247 format=format,
      248 storage_options=storage_options,
      249 **metadata,
      250 )
      File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:202](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=201), in _write_raster(raster_type, raster_data, group, name, format, storage_options, label_metadata, **metadata)
      200 parsed_axes = _get_valid_axes(axes=list(input_axes), fmt=format)
      201 storage_options = [{"chunks": chunk} for chunk in chunks]
      --> 202 dask_delayed = write_multi_scale_ngff(
      203 pyramid=data,
      204 group=group_data,
      205 fmt=format,
      206 axes=parsed_axes,
      207 coordinate_transformations=None,
      208 storage_options=storage_options,
      209 **metadata,
      210 compute=False,
      211 )
      212 # Compute all pyramid levels at once to allow Dask to optimize the computational graph.
      213 da.compute(*dask_delayed)
      File [<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py:253](<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py#line=252), in write_multiscale(pyramid, group, chunks, fmt, axes, coordinate_transformations, storage_options, name, compute, **metadata)
      251 data = da.array(data).rechunk(chunks=chunks_opt)
      252 options["chunks"] = chunks_opt
      --> 253 da_delayed = da.to_zarr(
      254 arr=data,
      255 url=group.store,
      256 component=str(Path(group.path, str(path))),
      257 storage_options=options,
      258 compressor=options.get("compressor", zarr.storage.default_compressor),
      259 dimension_separator=group._store._dimension_separator,
      260 compute=compute,
      261 )
      263 if not compute:
      264 dask_delayed.append(da_delayed)
      File [<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py:3875](<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py#line=3874), in to_zarr(arr, url, component, storage_options, overwrite, region, compute, return_stored, **kwargs)
      3872 raise ValueError("Cannot use `region` keyword when url is not a `zarr.Array`.")
      3874 if not _check_regular_chunks(arr.chunks):
      -> 3875 raise ValueError(
      3876 "Attempt to save array to zarr with irregular "
      3877 "chunking, please call `arr.rechunk(...)` first."
      3878 )
      3880 storage_options = storage_options or {}
      3882 if storage_options:
      ValueError: Attempt to save array to zarr with irregular chunking, please call `arr.rechunk(...)` first.
      Click to add a cell.
      

      Metadata

      Metadata

      Assignees

      No one assigned

        Labels

        No labels
        No labels

        Type

        No type

        Projects

        No projects

          Milestone

          No milestone

          Relationships

          None yet

          Development

          No branches or pull requests

          Issue actions

          , 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
          Skip to content

          Unable to save subsetted Xenium sdata to .zarr #821

          Description

          @christinedien

          The bug can be reproduced using one of the spatialdata example datasets: I had used the Xenium Aligned Breast Cancer dataset

          Describe the bug
          After subsetting a spatialdata object using sdata.query.bounding_box(...), attempting to save the new subset as a .zarr sometimes results in an irregular chunking error. This occurs after a sdata.write(...) command

          To Reproduce
          Code to reproduce the behavior:

          import spatialdata as sd
          import spatialdata_io
          import squidpy as sq
          import spatialdata_plot
          
          sdata = sd.read_zarr("/path/to/data_aligned.zarr/")
          

          The following subset calls DO NOT result in an error

          subset = sdata.query.bounding_box(
          axes=["x", "y"],
          min_coordinate=[0,0],
          max_coordinate=[15000,13000],
          target_coordinate_system="global",
          )
          subset.write(f'../data/xenium/subset_test/subset.zarr', overwrite=True)
          
          subset3 = sdata.query.bounding_box(
          axes=["x", "y"],
          min_coordinate=[0,0],
          max_coordinate=[20000,13000],
          target_coordinate_system="global",
          )
          subset3.write(f'../data/xenium/subset_test/subset3.zarr', overwrite=True)
          

          The following subsetting examples DO result in an error:

          subset2 = sdata.query.bounding_box(
          axes=["x", "y"],
          min_coordinate=[15000,0],
          max_coordinate=[35000,13000],
          target_coordinate_system="global",
          )
          subset2.write(f'../data/xenium/subset_test/subset2.zarr', overwrite=True)
          
          subset4 = sdata.query.bounding_box(
          axes=["x", "y"],
          min_coordinate=[10000,0],
          max_coordinate=[30000,13000],
          target_coordinate_system="global",
          )
          subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
          

          I initially thought maybe the subset size may have something to do with the irregular chunking. In this case the query size (20,000 x 13,000) in subset2 and subset4 resulted in an error but subset3 has the same query size and was able to be saved.

          In my private dataset, only 1/12 of my queries is savable

          Expected behavior
          I would have expected the subsetted spatialdata object to be savable to a .zarr

          Screenshots

          Image

          sdata
          Image

          subset3 (no error)
          Image

          subset4 (error)
          Image

          Desktop (optional):
          OS: Red Hat Enterprise Linux release 8.8 (Ootpa)

          Additional context
          This bug was briefly discussed in a thread of this PR

          The bug results in the following traceback:

          ---------------------------------------------------------------------------
          ValueError Traceback (most recent call last)
          Cell In[48], line 1
          ----> 1 subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
          <conda_env_loc>
          File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1186](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1185), in SpatialData.write(self, file_path, overwrite, consolidate_metadata, format)
          1183 store.close()
          1185 for element_type, element_name, element in self.gen_elements():
          -> 1186 self._write_element(
          1187 element=element,
          1188 zarr_container_path=file_path,
          1189 element_type=element_type,
          1190 element_name=element_name,
          1191 overwrite=False,
          1192 format=format,
          1193 )
          1195 if self.path != file_path:
          1196 old_path = self.path
          File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1230](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1229), in SpatialData._write_element(self, element, zarr_container_path, element_type, element_name, overwrite, format)
          1227 parsed = _parse_formats(formats=format)
          1229 if element_type == "images":
          -> 1230 write_image(image=element, group=element_type_group, name=element_name, format=parsed["raster"])
          1231 elif element_type == "labels":
          1232 write_labels(labels=element, group=root_group, name=element_name, format=parsed["raster"])
          File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:242](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=241), in write_image(image, group, name, format, storage_options, **metadata)
          234 def write_image(
          235 image: DataArray | DataTree,
          236 group: zarr.Group,
          (...)
          240 **metadata: str | JSONDict | list[JSONDict],
          241 ) -> None:
          --> 242 _write_raster(
          243 raster_type="image",
          244 raster_data=image,
          245 group=group,
          246 name=name,
          247 format=format,
          248 storage_options=storage_options,
          249 **metadata,
          250 )
          File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:202](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=201), in _write_raster(raster_type, raster_data, group, name, format, storage_options, label_metadata, **metadata)
          200 parsed_axes = _get_valid_axes(axes=list(input_axes), fmt=format)
          201 storage_options = [{"chunks": chunk} for chunk in chunks]
          --> 202 dask_delayed = write_multi_scale_ngff(
          203 pyramid=data,
          204 group=group_data,
          205 fmt=format,
          206 axes=parsed_axes,
          207 coordinate_transformations=None,
          208 storage_options=storage_options,
          209 **metadata,
          210 compute=False,
          211 )
          212 # Compute all pyramid levels at once to allow Dask to optimize the computational graph.
          213 da.compute(*dask_delayed)
          File [<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py:253](<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py#line=252), in write_multiscale(pyramid, group, chunks, fmt, axes, coordinate_transformations, storage_options, name, compute, **metadata)
          251 data = da.array(data).rechunk(chunks=chunks_opt)
          252 options["chunks"] = chunks_opt
          --> 253 da_delayed = da.to_zarr(
          254 arr=data,
          255 url=group.store,
          256 component=str(Path(group.path, str(path))),
          257 storage_options=options,
          258 compressor=options.get("compressor", zarr.storage.default_compressor),
          259 dimension_separator=group._store._dimension_separator,
          260 compute=compute,
          261 )
          263 if not compute:
          264 dask_delayed.append(da_delayed)
          File [<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py:3875](<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py#line=3874), in to_zarr(arr, url, component, storage_options, overwrite, region, compute, return_stored, **kwargs)
          3872 raise ValueError("Cannot use `region` keyword when url is not a `zarr.Array`.")
          3874 if not _check_regular_chunks(arr.chunks):
          -> 3875 raise ValueError(
          3876 "Attempt to save array to zarr with irregular "
          3877 "chunking, please call `arr.rechunk(...)` first."
          3878 )
          3880 storage_options = storage_options or {}
          3882 if storage_options:
          ValueError: Attempt to save array to zarr with irregular chunking, please call `arr.rechunk(...)` first.
          Click to add a cell.
          

          Metadata

          Metadata

          Assignees

          No one assigned

            Labels

            No labels
            No labels

            Type

            No type

            Projects

            No projects

              Milestone

              No milestone

              Relationships

              None yet

              Development

              No branches or pull requests

              Issue actions

              , 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
              Skip to content

              Unable to save subsetted Xenium sdata to .zarr #821

              Description

              @christinedien

              The bug can be reproduced using one of the spatialdata example datasets: I had used the Xenium Aligned Breast Cancer dataset

              Describe the bug
              After subsetting a spatialdata object using sdata.query.bounding_box(...), attempting to save the new subset as a .zarr sometimes results in an irregular chunking error. This occurs after a sdata.write(...) command

              To Reproduce
              Code to reproduce the behavior:

              import spatialdata as sd
              import spatialdata_io
              import squidpy as sq
              import spatialdata_plot
              
              sdata = sd.read_zarr("/path/to/data_aligned.zarr/")
              

              The following subset calls DO NOT result in an error

              subset = sdata.query.bounding_box(
              axes=["x", "y"],
              min_coordinate=[0,0],
              max_coordinate=[15000,13000],
              target_coordinate_system="global",
              )
              subset.write(f'../data/xenium/subset_test/subset.zarr', overwrite=True)
              
              subset3 = sdata.query.bounding_box(
              axes=["x", "y"],
              min_coordinate=[0,0],
              max_coordinate=[20000,13000],
              target_coordinate_system="global",
              )
              subset3.write(f'../data/xenium/subset_test/subset3.zarr', overwrite=True)
              

              The following subsetting examples DO result in an error:

              subset2 = sdata.query.bounding_box(
              axes=["x", "y"],
              min_coordinate=[15000,0],
              max_coordinate=[35000,13000],
              target_coordinate_system="global",
              )
              subset2.write(f'../data/xenium/subset_test/subset2.zarr', overwrite=True)
              
              subset4 = sdata.query.bounding_box(
              axes=["x", "y"],
              min_coordinate=[10000,0],
              max_coordinate=[30000,13000],
              target_coordinate_system="global",
              )
              subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
              

              I initially thought maybe the subset size may have something to do with the irregular chunking. In this case the query size (20,000 x 13,000) in subset2 and subset4 resulted in an error but subset3 has the same query size and was able to be saved.

              In my private dataset, only 1/12 of my queries is savable

              Expected behavior
              I would have expected the subsetted spatialdata object to be savable to a .zarr

              Screenshots

              Image

              sdata
              Image

              subset3 (no error)
              Image

              subset4 (error)
              Image

              Desktop (optional):
              OS: Red Hat Enterprise Linux release 8.8 (Ootpa)

              Additional context
              This bug was briefly discussed in a thread of this PR

              The bug results in the following traceback:

              ---------------------------------------------------------------------------
              ValueError Traceback (most recent call last)
              Cell In[48], line 1
              ----> 1 subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
              <conda_env_loc>
              File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1186](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1185), in SpatialData.write(self, file_path, overwrite, consolidate_metadata, format)
              1183 store.close()
              1185 for element_type, element_name, element in self.gen_elements():
              -> 1186 self._write_element(
              1187 element=element,
              1188 zarr_container_path=file_path,
              1189 element_type=element_type,
              1190 element_name=element_name,
              1191 overwrite=False,
              1192 format=format,
              1193 )
              1195 if self.path != file_path:
              1196 old_path = self.path
              File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1230](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1229), in SpatialData._write_element(self, element, zarr_container_path, element_type, element_name, overwrite, format)
              1227 parsed = _parse_formats(formats=format)
              1229 if element_type == "images":
              -> 1230 write_image(image=element, group=element_type_group, name=element_name, format=parsed["raster"])
              1231 elif element_type == "labels":
              1232 write_labels(labels=element, group=root_group, name=element_name, format=parsed["raster"])
              File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:242](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=241), in write_image(image, group, name, format, storage_options, **metadata)
              234 def write_image(
              235 image: DataArray | DataTree,
              236 group: zarr.Group,
              (...)
              240 **metadata: str | JSONDict | list[JSONDict],
              241 ) -> None:
              --> 242 _write_raster(
              243 raster_type="image",
              244 raster_data=image,
              245 group=group,
              246 name=name,
              247 format=format,
              248 storage_options=storage_options,
              249 **metadata,
              250 )
              File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:202](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=201), in _write_raster(raster_type, raster_data, group, name, format, storage_options, label_metadata, **metadata)
              200 parsed_axes = _get_valid_axes(axes=list(input_axes), fmt=format)
              201 storage_options = [{"chunks": chunk} for chunk in chunks]
              --> 202 dask_delayed = write_multi_scale_ngff(
              203 pyramid=data,
              204 group=group_data,
              205 fmt=format,
              206 axes=parsed_axes,
              207 coordinate_transformations=None,
              208 storage_options=storage_options,
              209 **metadata,
              210 compute=False,
              211 )
              212 # Compute all pyramid levels at once to allow Dask to optimize the computational graph.
              213 da.compute(*dask_delayed)
              File [<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py:253](<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py#line=252), in write_multiscale(pyramid, group, chunks, fmt, axes, coordinate_transformations, storage_options, name, compute, **metadata)
              251 data = da.array(data).rechunk(chunks=chunks_opt)
              252 options["chunks"] = chunks_opt
              --> 253 da_delayed = da.to_zarr(
              254 arr=data,
              255 url=group.store,
              256 component=str(Path(group.path, str(path))),
              257 storage_options=options,
              258 compressor=options.get("compressor", zarr.storage.default_compressor),
              259 dimension_separator=group._store._dimension_separator,
              260 compute=compute,
              261 )
              263 if not compute:
              264 dask_delayed.append(da_delayed)
              File [<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py:3875](<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py#line=3874), in to_zarr(arr, url, component, storage_options, overwrite, region, compute, return_stored, **kwargs)
              3872 raise ValueError("Cannot use `region` keyword when url is not a `zarr.Array`.")
              3874 if not _check_regular_chunks(arr.chunks):
              -> 3875 raise ValueError(
              3876 "Attempt to save array to zarr with irregular "
              3877 "chunking, please call `arr.rechunk(...)` first."
              3878 )
              3880 storage_options = storage_options or {}
              3882 if storage_options:
              ValueError: Attempt to save array to zarr with irregular chunking, please call `arr.rechunk(...)` first.
              Click to add a cell.
              

              Metadata

              Metadata

              Assignees

              No one assigned

                Labels

                No labels
                No labels

                Type

                No type

                Projects

                No projects

                  Milestone

                  No milestone

                  Relationships

                  None yet

                  Development

                  No branches or pull requests

                  Issue actions

                  , 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
                  Skip to content

                  Unable to save subsetted Xenium sdata to .zarr #821

                  Description

                  @christinedien

                  The bug can be reproduced using one of the spatialdata example datasets: I had used the Xenium Aligned Breast Cancer dataset

                  Describe the bug
                  After subsetting a spatialdata object using sdata.query.bounding_box(...), attempting to save the new subset as a .zarr sometimes results in an irregular chunking error. This occurs after a sdata.write(...) command

                  To Reproduce
                  Code to reproduce the behavior:

                  import spatialdata as sd
                  import spatialdata_io
                  import squidpy as sq
                  import spatialdata_plot
                  
                  sdata = sd.read_zarr("/path/to/data_aligned.zarr/")
                  

                  The following subset calls DO NOT result in an error

                  subset = sdata.query.bounding_box(
                  axes=["x", "y"],
                  min_coordinate=[0,0],
                  max_coordinate=[15000,13000],
                  target_coordinate_system="global",
                  )
                  subset.write(f'../data/xenium/subset_test/subset.zarr', overwrite=True)
                  
                  subset3 = sdata.query.bounding_box(
                  axes=["x", "y"],
                  min_coordinate=[0,0],
                  max_coordinate=[20000,13000],
                  target_coordinate_system="global",
                  )
                  subset3.write(f'../data/xenium/subset_test/subset3.zarr', overwrite=True)
                  

                  The following subsetting examples DO result in an error:

                  subset2 = sdata.query.bounding_box(
                  axes=["x", "y"],
                  min_coordinate=[15000,0],
                  max_coordinate=[35000,13000],
                  target_coordinate_system="global",
                  )
                  subset2.write(f'../data/xenium/subset_test/subset2.zarr', overwrite=True)
                  
                  subset4 = sdata.query.bounding_box(
                  axes=["x", "y"],
                  min_coordinate=[10000,0],
                  max_coordinate=[30000,13000],
                  target_coordinate_system="global",
                  )
                  subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
                  

                  I initially thought maybe the subset size may have something to do with the irregular chunking. In this case the query size (20,000 x 13,000) in subset2 and subset4 resulted in an error but subset3 has the same query size and was able to be saved.

                  In my private dataset, only 1/12 of my queries is savable

                  Expected behavior
                  I would have expected the subsetted spatialdata object to be savable to a .zarr

                  Screenshots

                  Image

                  sdata
                  Image

                  subset3 (no error)
                  Image

                  subset4 (error)
                  Image

                  Desktop (optional):
                  OS: Red Hat Enterprise Linux release 8.8 (Ootpa)

                  Additional context
                  This bug was briefly discussed in a thread of this PR

                  The bug results in the following traceback:

                  ---------------------------------------------------------------------------
                  ValueError Traceback (most recent call last)
                  Cell In[48], line 1
                  ----> 1 subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
                  <conda_env_loc>
                  File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1186](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1185), in SpatialData.write(self, file_path, overwrite, consolidate_metadata, format)
                  1183 store.close()
                  1185 for element_type, element_name, element in self.gen_elements():
                  -> 1186 self._write_element(
                  1187 element=element,
                  1188 zarr_container_path=file_path,
                  1189 element_type=element_type,
                  1190 element_name=element_name,
                  1191 overwrite=False,
                  1192 format=format,
                  1193 )
                  1195 if self.path != file_path:
                  1196 old_path = self.path
                  File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1230](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1229), in SpatialData._write_element(self, element, zarr_container_path, element_type, element_name, overwrite, format)
                  1227 parsed = _parse_formats(formats=format)
                  1229 if element_type == "images":
                  -> 1230 write_image(image=element, group=element_type_group, name=element_name, format=parsed["raster"])
                  1231 elif element_type == "labels":
                  1232 write_labels(labels=element, group=root_group, name=element_name, format=parsed["raster"])
                  File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:242](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=241), in write_image(image, group, name, format, storage_options, **metadata)
                  234 def write_image(
                  235 image: DataArray | DataTree,
                  236 group: zarr.Group,
                  (...)
                  240 **metadata: str | JSONDict | list[JSONDict],
                  241 ) -> None:
                  --> 242 _write_raster(
                  243 raster_type="image",
                  244 raster_data=image,
                  245 group=group,
                  246 name=name,
                  247 format=format,
                  248 storage_options=storage_options,
                  249 **metadata,
                  250 )
                  File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:202](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=201), in _write_raster(raster_type, raster_data, group, name, format, storage_options, label_metadata, **metadata)
                  200 parsed_axes = _get_valid_axes(axes=list(input_axes), fmt=format)
                  201 storage_options = [{"chunks": chunk} for chunk in chunks]
                  --> 202 dask_delayed = write_multi_scale_ngff(
                  203 pyramid=data,
                  204 group=group_data,
                  205 fmt=format,
                  206 axes=parsed_axes,
                  207 coordinate_transformations=None,
                  208 storage_options=storage_options,
                  209 **metadata,
                  210 compute=False,
                  211 )
                  212 # Compute all pyramid levels at once to allow Dask to optimize the computational graph.
                  213 da.compute(*dask_delayed)
                  File [<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py:253](<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py#line=252), in write_multiscale(pyramid, group, chunks, fmt, axes, coordinate_transformations, storage_options, name, compute, **metadata)
                  251 data = da.array(data).rechunk(chunks=chunks_opt)
                  252 options["chunks"] = chunks_opt
                  --> 253 da_delayed = da.to_zarr(
                  254 arr=data,
                  255 url=group.store,
                  256 component=str(Path(group.path, str(path))),
                  257 storage_options=options,
                  258 compressor=options.get("compressor", zarr.storage.default_compressor),
                  259 dimension_separator=group._store._dimension_separator,
                  260 compute=compute,
                  261 )
                  263 if not compute:
                  264 dask_delayed.append(da_delayed)
                  File [<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py:3875](<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py#line=3874), in to_zarr(arr, url, component, storage_options, overwrite, region, compute, return_stored, **kwargs)
                  3872 raise ValueError("Cannot use `region` keyword when url is not a `zarr.Array`.")
                  3874 if not _check_regular_chunks(arr.chunks):
                  -> 3875 raise ValueError(
                  3876 "Attempt to save array to zarr with irregular "
                  3877 "chunking, please call `arr.rechunk(...)` first."
                  3878 )
                  3880 storage_options = storage_options or {}
                  3882 if storage_options:
                  ValueError: Attempt to save array to zarr with irregular chunking, please call `arr.rechunk(...)` first.
                  Click to add a cell.
                  

                  Metadata

                  Metadata

                  Assignees

                  No one assigned

                    Labels

                    No labels
                    No labels

                    Type

                    No type

                    Projects

                    No projects

                      Milestone

                      No milestone

                      Relationships

                      None yet

                      Development

                      No branches or pull requests

                      Issue actions

                      , 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
                      Skip to content

                      Unable to save subsetted Xenium sdata to .zarr #821

                      Description

                      @christinedien

                      The bug can be reproduced using one of the spatialdata example datasets: I had used the Xenium Aligned Breast Cancer dataset

                      Describe the bug
                      After subsetting a spatialdata object using sdata.query.bounding_box(...), attempting to save the new subset as a .zarr sometimes results in an irregular chunking error. This occurs after a sdata.write(...) command

                      To Reproduce
                      Code to reproduce the behavior:

                      import spatialdata as sd
                      import spatialdata_io
                      import squidpy as sq
                      import spatialdata_plot
                      
                      sdata = sd.read_zarr("/path/to/data_aligned.zarr/")
                      

                      The following subset calls DO NOT result in an error

                      subset = sdata.query.bounding_box(
                      axes=["x", "y"],
                      min_coordinate=[0,0],
                      max_coordinate=[15000,13000],
                      target_coordinate_system="global",
                      )
                      subset.write(f'../data/xenium/subset_test/subset.zarr', overwrite=True)
                      
                      subset3 = sdata.query.bounding_box(
                      axes=["x", "y"],
                      min_coordinate=[0,0],
                      max_coordinate=[20000,13000],
                      target_coordinate_system="global",
                      )
                      subset3.write(f'../data/xenium/subset_test/subset3.zarr', overwrite=True)
                      

                      The following subsetting examples DO result in an error:

                      subset2 = sdata.query.bounding_box(
                      axes=["x", "y"],
                      min_coordinate=[15000,0],
                      max_coordinate=[35000,13000],
                      target_coordinate_system="global",
                      )
                      subset2.write(f'../data/xenium/subset_test/subset2.zarr', overwrite=True)
                      
                      subset4 = sdata.query.bounding_box(
                      axes=["x", "y"],
                      min_coordinate=[10000,0],
                      max_coordinate=[30000,13000],
                      target_coordinate_system="global",
                      )
                      subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
                      

                      I initially thought maybe the subset size may have something to do with the irregular chunking. In this case the query size (20,000 x 13,000) in subset2 and subset4 resulted in an error but subset3 has the same query size and was able to be saved.

                      In my private dataset, only 1/12 of my queries is savable

                      Expected behavior
                      I would have expected the subsetted spatialdata object to be savable to a .zarr

                      Screenshots

                      Image

                      sdata
                      Image

                      subset3 (no error)
                      Image

                      subset4 (error)
                      Image

                      Desktop (optional):
                      OS: Red Hat Enterprise Linux release 8.8 (Ootpa)

                      Additional context
                      This bug was briefly discussed in a thread of this PR

                      The bug results in the following traceback:

                      ---------------------------------------------------------------------------
                      ValueError Traceback (most recent call last)
                      Cell In[48], line 1
                      ----> 1 subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
                      <conda_env_loc>
                      File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1186](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1185), in SpatialData.write(self, file_path, overwrite, consolidate_metadata, format)
                      1183 store.close()
                      1185 for element_type, element_name, element in self.gen_elements():
                      -> 1186 self._write_element(
                      1187 element=element,
                      1188 zarr_container_path=file_path,
                      1189 element_type=element_type,
                      1190 element_name=element_name,
                      1191 overwrite=False,
                      1192 format=format,
                      1193 )
                      1195 if self.path != file_path:
                      1196 old_path = self.path
                      File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1230](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1229), in SpatialData._write_element(self, element, zarr_container_path, element_type, element_name, overwrite, format)
                      1227 parsed = _parse_formats(formats=format)
                      1229 if element_type == "images":
                      -> 1230 write_image(image=element, group=element_type_group, name=element_name, format=parsed["raster"])
                      1231 elif element_type == "labels":
                      1232 write_labels(labels=element, group=root_group, name=element_name, format=parsed["raster"])
                      File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:242](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=241), in write_image(image, group, name, format, storage_options, **metadata)
                      234 def write_image(
                      235 image: DataArray | DataTree,
                      236 group: zarr.Group,
                      (...)
                      240 **metadata: str | JSONDict | list[JSONDict],
                      241 ) -> None:
                      --> 242 _write_raster(
                      243 raster_type="image",
                      244 raster_data=image,
                      245 group=group,
                      246 name=name,
                      247 format=format,
                      248 storage_options=storage_options,
                      249 **metadata,
                      250 )
                      File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:202](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=201), in _write_raster(raster_type, raster_data, group, name, format, storage_options, label_metadata, **metadata)
                      200 parsed_axes = _get_valid_axes(axes=list(input_axes), fmt=format)
                      201 storage_options = [{"chunks": chunk} for chunk in chunks]
                      --> 202 dask_delayed = write_multi_scale_ngff(
                      203 pyramid=data,
                      204 group=group_data,
                      205 fmt=format,
                      206 axes=parsed_axes,
                      207 coordinate_transformations=None,
                      208 storage_options=storage_options,
                      209 **metadata,
                      210 compute=False,
                      211 )
                      212 # Compute all pyramid levels at once to allow Dask to optimize the computational graph.
                      213 da.compute(*dask_delayed)
                      File [<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py:253](<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py#line=252), in write_multiscale(pyramid, group, chunks, fmt, axes, coordinate_transformations, storage_options, name, compute, **metadata)
                      251 data = da.array(data).rechunk(chunks=chunks_opt)
                      252 options["chunks"] = chunks_opt
                      --> 253 da_delayed = da.to_zarr(
                      254 arr=data,
                      255 url=group.store,
                      256 component=str(Path(group.path, str(path))),
                      257 storage_options=options,
                      258 compressor=options.get("compressor", zarr.storage.default_compressor),
                      259 dimension_separator=group._store._dimension_separator,
                      260 compute=compute,
                      261 )
                      263 if not compute:
                      264 dask_delayed.append(da_delayed)
                      File [<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py:3875](<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py#line=3874), in to_zarr(arr, url, component, storage_options, overwrite, region, compute, return_stored, **kwargs)
                      3872 raise ValueError("Cannot use `region` keyword when url is not a `zarr.Array`.")
                      3874 if not _check_regular_chunks(arr.chunks):
                      -> 3875 raise ValueError(
                      3876 "Attempt to save array to zarr with irregular "
                      3877 "chunking, please call `arr.rechunk(...)` first."
                      3878 )
                      3880 storage_options = storage_options or {}
                      3882 if storage_options:
                      ValueError: Attempt to save array to zarr with irregular chunking, please call `arr.rechunk(...)` first.
                      Click to add a cell.
                      

                      Metadata

                      Metadata

                      Assignees

                      No one assigned

                        Labels

                        No labels
                        No labels

                        Type

                        No type

                        Projects

                        No projects

                          Milestone

                          No milestone

                          Relationships

                          None yet

                          Development

                          No branches or pull requests

                          Issue actions

                          , 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
                          Skip to content

                          Unable to save subsetted Xenium sdata to .zarr #821

                          Description

                          @christinedien

                          The bug can be reproduced using one of the spatialdata example datasets: I had used the Xenium Aligned Breast Cancer dataset

                          Describe the bug
                          After subsetting a spatialdata object using sdata.query.bounding_box(...), attempting to save the new subset as a .zarr sometimes results in an irregular chunking error. This occurs after a sdata.write(...) command

                          To Reproduce
                          Code to reproduce the behavior:

                          import spatialdata as sd
                          import spatialdata_io
                          import squidpy as sq
                          import spatialdata_plot
                          
                          sdata = sd.read_zarr("/path/to/data_aligned.zarr/")
                          

                          The following subset calls DO NOT result in an error

                          subset = sdata.query.bounding_box(
                          axes=["x", "y"],
                          min_coordinate=[0,0],
                          max_coordinate=[15000,13000],
                          target_coordinate_system="global",
                          )
                          subset.write(f'../data/xenium/subset_test/subset.zarr', overwrite=True)
                          
                          subset3 = sdata.query.bounding_box(
                          axes=["x", "y"],
                          min_coordinate=[0,0],
                          max_coordinate=[20000,13000],
                          target_coordinate_system="global",
                          )
                          subset3.write(f'../data/xenium/subset_test/subset3.zarr', overwrite=True)
                          

                          The following subsetting examples DO result in an error:

                          subset2 = sdata.query.bounding_box(
                          axes=["x", "y"],
                          min_coordinate=[15000,0],
                          max_coordinate=[35000,13000],
                          target_coordinate_system="global",
                          )
                          subset2.write(f'../data/xenium/subset_test/subset2.zarr', overwrite=True)
                          
                          subset4 = sdata.query.bounding_box(
                          axes=["x", "y"],
                          min_coordinate=[10000,0],
                          max_coordinate=[30000,13000],
                          target_coordinate_system="global",
                          )
                          subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
                          

                          I initially thought maybe the subset size may have something to do with the irregular chunking. In this case the query size (20,000 x 13,000) in subset2 and subset4 resulted in an error but subset3 has the same query size and was able to be saved.

                          In my private dataset, only 1/12 of my queries is savable

                          Expected behavior
                          I would have expected the subsetted spatialdata object to be savable to a .zarr

                          Screenshots

                          Image

                          sdata
                          Image

                          subset3 (no error)
                          Image

                          subset4 (error)
                          Image

                          Desktop (optional):
                          OS: Red Hat Enterprise Linux release 8.8 (Ootpa)

                          Additional context
                          This bug was briefly discussed in a thread of this PR

                          The bug results in the following traceback:

                          ---------------------------------------------------------------------------
                          ValueError Traceback (most recent call last)
                          Cell In[48], line 1
                          ----> 1 subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
                          <conda_env_loc>
                          File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1186](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1185), in SpatialData.write(self, file_path, overwrite, consolidate_metadata, format)
                          1183 store.close()
                          1185 for element_type, element_name, element in self.gen_elements():
                          -> 1186 self._write_element(
                          1187 element=element,
                          1188 zarr_container_path=file_path,
                          1189 element_type=element_type,
                          1190 element_name=element_name,
                          1191 overwrite=False,
                          1192 format=format,
                          1193 )
                          1195 if self.path != file_path:
                          1196 old_path = self.path
                          File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1230](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1229), in SpatialData._write_element(self, element, zarr_container_path, element_type, element_name, overwrite, format)
                          1227 parsed = _parse_formats(formats=format)
                          1229 if element_type == "images":
                          -> 1230 write_image(image=element, group=element_type_group, name=element_name, format=parsed["raster"])
                          1231 elif element_type == "labels":
                          1232 write_labels(labels=element, group=root_group, name=element_name, format=parsed["raster"])
                          File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:242](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=241), in write_image(image, group, name, format, storage_options, **metadata)
                          234 def write_image(
                          235 image: DataArray | DataTree,
                          236 group: zarr.Group,
                          (...)
                          240 **metadata: str | JSONDict | list[JSONDict],
                          241 ) -> None:
                          --> 242 _write_raster(
                          243 raster_type="image",
                          244 raster_data=image,
                          245 group=group,
                          246 name=name,
                          247 format=format,
                          248 storage_options=storage_options,
                          249 **metadata,
                          250 )
                          File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:202](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=201), in _write_raster(raster_type, raster_data, group, name, format, storage_options, label_metadata, **metadata)
                          200 parsed_axes = _get_valid_axes(axes=list(input_axes), fmt=format)
                          201 storage_options = [{"chunks": chunk} for chunk in chunks]
                          --> 202 dask_delayed = write_multi_scale_ngff(
                          203 pyramid=data,
                          204 group=group_data,
                          205 fmt=format,
                          206 axes=parsed_axes,
                          207 coordinate_transformations=None,
                          208 storage_options=storage_options,
                          209 **metadata,
                          210 compute=False,
                          211 )
                          212 # Compute all pyramid levels at once to allow Dask to optimize the computational graph.
                          213 da.compute(*dask_delayed)
                          File [<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py:253](<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py#line=252), in write_multiscale(pyramid, group, chunks, fmt, axes, coordinate_transformations, storage_options, name, compute, **metadata)
                          251 data = da.array(data).rechunk(chunks=chunks_opt)
                          252 options["chunks"] = chunks_opt
                          --> 253 da_delayed = da.to_zarr(
                          254 arr=data,
                          255 url=group.store,
                          256 component=str(Path(group.path, str(path))),
                          257 storage_options=options,
                          258 compressor=options.get("compressor", zarr.storage.default_compressor),
                          259 dimension_separator=group._store._dimension_separator,
                          260 compute=compute,
                          261 )
                          263 if not compute:
                          264 dask_delayed.append(da_delayed)
                          File [<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py:3875](<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py#line=3874), in to_zarr(arr, url, component, storage_options, overwrite, region, compute, return_stored, **kwargs)
                          3872 raise ValueError("Cannot use `region` keyword when url is not a `zarr.Array`.")
                          3874 if not _check_regular_chunks(arr.chunks):
                          -> 3875 raise ValueError(
                          3876 "Attempt to save array to zarr with irregular "
                          3877 "chunking, please call `arr.rechunk(...)` first."
                          3878 )
                          3880 storage_options = storage_options or {}
                          3882 if storage_options:
                          ValueError: Attempt to save array to zarr with irregular chunking, please call `arr.rechunk(...)` first.
                          Click to add a cell.
                          

                          Metadata

                          Metadata

                          Assignees

                          No one assigned

                            Labels

                            No labels
                            No labels

                            Type

                            No type

                            Projects

                            No projects

                              Milestone

                              No milestone

                              Relationships

                              None yet

                              Development

                              No branches or pull requests

                              Issue actions

                              , 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
                              Skip to content

                              Unable to save subsetted Xenium sdata to .zarr #821

                              Description

                              @christinedien

                              The bug can be reproduced using one of the spatialdata example datasets: I had used the Xenium Aligned Breast Cancer dataset

                              Describe the bug
                              After subsetting a spatialdata object using sdata.query.bounding_box(...), attempting to save the new subset as a .zarr sometimes results in an irregular chunking error. This occurs after a sdata.write(...) command

                              To Reproduce
                              Code to reproduce the behavior:

                              import spatialdata as sd
                              import spatialdata_io
                              import squidpy as sq
                              import spatialdata_plot
                              
                              sdata = sd.read_zarr("/path/to/data_aligned.zarr/")
                              

                              The following subset calls DO NOT result in an error

                              subset = sdata.query.bounding_box(
                              axes=["x", "y"],
                              min_coordinate=[0,0],
                              max_coordinate=[15000,13000],
                              target_coordinate_system="global",
                              )
                              subset.write(f'../data/xenium/subset_test/subset.zarr', overwrite=True)
                              
                              subset3 = sdata.query.bounding_box(
                              axes=["x", "y"],
                              min_coordinate=[0,0],
                              max_coordinate=[20000,13000],
                              target_coordinate_system="global",
                              )
                              subset3.write(f'../data/xenium/subset_test/subset3.zarr', overwrite=True)
                              

                              The following subsetting examples DO result in an error:

                              subset2 = sdata.query.bounding_box(
                              axes=["x", "y"],
                              min_coordinate=[15000,0],
                              max_coordinate=[35000,13000],
                              target_coordinate_system="global",
                              )
                              subset2.write(f'../data/xenium/subset_test/subset2.zarr', overwrite=True)
                              
                              subset4 = sdata.query.bounding_box(
                              axes=["x", "y"],
                              min_coordinate=[10000,0],
                              max_coordinate=[30000,13000],
                              target_coordinate_system="global",
                              )
                              subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
                              

                              I initially thought maybe the subset size may have something to do with the irregular chunking. In this case the query size (20,000 x 13,000) in subset2 and subset4 resulted in an error but subset3 has the same query size and was able to be saved.

                              In my private dataset, only 1/12 of my queries is savable

                              Expected behavior
                              I would have expected the subsetted spatialdata object to be savable to a .zarr

                              Screenshots

                              Image

                              sdata
                              Image

                              subset3 (no error)
                              Image

                              subset4 (error)
                              Image

                              Desktop (optional):
                              OS: Red Hat Enterprise Linux release 8.8 (Ootpa)

                              Additional context
                              This bug was briefly discussed in a thread of this PR

                              The bug results in the following traceback:

                              ---------------------------------------------------------------------------
                              ValueError Traceback (most recent call last)
                              Cell In[48], line 1
                              ----> 1 subset4.write(f'../data/xenium/subset_test/subset4.zarr', overwrite=True)
                              <conda_env_loc>
                              File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1186](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1185), in SpatialData.write(self, file_path, overwrite, consolidate_metadata, format)
                              1183 store.close()
                              1185 for element_type, element_name, element in self.gen_elements():
                              -> 1186 self._write_element(
                              1187 element=element,
                              1188 zarr_container_path=file_path,
                              1189 element_type=element_type,
                              1190 element_name=element_name,
                              1191 overwrite=False,
                              1192 format=format,
                              1193 )
                              1195 if self.path != file_path:
                              1196 old_path = self.path
                              File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py:1230](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_core/spatialdata.py#line=1229), in SpatialData._write_element(self, element, zarr_container_path, element_type, element_name, overwrite, format)
                              1227 parsed = _parse_formats(formats=format)
                              1229 if element_type == "images":
                              -> 1230 write_image(image=element, group=element_type_group, name=element_name, format=parsed["raster"])
                              1231 elif element_type == "labels":
                              1232 write_labels(labels=element, group=root_group, name=element_name, format=parsed["raster"])
                              File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:242](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=241), in write_image(image, group, name, format, storage_options, **metadata)
                              234 def write_image(
                              235 image: DataArray | DataTree,
                              236 group: zarr.Group,
                              (...)
                              240 **metadata: str | JSONDict | list[JSONDict],
                              241 ) -> None:
                              --> 242 _write_raster(
                              243 raster_type="image",
                              244 raster_data=image,
                              245 group=group,
                              246 name=name,
                              247 format=format,
                              248 storage_options=storage_options,
                              249 **metadata,
                              250 )
                              File [<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py:202](<conda_env_loc>/lib/python3.12/site-packages/spatialdata/_io/io_raster.py#line=201), in _write_raster(raster_type, raster_data, group, name, format, storage_options, label_metadata, **metadata)
                              200 parsed_axes = _get_valid_axes(axes=list(input_axes), fmt=format)
                              201 storage_options = [{"chunks": chunk} for chunk in chunks]
                              --> 202 dask_delayed = write_multi_scale_ngff(
                              203 pyramid=data,
                              204 group=group_data,
                              205 fmt=format,
                              206 axes=parsed_axes,
                              207 coordinate_transformations=None,
                              208 storage_options=storage_options,
                              209 **metadata,
                              210 compute=False,
                              211 )
                              212 # Compute all pyramid levels at once to allow Dask to optimize the computational graph.
                              213 da.compute(*dask_delayed)
                              File [<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py:253](<conda_env_loc>/lib/python3.12/site-packages/ome_zarr/writer.py#line=252), in write_multiscale(pyramid, group, chunks, fmt, axes, coordinate_transformations, storage_options, name, compute, **metadata)
                              251 data = da.array(data).rechunk(chunks=chunks_opt)
                              252 options["chunks"] = chunks_opt
                              --> 253 da_delayed = da.to_zarr(
                              254 arr=data,
                              255 url=group.store,
                              256 component=str(Path(group.path, str(path))),
                              257 storage_options=options,
                              258 compressor=options.get("compressor", zarr.storage.default_compressor),
                              259 dimension_separator=group._store._dimension_separator,
                              260 compute=compute,
                              261 )
                              263 if not compute:
                              264 dask_delayed.append(da_delayed)
                              File [<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py:3875](<conda_env_loc>/lib/python3.12/site-packages/dask/array/core.py#line=3874), in to_zarr(arr, url, component, storage_options, overwrite, region, compute, return_stored, **kwargs)
                              3872 raise ValueError("Cannot use `region` keyword when url is not a `zarr.Array`.")
                              3874 if not _check_regular_chunks(arr.chunks):
                              -> 3875 raise ValueError(
                              3876 "Attempt to save array to zarr with irregular "
                              3877 "chunking, please call `arr.rechunk(...)` first."
                              3878 )
                              3880 storage_options = storage_options or {}
                              3882 if storage_options:
                              ValueError: Attempt to save array to zarr with irregular chunking, please call `arr.rechunk(...)` first.
                              Click to add a cell.
                              

                              Metadata

                              Metadata

                              Assignees

                              No one assigned

                                Labels

                                No labels
                                No labels

                                Type

                                No type

                                Projects

                                No projects

                                  Milestone

                                  No milestone

                                  Relationships

                                  None yet

                                  Development

                                  No branches or pull requests

                                  Issue actions