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.

Version 0.0.4 / native tile assembly and multidimensional scene canvases.

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.

recover native placementfilter scene, axes, channelbound finest levelsize each levelbuild without pixel readsrequest output chunkmap centres to samplesoverwrite in source orderOME image levels + live factorsPieces grouped by factortiles + placement metadataCommon native extentMosaic + spatial binsLazy Dask pyramidIntersecting piecesBounded Zarr readsComposed output chunkrecover native placementfilter scene, axes, channelbound finest levelsize each levelbuild without pixel readsrequest output chunkmap centres to samplesoverwrite in source orderOME image levels + live factorsPieces grouped by factortiles + placement metadataCommon native extentMosaic + spatial binsLazy Dask pyramidIntersecting piecesBounded Zarr readsComposed 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 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
  channels_last      prepared scene layout
  leading_ndim       retained T/Z axes

A piece can represent a regular image level or an irregular tile. Regular sources come first; numeric tile names follow. Prepared scene arrays reuse the same piece reader.

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.

Tile pyramids

Recover stored tile levels, not missing native data.

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.

Scene canvases

The same chunk reader also combines matching scenes.

places samples Original sceneslazy T/Z/Y/X + RGBstored pyramid arrays Spatial piecesphysical originsoutput-chunk bins One channel layerT/Z + spatial Y/Xcached overviews switch back to S: restore original scene arrays Scene composition adds display overviews, not missing source tiles or native detail.
Fig. 6Scene-canvas overviews sample existing scene sources; native S restoration uses the original arrays, not the composed pixels.

Tile assembly recovers source coverage

assemble_czi_layers uses native tile footprints and refkv's live factor summary. It groups available source resolutions without inventing missing tile factors.

Scene composition makes a display canvas

compose_scene_canvas converts scene origins into a common pixel frame. It reuses stored scene levels, then samples extra overviews when the canvas remains too large.

Overview generation halves the output shape until its longest side fits an output chunk. Each added overview keeps the common extent and reads intersecting regions from the coarsest available scene sources. No dense full-resolution canvas is needed.

Matching S/T/C/Z/Y/X scenes keep one layer per acquisition channel in both modes. The canvas composes S in Y/X and retains T/Z, with one plane per output chunk. Scenes need shared T/Z origins, matching shapes, scales, dtypes and pyramids, without rotation, shear or extra affine transforms. Unsupported scenes retain individual layers.

The canvas fills gaps with zero, gives later numeric scenes overlap priority and uses nearest-neighbour sampling for fractional placement. The dock preserves source arrays, pyramid levels and display settings for the return to native S.

looks up hit: reuses miss stores returns pixels Overview requestT / Z / level / region Shared LRU cachechannels + levels Display overviewchosen plane only Compose chunkdecode source scenes 64 MiB total cache
Fig. 7Generated overview hits skip source reads; the byte limit evicts least-recently-used chunks across channels and levels.

Only generated overview levels use this cache. Native and stored pyramid levels remain uncached; decoding errors still propagate. First visits can decode full source chunks even for small overviews. Cache keys separate T/Z positions, levels, channels and regions. Cached buffers are isolated from consumer edits.

The cache is memory-only and starts fresh when rebuilding a canvas. Nothing is prefetched or written to disk. With a canvas selected, dragging T/Z thumbs previews the index and requests pixels only on release by default; live dragging is optional in the dock. Numeric commits, keyboard steps and playback remain immediate.

Scene composition can use regular images from CZI-derived VZIP archives. It does not remove the archive's separate-tile limitation: native tile assembly still needs the live calibration summary from the original CZI.

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. 8Only 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: pieces, spatial index, tile assembly and compose_scene_canvas
_reader.py: scene compatibility, canvas eligibility and residual warnings
_widget.py: native S controls and original-scene restoration
Tile tests: native pixels, overlap, gaps, lazy reads, odd extents and errors
Scene tests: compact canvas, RGB, pyramids, sparse overviews and mode round-trips
refkv CZI profile: factors, placement and calibration
Editable Mermaid tile-path diagram

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