/* eslint-disable no-underscore-dangle */ import type { AbstractImageWrapper, VivLoaderType, VivLoaderDataType, ImageOptions, ChannelObject, ResolutionObject, BoundingCube, ResolutionLevel, ChannelWindow, } from '@vitessce/types'; import { normalizeCoordinateTransformations, coordinateTransformationsToMatrix, coordinateTransformationsToMatrixForSpatialData, getNgffAxes, getNgffAxesForTiff, physicalSizeToMatrix, hexToRgb, getSourceFromLoader, getDatasetScale, canLoadResolution, getStatsForResolution, isInterleaved as isInterleavedUtil, } from '@vitessce/spatial-utils'; import { VIEWER_PALETTE, UNIT_TO_METERS } from '@vitessce/utils'; import { log } from '@vitessce/globals'; import { readTiffTileShape, readTiffSampleRange } from './tiff-metadata.js'; import type { TiffPixelSourceLike } from './tiff-metadata.js'; type OmeroWindow = { start?: number; end?: number; min?: number; max?: number; }; /** * The OMERO display window (start/end) of a channel, or else its data range * (min/max), when it is a non-empty range. */ function getOmeroWindow(window: OmeroWindow | undefined): ChannelWindow { const start = window?.start ?? window?.min; const end = window?.end ?? window?.max; return Number.isFinite(start) && Number.isFinite(end) && (end as number) > (start as number) ? [start as number, end as number] : undefined; } /** * A wrapper around the Viv loader, to provide a common interface for * all image file types. */ export default class ImageWrapper implements AbstractImageWrapper { vivLoader: VivLoaderType; options: ImageOptions; modelMatrix: number[]|null = null; constructor(vivLoader: VivLoaderType, options: ImageOptions) { this.options = options || {}; this.vivLoader = vivLoader; } getType(): 'ome-tiff' | 'ome-zarr' { if ('Pixels' in this.vivLoader.metadata) { return 'ome-tiff'; } if ('omero' in this.vivLoader.metadata) { return 'ome-zarr'; } throw new Error('Unknown image type.'); } hasPhysicalSize(): boolean { if ('Pixels' in this.vivLoader.metadata) { // This is the OME-TIFF case. const { Pixels: { PhysicalSizeX, PhysicalSizeXUnit, PhysicalSizeY, PhysicalSizeYUnit, }, } = this.vivLoader.metadata; return Boolean( PhysicalSizeX && PhysicalSizeXUnit && PhysicalSizeY && PhysicalSizeYUnit, ); } // This is the OME-Zarr case. // OME-Zarr is required to have coordinateTransformations. return true; } // TODO: make stripPhysicalSizes the default behavior, // and remove it as a parameter, once it is no longer // used by spatial-accelerated and spatial-three. getData(stripPhysicalSizes = true): VivLoaderDataType { // Here, we strip the physical size information from the Viv loaders, // since we instead pass it via the model matrix. // If we keep it here AND the caller also uses getModelMatrix(), // then the physical size information will be applied twice. // Reference: https://github.com/hms-dbmi/viv/blob/ec590278f8f5591c64200be9ce189aa5c12215fc/packages/layers/src/utils.js#L162 if (stripPhysicalSizes) { const { data } = this.vivLoader; // Clone each pixel source rather than spreading it into a plain object, // so that its prototype methods (e.g. getRaster, getTile) are preserved. const newData = data.map((d) => { if ('meta' in d) { const { meta } = d; if (meta && 'physicalSizes' in meta) { // Undefined results in using the identity matrix. const newMeta = { ...meta, physicalSizes: undefined }; const clone = Object.create(Object.getPrototypeOf(d)); Object.assign(clone, d, { meta: newMeta }); return clone; } } return d; }); return newData as VivLoaderDataType; } return this.vivLoader.data; } getModelMatrix(): number[] { if (!this.modelMatrix) { // Cache the model matrix this.modelMatrix = this._getModelMatrix(); } return this.modelMatrix; } _getModelMatrix(): number[] { // The user can always provide an additional transform matrix // via the file definition options property. const { coordinateSystem = 'global', coordinateTransformations: coordinateTransformationsFromOptions, } = this.options; // We combine any user-provided transform matrix with the one // from the image file. if ('multiscales' in this.vivLoader.metadata) { // OME-Zarr case. const { multiscales: [ { datasets, coordinateTransformations: coordinateTransformationsFromFile, axes, }, ], } = this.vivLoader.metadata; // Axes in v0.4 format. const ngffAxes = getNgffAxes(axes); const transformMatrixFromOptions = coordinateTransformationsToMatrix( coordinateTransformationsFromOptions, ngffAxes, ); let transformMatrixFromFile; // Note: Older SpatialData objects did not include 'spatialdata_attrs' // in the image Element metadata. if ('spatialdata_attrs' in this.vivLoader.metadata) { // This is a SpatialData images or labels element. transformMatrixFromFile = coordinateTransformationsToMatrixForSpatialData( // Pass the first multiscales element. this.vivLoader.metadata.multiscales[0], coordinateSystem, ); } else { // TODO: update this if NGFF eventually supports named coordinate systems. // Normalize the coordinate transformations from the file. const normCoordinateTransformationsFromFile = normalizeCoordinateTransformations( coordinateTransformationsFromFile, datasets, ); transformMatrixFromFile = coordinateTransformationsToMatrix( normCoordinateTransformationsFromFile, ngffAxes, ); } const transformMatrix = transformMatrixFromFile.multiplyLeft(transformMatrixFromOptions); return transformMatrix; } if ('Pixels' in this.vivLoader.metadata) { // OME-TIFF case. const { Pixels: { PhysicalSizeX, PhysicalSizeXUnit, PhysicalSizeY, PhysicalSizeYUnit, PhysicalSizeZ, PhysicalSizeZUnit, DimensionOrder, }, } = this.vivLoader.metadata; const ngffAxes = getNgffAxesForTiff(DimensionOrder); const transformMatrixFromOptions = coordinateTransformationsToMatrix( coordinateTransformationsFromOptions, ngffAxes, ); // For the OME-TIFF case, we convert the size and unit information // to a transformation matrix. const transformMatrixFromFile = physicalSizeToMatrix( PhysicalSizeX, PhysicalSizeY, PhysicalSizeZ, PhysicalSizeXUnit, PhysicalSizeYUnit, PhysicalSizeZUnit, ); const transformMatrix = transformMatrixFromFile.multiplyLeft(transformMatrixFromOptions); return transformMatrix; } throw new Error('Unknown image type.'); } getDefaultTargetT(): number { if ('omero' in this.vivLoader.metadata) { // OME-Zarr case. const { omero: { rdefs: { defaultT, } = {}, }, } = this.vivLoader.metadata; return defaultT || 0; } return 0; } getDefaultTargetZ(): number { if ('omero' in this.vivLoader.metadata) { // OME-Zarr case. const { omero: { rdefs: { defaultZ, } = {}, }, } = this.vivLoader.metadata; return defaultZ || 0; } return 0; } getName(): string { let result; if ('Pixels' in this.vivLoader.metadata) { // This is the OME-TIFF case. const { Name, } = this.vivLoader.metadata; result = Name; } if ('omero' in this.vivLoader.metadata) { // This is the OME-Zarr case. const { omero: { name, }, } = this.vivLoader.metadata; result = name; } if (!result) { // Fallback to a default name. result = 'Image'; } return result; } getNumChannels(): number { // SpatialData case: should be temporary code path, // References: // - https://github.com/ome/ngff/issues/192 // - https://github.com/ome/ome-zarr-py/pull/261 if ('image-label' in this.vivLoader.metadata) { // As far as I can tell, SpatialData labels // are always single-channel bitmasks (as of 2023-09-20). return 1; } if ('channels_metadata' in this.vivLoader.metadata) { const { channels_metadata: channelsMetadata, } = this.vivLoader.metadata; return channelsMetadata?.channels.length || 0; } if ('omero' in this.vivLoader.metadata) { const { omero: { channels, }, } = this.vivLoader.metadata; return channels.length; } if ('Pixels' in this.vivLoader.metadata) { const { Pixels: { Channels, }, } = this.vivLoader.metadata; return Channels.length; } return 0; } getChannelNames(): string[] { if ('Pixels' in this.vivLoader.metadata) { const { Pixels: { Channels, }, } = this.vivLoader.metadata; return Channels.map((channel, i) => channel.Name || `Channel ${i}`); } // SpatialData cases (image-label and channels_metadata) // need to take precedence over general OME-NGFF omero metadata. if ('image-label' in this.vivLoader.metadata) { return ['labels']; } if ('channels_metadata' in this.vivLoader.metadata) { const { channels_metadata: channelsMetadata, } = this.vivLoader.metadata; if (channelsMetadata && Array.isArray(channelsMetadata?.channels)) { return channelsMetadata.channels.map(channel => `Channel ${channel.label}`); } } if ('omero' in this.vivLoader.metadata) { const { omero: { channels, }, } = this.vivLoader.metadata; return channels.map((channel, i) => channel.label || `Channel ${i}`); } return []; } getChannelIndex(channelSpecifier: string|number): number { if (typeof channelSpecifier === 'number') { return channelSpecifier; } // If not a number, // then assume the user passed a string corresponding to a channel name. const channelNames = this.getChannelNames(); const channelIndex = channelNames.indexOf(channelSpecifier); if (channelIndex === -1) { log.error(`Channel ${channelSpecifier} not found in image.`); } return channelIndex; } // TODO: support passing a custom color palette array. getChannelObjects(): ChannelObject[] { // SpatialData cases (image-label and channels_metadata) // need to take precedence over general OME-NGFF omero metadata. if ('image-label' in this.vivLoader.metadata) { return [{ name: 'labels', defaultColor: [255, 255, 255], defaultWindow: [0, 255], autoDefaultColor: [0, 0, 0], }]; } if ('channels_metadata' in this.vivLoader.metadata) { // Temporary code path for SpatialData. const { channels_metadata: channelsMetadata, } = this.vivLoader.metadata; if (channelsMetadata && Array.isArray(channelsMetadata?.channels)) { return channelsMetadata.channels.map((channel, i) => ({ name: `Channel ${channel.label}`, defaultColor: undefined, defaultWindow: undefined, autoDefaultColor: VIEWER_PALETTE[i % VIEWER_PALETTE.length], })); } } if ('omero' in this.vivLoader.metadata) { // This is the OME-Zarr case. const { omero: { channels, }, } = this.vivLoader.metadata; return channels.map((channel, i) => ({ name: channel.label || `Channel ${i}`, defaultColor: channel.color ? hexToRgb(channel.color) : undefined, defaultWindow: getOmeroWindow(channel.window), autoDefaultColor: VIEWER_PALETTE[i % VIEWER_PALETTE.length], })); } if ('Pixels' in this.vivLoader.metadata) { const { Pixels: { Channels, }, } = this.vivLoader.metadata; return Channels.map((channel, i) => ({ name: channel.Name || `Channel ${i}`, defaultColor: channel.Color ? channel.Color : undefined, defaultWindow: undefined, // TODO: does OME-TIFF support this? autoDefaultColor: VIEWER_PALETTE[i % VIEWER_PALETTE.length], })); } return []; } getDtype(): string | undefined { const loader = this.vivLoader; const source = getSourceFromLoader(loader, undefined) as any; if ('dtype' in source) { return source.dtype as string; } return undefined; } hasZStack(): boolean { const loader = this.vivLoader; const { labels, shape } = Array.isArray(loader.data) ? loader.data[0] : loader.data; if (!labels.includes('z')) { // If there is no 'z' dimension, then there is no z stack. return false; } const hasZStack = shape[labels.indexOf('z')] > 1; return hasZStack; } hasTStack(): boolean { const loader = this.vivLoader; const { labels, shape } = Array.isArray(loader.data) ? loader.data[0] : loader.data; if (!labels.includes('t')) { // If there is no 't' dimension, then there is no time stack. return false; } const hasTStack = shape[labels.indexOf('t')] > 1; return hasTStack; } hasCStack(): boolean { const loader = this.vivLoader; const { labels, shape } = Array.isArray(loader.data) ? loader.data[0] : loader.data; if (!labels.includes('c')) { // If there is no 'c' dimension, then there is no channel stack. return false; } const hasCStack = shape[labels.indexOf('c')] > 1; return hasCStack; } hasDimZ(): boolean { const loader = this.vivLoader; const { labels } = Array.isArray(loader.data) ? loader.data[0] : loader.data; return labels.includes('z'); } hasDimT(): boolean { const loader = this.vivLoader; const { labels } = Array.isArray(loader.data) ? loader.data[0] : loader.data; return labels.includes('t'); } hasDimC(): boolean { const loader = this.vivLoader; const { labels } = Array.isArray(loader.data) ? loader.data[0] : loader.data; return labels.includes('c'); } getNumZ(): number { const loader = this.vivLoader; const { labels, shape } = Array.isArray(loader.data) ? loader.data[0] : loader.data; return shape[labels.indexOf('z')]; } /** * Clamp a z target to a valid plane index. * spatialTargetZ can hold a 3D camera target in scene units, which may * exceed the number of planes; geotiff throws on out-of-range indices. */ getClampedZIndex(targetZ: number | null | undefined): number { const numZ = this.getNumZ(); if (!Number.isFinite(numZ) || !Number.isFinite(targetZ)) return 0; return Math.min(Math.max(Math.floor(targetZ as number), 0), numZ - 1); } getNumT(): number { const loader = this.vivLoader; const { labels, shape } = Array.isArray(loader.data) ? loader.data[0] : loader.data; return shape[labels.indexOf('t')]; } getNumC(): number { const loader = this.vivLoader; const { labels, shape } = Array.isArray(loader.data) ? loader.data[0] : loader.data; return shape[labels.indexOf('c')]; } getNumResolutions(): number { const loader = this.vivLoader; return Array.isArray(loader.data) ? loader.data.length : 1; } isMultiResolution(): boolean { const loader = this.vivLoader; const hasViewableResolutions = Boolean( Array.from({ length: loader.data.length, }).filter((_, resolution) => canLoadResolution(loader.data, resolution)).length, ); return hasViewableResolutions; } getMultiResolutionStats(): ResolutionObject[] { const loader = this.vivLoader; return Array.from({ length: loader.data.length }) .fill(0) // eslint-disable-next-line no-unused-vars .map((_, resolution) => { const { height, width, depth, depthDownsampled, totalBytes, dims, } = getStatsForResolution(loader.data, resolution); return { canLoad: canLoadResolution(loader.data, resolution), height, width, depth, depthDownsampled, totalBytes, dims, // chunkHeight // chunkWidth // chunkDepth // physicalSizeVoxel // eslint-disable-next-line max-len // physicalSizeTotal (physicalSizeVoxel * highest-resolution numPixels, for each dimension) }; }); } /** * Compute an index of an array element returned by getMultiResolutionStats() * which corresponds to a "good" automatic target resolution to select. * In the future, we could make this more sophisticated, for example * to take into account the network speed. */ getAutoTargetResolution(): number|null { const multiResStats = this.getMultiResolutionStats(); if (multiResStats.length === 0) { return null; } let nextTargetResolution = -1; let totalBytes = Infinity; do { nextTargetResolution += 1; // eslint-disable-next-line prefer-destructuring totalBytes = multiResStats[nextTargetResolution].totalBytes; } while (totalBytes > 5e7 && nextTargetResolution < multiResStats.length - 1); return nextTargetResolution; } getBoundingCube(): BoundingCube { const loader = this.vivLoader; const { labels, shape } = Array.isArray(loader.data) ? loader.data[0] : loader.data; const physicalSizeScalingMatrix = this.getModelMatrix(); const xSlice: [number, number] = [0, physicalSizeScalingMatrix[0] * shape[labels.indexOf('x')]]; const ySlice: [number, number] = [0, physicalSizeScalingMatrix[5] * shape[labels.indexOf('y')]]; const zSlice: [number, number] = [ 0, physicalSizeScalingMatrix[10] * shape[labels.indexOf('z')], ]; return [xSlice, ySlice, zSlice]; } /** * Whether the last dimension holds interleaved RGB(A) samples. * viv labels it '_c' (OME-TIFF). When the last label is 'x', * the image is not interleaved, even if it is 3 or 4 pixels wide. */ isInterleaved(): boolean { const loader = this.vivLoader; const { shape, labels } = Array.isArray(loader.data) ? loader.data[0] : loader.data; if (labels?.length === shape.length && labels.at(-1) === 'x') { return false; } return isInterleavedUtil(shape); } getPhotometricInterpretation() : 'RGB' | 'BlackIsZero' { const loader = this.vivLoader; if ('Pixels' in loader.metadata) { // OME-TIFF case const source = Array.isArray(loader.data) ? loader.data[0] : loader.data; if ('meta' in source) { const { meta } = source; if (meta && 'photometricInterpretation' in meta) { const numericValue = meta.photometricInterpretation; if (numericValue === 2) { return 'RGB'; } // We use BlackIsZero as default but should ideally be specified by a value of 1. } } } if ('omero' in loader.metadata) { // This is the OME-Zarr case. const { omero: { rdefs: { model, } = {}, }, } = loader.metadata; if (model === 'color') { return 'RGB'; } } return 'BlackIsZero'; } /** * The unit of the 3D scene, i.e. of getModelMatrix() and getVoxelSpacing(). * OME-TIFF: physicalSizeToMatrix divides by 1 µm, so the scene is in µm, * whatever PhysicalSizeXUnit is (only when physical sizes exist; * otherwise pixels, unit unknown → null). * OME-Zarr: the model matrix is in the units of the NGFF axes, as spelled * there (e.g. 'micrometer'). */ getSpatialUnit(): string | null { const { metadata } = this.vivLoader as any; if (!metadata) return null; if ('Pixels' in metadata) { return this.hasPhysicalSize() ? 'µm' : null; } if ('multiscales' in metadata) { const axes = metadata.multiscales?.[0]?.axes ?? []; const xAxis = axes.find((a: any) => (typeof a === 'string' ? a : a?.name) === 'x'); return (typeof xAxis === 'object' ? xAxis?.unit : null) || null; } return null; } /** * Meters per 3D scene unit, i.e. the unit of getModelMatrix(). * Null when the unit is unknown. */ getSceneMetersPerUnit(): number | null { const unit = this.getSpatialUnit(); return unit ? UNIT_TO_METERS[unit.normalize('NFKC')] ?? null : null; } /** * Level-0 voxel size, ZYX, in units of getSpatialUnit(): the scale of each * axis of getModelMatrix() (including transforms from the file options), * times the scale of the non-standard root-level coordinateTransformations * that some converted OME-Zarr datasets (e.g. kingsnake, f8ii, melanoma) use * for their physical spacing. getModelMatrix() itself ignores the latter. */ getVoxelSpacing(): [number, number, number] { const modelMatrix = this.getModelMatrix(); // Column-major: the norms of the X, Y, and Z columns, in ZYX order. const spacing = [8, 4, 0].map(i => Math.hypot( modelMatrix[i], modelMatrix[i + 1], modelMatrix[i + 2], ) || 1) as [number, number, number]; const { metadata } = this.vivLoader as any; const rootScale = metadata?.coordinateTransformations ?.find((t: any) => t?.type === 'scale')?.scale; if (Array.isArray(rootScale) && rootScale.length >= 3) { rootScale.slice(-3).forEach((value: number, axis: number) => { if (Number.isFinite(value) && value > 0) spacing[axis] *= value; }); } return spacing; } /** * Every resolution level as stored, finest first, with its chunk shape * and, for OME-Zarr, the scale of its multiscales dataset. * For OME-TIFF, the chunk is each level's own TIFF tile, read from its TIFF * directory (viv's tileSize is level 0's for every level). */ async getResolutionLevels(): Promise { const { data, metadata } = this.vivLoader; const pixelSources: any[] = Array.isArray(data) ? data : [data]; if ('Pixels' in metadata) { return Promise.all(pixelSources.map(async (pixelSource) => { const { shape, labels, dtype } = pixelSource; const [tileHeight, tileWidth] = await readTiffTileShape(pixelSource); const tileShape: Record = { y: tileHeight, x: tileWidth }; return { shape, labels, dtype, chunks: labels.map((axis: string) => tileShape[axis] ?? 1), data: pixelSource, }; })); } // OME-Zarr: viv's ZarrPixelSource wraps the zarrita array. The pixel // sources follow the order of the multiscales datasets. const datasets = (metadata as any).multiscales?.[0]?.datasets ?? []; return pixelSources.map((pixelSource, i) => ({ shape: pixelSource.shape, labels: pixelSource.labels, dtype: pixelSource.dtype, chunks: pixelSource._data.chunks, scale: getDatasetScale(datasets[i]), data: pixelSource._data, })); } /** * Value range of each channel from the image metadata, in the order of * getChannelObjects(): its defaultWindow, or for OME-TIFF the sample range * the writer recorded in the TIFF (see readTiffSampleRange), which needs a * read of the first TIFF directory. Undefined for channels without either. */ async getChannelWindows(): Promise { const windows = this.getChannelObjects().map(channel => channel.defaultWindow); const { data, metadata } = this.vivLoader; if (!('Pixels' in metadata)) { return windows; } const pixelSource = (Array.isArray(data) ? data[0] : data) as unknown; const sampleRange = await readTiffSampleRange(pixelSource as TiffPixelSourceLike); return sampleRange ? windows.map(window => window ?? sampleRange) : windows; } }