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.
- Read tile footprints from metadata; keep each source array lazy.
- Use a common native frame; later numeric tile 10 overwrites tile 2 in their overlap.
- A later display request composes only the required output chunks.
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.
Preparation
Combine regular levels with eligible irregular tiles.
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.
- Dask requests an output chunk; RGB(A) components stay together.
- Spatial bins return candidate piece indexes; distant pieces are not read.
- Exact centre coverage selects samples, then sorted source order resolves overlaps.
- Allocate a zero-filled result for the requested region.
- Find candidates in all intersected output-chunk bins.
- Compute output pixel centres in native coordinates.
- Map covered centres to stored source row and column indexes.
- Read their bounding rectangle using basic Zarr slices.
- Select the Cartesian product of rows and columns in NumPy; reorder packed colour samples if needed.
- 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.
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.
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.
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.
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.
Compatible 2D tiles
Some tiles or channels unused
Missing or unreadable data
- Overlap: regular sources first, then tiles in numeric name order. Later sources overwrite earlier ones; there is no blending or registration.
- Incomplete views: time/Z stacks, unclassified tile factors and incompatible placement/channel metadata are not assembled.
- No OME image: tile-only sources do not get a guessed image; inputs without any supported OME image fail explicitly.
- VZIP: reopening lacks the live factor summary. The saved original reference layout is not this runtime composition.
- Warnings: remaining tiles produce one source-load warning and
metadata["reader_warning"]. - Provenance:
metadata["czi_assembly"]records bounds, factors, full-resolution availability, incorporated tile count, overlap and sampling policies.
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.