@fideus-labs/ngff-zarr 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,489 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) Fideus Labs LLC
2
+ // SPDX-License-Identifier: MIT
3
+ import * as zarr from "zarrita";
4
+ export const SPATIAL_DIMS = ["x", "y", "z"];
5
+ /**
6
+ * Calculate the incremental factor needed to reach the target size from the previous size.
7
+ * This ensures exact target sizes when downsampling incrementally.
8
+ */
9
+ export function calculateIncrementalFactor(previousSize, targetSize) {
10
+ if (targetSize <= 0) {
11
+ return 1;
12
+ }
13
+ // Start with the theoretical factor
14
+ let factor = Math.floor(Math.ceil(previousSize / (targetSize + 0.5)));
15
+ // Verify this gives us the right size
16
+ let actualSize = Math.floor(previousSize / factor);
17
+ if (actualSize !== targetSize) {
18
+ // Adjust factor to get exact target
19
+ factor = Math.max(1, Math.floor(previousSize / targetSize));
20
+ actualSize = Math.floor(previousSize / factor);
21
+ // If still not exact, try ceil
22
+ if (actualSize !== targetSize) {
23
+ factor = Math.max(1, Math.ceil(previousSize / targetSize));
24
+ }
25
+ }
26
+ return Math.max(1, factor);
27
+ }
28
+ /**
29
+ * Convert dimension scale factors to ITK-Wasm format
30
+ * This computes the incremental scale factor relative to the previous scale,
31
+ * not the absolute scale factor from the original image.
32
+ *
33
+ * When originalImage and previousImage are provided, calculates the exact
34
+ * incremental factor needed to reach the target size from the previous size.
35
+ * This ensures we get exact 1x, 2x, 3x, 4x sizes even with incremental downsampling.
36
+ */
37
+ export function dimScaleFactors(dims, scaleFactor, previousDimFactors, originalImage, previousImage) {
38
+ const dimFactors = {};
39
+ if (typeof scaleFactor === "number") {
40
+ if (originalImage !== undefined && previousImage !== undefined) {
41
+ // Calculate target size: floor(original_size / scale_factor)
42
+ // Then calculate incremental factor from previous size to target size
43
+ for (const dim of dims) {
44
+ if (SPATIAL_DIMS.includes(dim)) {
45
+ const dimIndex = originalImage.dims.indexOf(dim);
46
+ const originalSize = originalImage.data.shape[dimIndex];
47
+ const targetSize = Math.floor(originalSize / scaleFactor);
48
+ const prevDimIndex = previousImage.dims.indexOf(dim);
49
+ const previousSize = previousImage.data.shape[prevDimIndex];
50
+ dimFactors[dim] = calculateIncrementalFactor(previousSize, targetSize);
51
+ }
52
+ else {
53
+ dimFactors[dim] = 1;
54
+ }
55
+ }
56
+ }
57
+ else {
58
+ // Fallback to old behavior when images not provided
59
+ for (const dim of dims) {
60
+ if (SPATIAL_DIMS.includes(dim)) {
61
+ // Divide by previous factor to get incremental scaling
62
+ // Use Math.floor to truncate (matching Python's int() behavior)
63
+ const incrementalFactor = scaleFactor /
64
+ (previousDimFactors[dim] || 1);
65
+ dimFactors[dim] = Math.max(1, Math.floor(incrementalFactor));
66
+ }
67
+ else {
68
+ dimFactors[dim] = previousDimFactors[dim] || 1;
69
+ }
70
+ }
71
+ }
72
+ }
73
+ else {
74
+ if (originalImage !== undefined && previousImage !== undefined) {
75
+ for (const dim in scaleFactor) {
76
+ const dimIndex = originalImage.dims.indexOf(dim);
77
+ const originalSize = originalImage.data.shape[dimIndex];
78
+ const targetSize = Math.floor(originalSize / scaleFactor[dim]);
79
+ const prevDimIndex = previousImage.dims.indexOf(dim);
80
+ const previousSize = previousImage.data.shape[prevDimIndex];
81
+ dimFactors[dim] = calculateIncrementalFactor(previousSize, targetSize);
82
+ }
83
+ }
84
+ else {
85
+ // Fallback to old behavior when images not provided
86
+ for (const dim in scaleFactor) {
87
+ // Divide by previous factor to get incremental scaling
88
+ // Use Math.floor to truncate (matching Python's int() behavior)
89
+ const incrementalFactor = scaleFactor[dim] /
90
+ (previousDimFactors[dim] || 1);
91
+ dimFactors[dim] = Math.max(1, Math.floor(incrementalFactor));
92
+ }
93
+ }
94
+ // Add dims not in scale_factor with factor of 1
95
+ for (const dim of dims) {
96
+ if (!(dim in dimFactors)) {
97
+ dimFactors[dim] = 1;
98
+ }
99
+ }
100
+ }
101
+ return dimFactors;
102
+ }
103
+ /**
104
+ * Update previous dimension factors
105
+ */
106
+ export function updatePreviousDimFactors(scaleFactor, spatialDims, previousDimFactors) {
107
+ const updated = { ...previousDimFactors };
108
+ if (typeof scaleFactor === "number") {
109
+ for (const dim of spatialDims) {
110
+ updated[dim] = scaleFactor;
111
+ }
112
+ }
113
+ else {
114
+ for (const dim in scaleFactor) {
115
+ updated[dim] = scaleFactor[dim];
116
+ }
117
+ }
118
+ return updated;
119
+ }
120
+ /**
121
+ * Compute next scale metadata
122
+ */
123
+ export function nextScaleMetadata(image, dimFactors, spatialDims) {
124
+ const translation = {};
125
+ const scale = {};
126
+ for (const dim of image.dims) {
127
+ if (spatialDims.includes(dim)) {
128
+ const factor = dimFactors[dim];
129
+ scale[dim] = image.scale[dim] * factor;
130
+ // Add offset to account for pixel center shift when downsampling
131
+ translation[dim] = image.translation[dim] +
132
+ 0.5 * (factor - 1) * image.scale[dim];
133
+ }
134
+ else {
135
+ scale[dim] = image.scale[dim];
136
+ translation[dim] = image.translation[dim];
137
+ }
138
+ }
139
+ return [translation, scale];
140
+ }
141
+ /**
142
+ * Copy typed array to appropriate type
143
+ */
144
+ function copyTypedArray(data) {
145
+ if (data instanceof Float32Array) {
146
+ return new Float32Array(data);
147
+ }
148
+ else if (data instanceof Float64Array) {
149
+ return new Float64Array(data);
150
+ }
151
+ else if (data instanceof Uint8Array) {
152
+ return new Uint8Array(data);
153
+ }
154
+ else if (data instanceof Int8Array) {
155
+ return new Int8Array(data);
156
+ }
157
+ else if (data instanceof Uint16Array) {
158
+ return new Uint16Array(data);
159
+ }
160
+ else if (data instanceof Int16Array) {
161
+ return new Int16Array(data);
162
+ }
163
+ else if (data instanceof Uint32Array) {
164
+ return new Uint32Array(data);
165
+ }
166
+ else if (data instanceof Int32Array) {
167
+ return new Int32Array(data);
168
+ }
169
+ else {
170
+ // Convert to Float32Array as fallback
171
+ return new Float32Array(data);
172
+ }
173
+ }
174
+ /**
175
+ * Get ITK component type from typed array
176
+ */
177
+ export function getItkComponentType(data) {
178
+ if (data instanceof Uint8Array)
179
+ return "uint8";
180
+ if (data instanceof Int8Array)
181
+ return "int8";
182
+ if (data instanceof Uint16Array)
183
+ return "uint16";
184
+ if (data instanceof Int16Array)
185
+ return "int16";
186
+ if (data instanceof Uint32Array)
187
+ return "uint32";
188
+ if (data instanceof Int32Array)
189
+ return "int32";
190
+ if (data instanceof Float64Array)
191
+ return "float64";
192
+ return "float32";
193
+ }
194
+ /**
195
+ * Create identity matrix for ITK direction
196
+ */
197
+ export function createIdentityMatrix(dimension) {
198
+ const matrix = new Float64Array(dimension * dimension);
199
+ for (let i = 0; i < dimension * dimension; i++) {
200
+ matrix[i] = i % (dimension + 1) === 0 ? 1 : 0;
201
+ }
202
+ return matrix;
203
+ }
204
+ /**
205
+ * Calculate stride for array
206
+ */
207
+ function calculateStride(shape) {
208
+ const stride = new Array(shape.length);
209
+ stride[shape.length - 1] = 1;
210
+ for (let i = shape.length - 2; i >= 0; i--) {
211
+ stride[i] = stride[i + 1] * shape[i + 1];
212
+ }
213
+ return stride;
214
+ }
215
+ /**
216
+ * Transpose array data according to permutation
217
+ */
218
+ export function transposeArray(data, shape, permutation, componentType) {
219
+ const typedData = data;
220
+ // Create output array of same type
221
+ let output;
222
+ const totalSize = typedData.length;
223
+ switch (componentType) {
224
+ case "uint8":
225
+ output = new Uint8Array(totalSize);
226
+ break;
227
+ case "int8":
228
+ output = new Int8Array(totalSize);
229
+ break;
230
+ case "uint16":
231
+ output = new Uint16Array(totalSize);
232
+ break;
233
+ case "int16":
234
+ output = new Int16Array(totalSize);
235
+ break;
236
+ case "uint32":
237
+ output = new Uint32Array(totalSize);
238
+ break;
239
+ case "int32":
240
+ output = new Int32Array(totalSize);
241
+ break;
242
+ case "float64":
243
+ output = new Float64Array(totalSize);
244
+ break;
245
+ case "float32":
246
+ default:
247
+ output = new Float32Array(totalSize);
248
+ break;
249
+ }
250
+ // Calculate strides for source
251
+ const sourceStride = calculateStride(shape);
252
+ // Calculate new shape after permutation
253
+ const newShape = permutation.map((i) => shape[i]);
254
+ const targetStride = calculateStride(newShape);
255
+ // Perform transpose
256
+ const indices = new Array(shape.length).fill(0);
257
+ for (let i = 0; i < totalSize; i++) {
258
+ // Calculate source index from multi-dimensional indices
259
+ let sourceIdx = 0;
260
+ for (let j = 0; j < shape.length; j++) {
261
+ sourceIdx += indices[j] * sourceStride[j];
262
+ }
263
+ // Calculate target index with permuted dimensions
264
+ let targetIdx = 0;
265
+ for (let j = 0; j < permutation.length; j++) {
266
+ targetIdx += indices[permutation[j]] * targetStride[j];
267
+ }
268
+ output[targetIdx] = typedData[sourceIdx];
269
+ // Increment indices
270
+ for (let j = shape.length - 1; j >= 0; j--) {
271
+ indices[j]++;
272
+ if (indices[j] < shape[j])
273
+ break;
274
+ indices[j] = 0;
275
+ }
276
+ }
277
+ return output;
278
+ }
279
+ /**
280
+ * Convert zarr array to ITK-Wasm Image format
281
+ * If isVector is true, ensures "c" dimension is last by transposing if needed
282
+ */
283
+ export async function zarrToItkImage(array, dims, isVector = false) {
284
+ // Read the full array data
285
+ const result = await zarr.get(array);
286
+ // Ensure we have the data
287
+ if (!result.data || result.data.length === 0) {
288
+ throw new Error("Zarr array data is empty");
289
+ }
290
+ let data;
291
+ let shape = result.shape;
292
+ let _finalDims = dims;
293
+ // If vector image, ensure "c" is last dimension
294
+ if (isVector) {
295
+ const cIndex = dims.indexOf("c");
296
+ if (cIndex !== -1 && cIndex !== dims.length - 1) {
297
+ // Need to transpose to move "c" to the end
298
+ const permutation = dims.map((_, i) => i).filter((i) => i !== cIndex);
299
+ permutation.push(cIndex);
300
+ // Reorder dims
301
+ _finalDims = permutation.map((i) => dims[i]);
302
+ // Reorder shape
303
+ shape = permutation.map((i) => result.shape[i]);
304
+ // Transpose the data
305
+ data = transposeArray(result.data, result.shape, permutation, getItkComponentType(result.data));
306
+ }
307
+ else {
308
+ // "c" already at end or not present, just copy data
309
+ data = copyTypedArray(result.data);
310
+ }
311
+ }
312
+ else {
313
+ // Not a vector image, just copy data
314
+ data = copyTypedArray(result.data);
315
+ }
316
+ // For vector images, the last dimension is the component count, not a spatial dimension
317
+ const spatialShape = isVector ? shape.slice(0, -1) : shape;
318
+ const components = isVector ? shape[shape.length - 1] : 1;
319
+ // ITK expects size in physical space order [x, y, z], but spatialShape is in array order [z, y, x]
320
+ // So we need to reverse it
321
+ const itkSize = [...spatialShape].reverse();
322
+ // Create ITK-Wasm image
323
+ const itkImage = {
324
+ imageType: {
325
+ dimension: spatialShape.length,
326
+ componentType: getItkComponentType(data),
327
+ pixelType: isVector ? "VariableLengthVector" : "Scalar",
328
+ components,
329
+ },
330
+ name: "image",
331
+ origin: spatialShape.map(() => 0),
332
+ spacing: spatialShape.map(() => 1),
333
+ direction: createIdentityMatrix(spatialShape.length),
334
+ size: itkSize,
335
+ data: data,
336
+ metadata: new Map(),
337
+ };
338
+ return itkImage;
339
+ }
340
+ /**
341
+ * Convert ITK-Wasm Image back to zarr array
342
+ * Uses the provided store instead of creating a new one
343
+ *
344
+ * Important: ITK-Wasm stores size in physical space order [x, y, z], but data in
345
+ * column-major order (x contiguous). This column-major layout with size [x, y, z]
346
+ * is equivalent to C-order (row-major) with shape [z, y, x]. We reverse the size
347
+ * to get the zarr shape and use C-order strides for that reversed shape.
348
+ *
349
+ * @param itkImage - The ITK-Wasm image to convert
350
+ * @param store - The zarr store to write to
351
+ * @param path - The path within the store
352
+ * @param chunkShape - The chunk shape (in spatial dimension order, will be adjusted for components)
353
+ * @param targetDims - The target dimension order (e.g., ["c", "z", "y", "x"])
354
+ */
355
+ export async function itkImageToZarr(itkImage, store, path, chunkShape, targetDims) {
356
+ const root = zarr.root(store);
357
+ if (!itkImage.data) {
358
+ throw new Error("ITK image data is null or undefined");
359
+ }
360
+ // Determine data type - support all ITK TypedArray types
361
+ let dataType;
362
+ if (itkImage.data instanceof Uint8Array) {
363
+ dataType = "uint8";
364
+ }
365
+ else if (itkImage.data instanceof Int8Array) {
366
+ dataType = "int8";
367
+ }
368
+ else if (itkImage.data instanceof Uint16Array) {
369
+ dataType = "uint16";
370
+ }
371
+ else if (itkImage.data instanceof Int16Array) {
372
+ dataType = "int16";
373
+ }
374
+ else if (itkImage.data instanceof Uint32Array) {
375
+ dataType = "uint32";
376
+ }
377
+ else if (itkImage.data instanceof Int32Array) {
378
+ dataType = "int32";
379
+ }
380
+ else if (itkImage.data instanceof Float32Array) {
381
+ dataType = "float32";
382
+ }
383
+ else if (itkImage.data instanceof Float64Array) {
384
+ dataType = "float64";
385
+ }
386
+ else {
387
+ throw new Error(`Unsupported data type: ${itkImage.data.constructor.name}`);
388
+ }
389
+ // ITK stores size/spacing/origin in physical space order [x, y, z],
390
+ // but the data buffer is in C-order (row-major) which means [z, y, x] indexing.
391
+ // We need to reverse the size to match the data layout, just like we do for spacing/origin.
392
+ const shape = [...itkImage.size].reverse();
393
+ // For vector images, the components are stored in the data but not in the size
394
+ // The actual data length includes components
395
+ const components = itkImage.imageType.components || 1;
396
+ const isVector = components > 1;
397
+ // Validate data length matches expected shape (including components for vector images)
398
+ const spatialElements = shape.reduce((a, b) => a * b, 1);
399
+ const expectedLength = spatialElements * components;
400
+ if (itkImage.data.length !== expectedLength) {
401
+ console.error(`[ERROR] Data length mismatch in itkImageToZarr:`);
402
+ console.error(` ITK image size (physical order):`, itkImage.size);
403
+ console.error(` Shape (reversed):`, shape);
404
+ console.error(` Components:`, components);
405
+ console.error(` Expected data length:`, expectedLength);
406
+ console.error(` Actual data length:`, itkImage.data.length);
407
+ throw new Error(`Data length (${itkImage.data.length}) doesn't match expected shape ${shape} with ${components} components (${expectedLength} elements)`);
408
+ }
409
+ // Determine the final shape and whether we need to transpose
410
+ // ITK image data has shape [...spatialDimsReversed, components] (with c at end)
411
+ // If targetDims is provided, we need to match that order
412
+ let zarrShape;
413
+ let zarrChunkShape;
414
+ let finalData = itkImage.data;
415
+ if (isVector && targetDims) {
416
+ // Find where "c" should be in targetDims
417
+ const cIndex = targetDims.indexOf("c");
418
+ if (cIndex === -1) {
419
+ throw new Error("Vector image but 'c' not found in targetDims");
420
+ }
421
+ // Current shape is [z, y, x, c] (spatial reversed + c at end)
422
+ // Target shape should match targetDims order
423
+ const currentShape = [...shape, components];
424
+ // Build target shape based on targetDims
425
+ zarrShape = new Array(targetDims.length);
426
+ const spatialDims = shape.slice(); // [z, y, x]
427
+ let spatialIdx = 0;
428
+ for (let i = 0; i < targetDims.length; i++) {
429
+ if (targetDims[i] === "c") {
430
+ zarrShape[i] = components;
431
+ }
432
+ else {
433
+ zarrShape[i] = spatialDims[spatialIdx++];
434
+ }
435
+ }
436
+ // If c is not at the end, we need to transpose
437
+ if (cIndex !== targetDims.length - 1) {
438
+ // Build permutation: where does each target dim come from in current shape?
439
+ const permutation = [];
440
+ spatialIdx = 0;
441
+ for (let i = 0; i < targetDims.length; i++) {
442
+ if (targetDims[i] === "c") {
443
+ permutation.push(currentShape.length - 1); // c is at end of current
444
+ }
445
+ else {
446
+ permutation.push(spatialIdx++);
447
+ }
448
+ }
449
+ // Transpose the data
450
+ finalData = transposeArray(itkImage.data, currentShape, permutation, getItkComponentType(itkImage.data));
451
+ }
452
+ // Chunk shape should match zarrShape
453
+ zarrChunkShape = new Array(zarrShape.length);
454
+ spatialIdx = 0;
455
+ for (let i = 0; i < targetDims.length; i++) {
456
+ if (targetDims[i] === "c") {
457
+ zarrChunkShape[i] = components;
458
+ }
459
+ else {
460
+ zarrChunkShape[i] = chunkShape[spatialIdx++];
461
+ }
462
+ }
463
+ }
464
+ else {
465
+ // No targetDims or not a vector - use default behavior
466
+ zarrShape = isVector ? [...shape, components] : shape;
467
+ zarrChunkShape = isVector ? [...chunkShape, components] : chunkShape;
468
+ }
469
+ // Chunk shape should match the dimensionality of zarrShape
470
+ if (zarrChunkShape.length !== zarrShape.length) {
471
+ throw new Error(`chunkShape length (${zarrChunkShape.length}) must match shape length (${zarrShape.length})`);
472
+ }
473
+ const array = await zarr.create(root.resolve(path), {
474
+ shape: zarrShape,
475
+ chunk_shape: zarrChunkShape,
476
+ data_type: dataType,
477
+ fill_value: 0,
478
+ });
479
+ // Write data - preserve the actual data type, don't cast to Float32Array
480
+ // Shape and stride should match the ITK image size order
481
+ // Use null for each dimension to select the entire array
482
+ const selection = zarrShape.map(() => null);
483
+ await zarr.set(array, selection, {
484
+ data: finalData,
485
+ shape: zarrShape,
486
+ stride: calculateStride(zarrShape),
487
+ });
488
+ return array;
489
+ }
@@ -1,6 +1,14 @@
1
- import { NgffImage } from "../types/ngff_image.js";
2
1
  /**
3
- * Main downsampling function for ITK-Wasm
2
+ * ITK-Wasm downsampling support for multiscale generation
3
+ *
4
+ * This module provides conditional exports for browser and Node environments.
5
+ * The actual implementation is delegated to environment-specific modules:
6
+ * - itkwasm-browser.ts: Uses WebWorker-based functions for browser environments
7
+ * - itkwasm-node.ts: Uses native WASM functions for Node/Deno environments
8
+ *
9
+ * For Deno runtime, we default to the node implementation.
10
+ * For browser bundlers, they should use conditional exports in package.json
11
+ * to resolve to the browser implementation.
4
12
  */
5
- export declare function downsampleItkWasm(ngffImage: NgffImage, scaleFactors: (Record<string, number> | number)[], smoothing: "gaussian" | "bin_shrink" | "label_image"): Promise<NgffImage[]>;
13
+ export { downsampleItkWasm } from "./itkwasm-node.js";
6
14
  //# sourceMappingURL=itkwasm.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"itkwasm.d.ts","sourceRoot":"","sources":["../../src/methods/itkwasm.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAknCnD;;GAEG;AACH,wBAAsB,iBAAiB,CACrC,SAAS,EAAE,SAAS,EACpB,YAAY,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAAC,EAAE,EACjD,SAAS,EAAE,UAAU,GAAG,YAAY,GAAG,aAAa,GACnD,OAAO,CAAC,SAAS,EAAE,CAAC,CA8HtB"}
1
+ {"version":3,"file":"itkwasm.d.ts","sourceRoot":"","sources":["../../src/methods/itkwasm.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;GAWG;AAIH,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC"}