napari-virtual-reader / CZI implementation

Place tiles now. Read their pixels later.

A spatial index turns irregular CZI tiles into lazy, aligned pyramid arrays without writing a full mosaic.

NATIVE TILE FOOTPRINTSONE VIRTUAL CANVAS tile 2origin (-3, -2)tile 10origin (0, 0) places tile 2tile 10 winsgap = 0gap = 0 requested region 7 native pixels wide Each tile: 4 x 4 pixels. Canvas: 7 x 6 pixels. Schematic scalar example.
  1. Read tile footprints from metadata; keep each source array lazy.
  2. Use a common native frame; later numeric tile 10 overwrites tile 2 in their overlap.
  3. A later display request composes only the required output chunks.
Fig. 1Placement uses stored coordinates, not image registration; the full canvas is a lazy array, not an allocated image.

The pixels existed, but the view was missing

refkv can expose irregular or overlapping CZI tiles under tiles instead of regular image levels. The original reader skipped that group, so native resolution or additional stored levels could remain undisplayed.

Placement fixes coverage; laziness controls the work

CZI coordinates and factors let the plugin combine those pieces into aligned image levels. Dask then composes requested chunks rather than allocating the full slide. This recovers supported, existing data; it does not invent missing pixels or levels.

This solution is CZI-only. It depends on CZI placement metadata and refkv's live CZI factor summary. Other formats still use refkv's existing image arrays and pyramids; the plugin does not yet assemble their separate irregular tile arrays.

Preparation

Combine regular levels with eligible irregular tiles.

flowchart TD
    Regular["OME image levels + live factors"] -->|recover native placement| Pieces["Pieces grouped by factor"]
    Tiles["tiles + placement metadata"] -->|filter scene, axes, channel| Pieces
    Pieces -->|bound finest level| Extent["Common native extent"]
    Extent -->|size each level| Mosaic["Mosaic + spatial bins"]
    Mosaic -->|build without pixel reads| Dask["Lazy Dask pyramid"]
    Dask -->|request output chunk| Candidates["Intersecting pieces"]
    Candidates -->|map centres to samples| Read["Bounded Zarr reads"]
    Read -->|overwrite in source order| Output["Composed output chunk"]
Fig. 2The metadata path constructs arrays; only the request path invokes source pixel reads.

Eligibility

  • An existing 2D OME image and the live refkv image-factor summary are required.
  • Tiles need placement, native size, stored size and plane metadata.
  • Only (y, x) or (c, y, x) tiles qualify.
  • Scene/block dimensions must match, with one common time/Z plane origin.
  • The acquisition channel, packed component count and dtype must fit the layer.

One piece per source and channel

_Piece
  array              lazy Zarr source
  x, y               native origin
  width, height      native footprint
  factor             level classification
  channel            local acquisition index
  order              RGB(A) permutation
  has_c              source has C axis

A piece can represent a regular image level or an irregular tile. Regular sources come first; numeric tile names follow.

How the resolution factor is classified

Equal native and stored sizes mean native resolution. Otherwise the classifier uses the longer stored axis, choosing Y on ties. It checks powers of two before powers of three, with the tolerances specified by refkv's CZI profile. It does not simply round to the nearest power. Unknown factors remain unassembled.

Irregular placement, overlap and interior clipping can prevent refkv from exposing a level as one regular array. Different tile sizes alone are not proof that assembly is impossible.

The assembler does not require the tiles themselves to form a regular grid. It builds a regular output grid and maps each requested sample into the tile footprints, while retaining the reference-backed source reads.

On demand

A chunk reads nearby pieces, not the whole slide.

OUTPUT-CHUNK SPATIAL BINS nearpiece distant piece looks up Candidate source indexesdeduplicate; sort in source order checks footprint Read + sample + overwriteonly when centres lie inside up to 1024 px Same limit per output axis; edge chunks can be smaller.
  1. Dask requests an output chunk; RGB(A) components stay together.
  2. Spatial bins return candidate piece indexes; distant pieces are not read.
  3. Exact centre coverage selects samples, then sorted source order resolves overlaps.
Fig. 3The spatial index is conservative; exact coverage checks prevent extra candidates from contributing pixels.
  1. Allocate a zero-filled result for the requested region.
  2. Find candidates in all intersected output-chunk bins.
  3. Compute output pixel centres in native coordinates.
  4. Map covered centres to stored source row and column indexes.
  5. Read their bounding rectangle using basic Zarr slices.
  6. Select the Cartesian product of rows and columns in NumPy; reorder packed colour samples if needed.
  7. Write into the result in sorted source order. Uncovered pixels stay zero.

The output chunk bound is not a total-memory guarantee. A compressed source chunk may require full decoding; concurrent Dask tasks, source buffers and napari textures use additional memory. A small display slice can still cause a whole output chunk to be computed.

Coordinates

Sample pixel centres over the same native extent.

ILLUSTRATIVE X AXIS / FACTOR 2 0.8752.6254.3756.125 4 centresceil(7 / 2) 7 native pixels / common width W step = 1.75 The far edge is excluded: start <= centre < start + extent.
Fig. 4Odd extents use the actual shape-derived sampling pitch, not an assumed integer stride.

Output to native coordinates

Nx = ceil(W / F)
Ny = ceil(H / F)
step_x = W / Nx
step_y = H / Ny
world_x = x0 + (column + 0.5) * step_x
world_y = y0 + (row    + 0.5) * step_y

(x0, y0, W, H) is the common native canvas. F classifies the level; it need not equal the exact edge sampling pitch.

Native coordinates to source pixels

inside = start <= centre < start + extent
source_index = floor(
    (centre - start) * stored_count / extent
)

Apply this independently to X and Y. Clip only to guard floating-point rounding at the far edge. The native footprint and stored shape handle clipped tiles.

Physical calibration and the half-pixel correction

Regular levels carry physical translations, while tiles carry native pixel origins. The plugin recovers native pixel size from the initial layer scale and its live factor, then removes refkv's downsampled-pixel centre offset.

native_pixel_size_x = initial_scale_x / initial_factor
regular_origin_x = physical_translation_x / native_pixel_size_x
                   - (F - 1) / 2

finest_step_x = W / finest_output_width
napari_scale_x = native_pixel_size_x * finest_step_x
napari_translate_x = native_pixel_size_x * (x0 + (finest_step_x - 1) / 2)

Y uses the same calculation. Regular origins must be integral within the code's tolerance; ambiguous translations or mismatched summaries raise errors. Array order is Y, X, then optional RGB(A); placement metadata uses X, Y.

Pyramids

Reuse available levels; do not invent missing ones.

ILLUSTRATIVE AVAILABLE FACTORS F = 1 / nativeF = 2 / coarseF = 4 / coarser Common footprint; progressively fewer samples, not progressively smaller coverage.
Fig. 5All levels cover the finest level's bounds so napari's shape-derived pyramid transforms align them.

Sources are grouped by their stored factor. The union of the finest group's footprints sets the canvas. Coarser edge tiles cannot enlarge it. Each factor gets its own lazy mosaic; source pieces are not mixed across factors.

Native tiles preserve full-resolution samples. Coarse levels use nearest-neighbour sampling on the common extent. A missing factor is not synthesized; a gap at one level is not filled from another.

Why a small file once had a pyramid

refkv already exposed multiple regular overview levels. The original reader could display those without displaying the irregular native tiles.

Why a larger file could have only one level

Only one overview could be represented as a regular array. Other resolutions remained separate tile arrays until this assembly stage incorporated them.

Policies and limits

A deterministic view is not a ZEN-identical rendering.

Assembled

Compatible 2D tiles

Still warned

Some tiles or channels unused

unused
Not a fallback

Missing or unreadable data

error
Fig. 6Only fully consumed tile arrays leave the warning count; a tile with unused acquisition channels is still reported.
Use the original CZI for assembly. ZEN/libCZI may choose different overlapping tiles, and codec rounding can differ. Validate pixels independently before quantitative use.

Extending this to another format requires a supported placement and calibration mapping for that format. Ordinary lazy loading does not supply that mapping, and the CZI incomplete-tile warning does not cover other formats.

Implementation and evidence

_czi_mosaic.py: _Piece, _Mosaic, _sample_axis and assemble_czi_layers
_reader.py: RGB ordering, scene stacking and residual warnings
Tests: native pixels, overlap, gaps, lazy reads, odd extents, scenes and errors
refkv CZI profile: factors, placement and calibration
Editable Mermaid diagram

Diagrams are schematic, not tissue images or performance measurements. Return to the general plugin workflow.