@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.
@@ -1,984 +1,21 @@
1
1
  "use strict";
2
2
  // SPDX-FileCopyrightText: Copyright (c) Fideus Labs LLC
3
3
  // SPDX-License-Identifier: MIT
4
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
- if (k2 === undefined) k2 = k;
6
- var desc = Object.getOwnPropertyDescriptor(m, k);
7
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
- desc = { enumerable: true, get: function() { return m[k]; } };
9
- }
10
- Object.defineProperty(o, k2, desc);
11
- }) : (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- o[k2] = m[k];
14
- }));
15
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
- Object.defineProperty(o, "default", { enumerable: true, value: v });
17
- }) : function(o, v) {
18
- o["default"] = v;
19
- });
20
- var __importStar = (this && this.__importStar) || function (mod) {
21
- if (mod && mod.__esModule) return mod;
22
- var result = {};
23
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
24
- __setModuleDefault(result, mod);
25
- return result;
26
- };
27
4
  Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.downsampleItkWasm = downsampleItkWasm;
29
- const downsample_1 = require("@itk-wasm/downsample");
30
- const zarr = __importStar(require("zarrita"));
31
- const ngff_image_js_1 = require("../types/ngff_image.js");
32
- const SPATIAL_DIMS = ["x", "y", "z"];
5
+ exports.downsampleItkWasm = void 0;
33
6
  /**
34
- * Calculate the incremental factor needed to reach the target size from the previous size.
35
- * This ensures exact target sizes when downsampling incrementally.
36
- */
37
- function calculateIncrementalFactor(previousSize, targetSize) {
38
- if (targetSize <= 0) {
39
- return 1;
40
- }
41
- // Start with the theoretical factor
42
- let factor = Math.floor(Math.ceil(previousSize / (targetSize + 0.5)));
43
- // Verify this gives us the right size
44
- let actualSize = Math.floor(previousSize / factor);
45
- if (actualSize !== targetSize) {
46
- // Adjust factor to get exact target
47
- factor = Math.max(1, Math.floor(previousSize / targetSize));
48
- actualSize = Math.floor(previousSize / factor);
49
- // If still not exact, try ceil
50
- if (actualSize !== targetSize) {
51
- factor = Math.max(1, Math.ceil(previousSize / targetSize));
52
- }
53
- }
54
- return Math.max(1, factor);
55
- }
56
- /**
57
- * Convert dimension scale factors to ITK-Wasm format
58
- * This computes the incremental scale factor relative to the previous scale,
59
- * not the absolute scale factor from the original image.
60
- *
61
- * When originalImage and previousImage are provided, calculates the exact
62
- * incremental factor needed to reach the target size from the previous size.
63
- * This ensures we get exact 1x, 2x, 3x, 4x sizes even with incremental downsampling.
64
- */
65
- function dimScaleFactors(dims, scaleFactor, previousDimFactors, originalImage, previousImage) {
66
- const dimFactors = {};
67
- if (typeof scaleFactor === "number") {
68
- if (originalImage !== undefined && previousImage !== undefined) {
69
- // Calculate target size: floor(original_size / scale_factor)
70
- // Then calculate incremental factor from previous size to target size
71
- for (const dim of dims) {
72
- if (SPATIAL_DIMS.includes(dim)) {
73
- const dimIndex = originalImage.dims.indexOf(dim);
74
- const originalSize = originalImage.data.shape[dimIndex];
75
- const targetSize = Math.floor(originalSize / scaleFactor);
76
- const prevDimIndex = previousImage.dims.indexOf(dim);
77
- const previousSize = previousImage.data.shape[prevDimIndex];
78
- dimFactors[dim] = calculateIncrementalFactor(previousSize, targetSize);
79
- }
80
- else {
81
- dimFactors[dim] = 1;
82
- }
83
- }
84
- }
85
- else {
86
- // Fallback to old behavior when images not provided
87
- for (const dim of dims) {
88
- if (SPATIAL_DIMS.includes(dim)) {
89
- // Divide by previous factor to get incremental scaling
90
- // Use Math.floor to truncate (matching Python's int() behavior)
91
- const incrementalFactor = scaleFactor /
92
- (previousDimFactors[dim] || 1);
93
- dimFactors[dim] = Math.max(1, Math.floor(incrementalFactor));
94
- }
95
- else {
96
- dimFactors[dim] = previousDimFactors[dim] || 1;
97
- }
98
- }
99
- }
100
- }
101
- else {
102
- if (originalImage !== undefined && previousImage !== undefined) {
103
- for (const dim in scaleFactor) {
104
- const dimIndex = originalImage.dims.indexOf(dim);
105
- const originalSize = originalImage.data.shape[dimIndex];
106
- const targetSize = Math.floor(originalSize / scaleFactor[dim]);
107
- const prevDimIndex = previousImage.dims.indexOf(dim);
108
- const previousSize = previousImage.data.shape[prevDimIndex];
109
- dimFactors[dim] = calculateIncrementalFactor(previousSize, targetSize);
110
- }
111
- }
112
- else {
113
- // Fallback to old behavior when images not provided
114
- for (const dim in scaleFactor) {
115
- // Divide by previous factor to get incremental scaling
116
- // Use Math.floor to truncate (matching Python's int() behavior)
117
- const incrementalFactor = scaleFactor[dim] /
118
- (previousDimFactors[dim] || 1);
119
- dimFactors[dim] = Math.max(1, Math.floor(incrementalFactor));
120
- }
121
- }
122
- // Add dims not in scale_factor with factor of 1
123
- for (const dim of dims) {
124
- if (!(dim in dimFactors)) {
125
- dimFactors[dim] = 1;
126
- }
127
- }
128
- }
129
- return dimFactors;
130
- }
131
- /**
132
- * Update previous dimension factors
133
- */
134
- function updatePreviousDimFactors(scaleFactor, spatialDims, previousDimFactors) {
135
- const updated = { ...previousDimFactors };
136
- if (typeof scaleFactor === "number") {
137
- for (const dim of spatialDims) {
138
- updated[dim] = scaleFactor;
139
- }
140
- }
141
- else {
142
- for (const dim in scaleFactor) {
143
- updated[dim] = scaleFactor[dim];
144
- }
145
- }
146
- return updated;
147
- }
148
- /**
149
- * Compute next scale metadata
150
- */
151
- function nextScaleMetadata(image, dimFactors, spatialDims) {
152
- const translation = {};
153
- const scale = {};
154
- for (const dim of image.dims) {
155
- if (spatialDims.includes(dim)) {
156
- const factor = dimFactors[dim];
157
- scale[dim] = image.scale[dim] * factor;
158
- // Add offset to account for pixel center shift when downsampling
159
- translation[dim] = image.translation[dim] +
160
- 0.5 * (factor - 1) * image.scale[dim];
161
- }
162
- else {
163
- scale[dim] = image.scale[dim];
164
- translation[dim] = image.translation[dim];
165
- }
166
- }
167
- return [translation, scale];
168
- }
169
- /**
170
- * Convert zarr array to ITK-Wasm Image format
171
- * If isVector is true, ensures "c" dimension is last by transposing if needed
172
- */
173
- async function zarrToItkImage(array, dims, isVector = false) {
174
- // Read the full array data
175
- const result = await zarr.get(array);
176
- // Ensure we have the data
177
- if (!result.data || result.data.length === 0) {
178
- throw new Error("Zarr array data is empty");
179
- }
180
- let data;
181
- let shape = result.shape;
182
- let _finalDims = dims;
183
- // If vector image, ensure "c" is last dimension
184
- if (isVector) {
185
- const cIndex = dims.indexOf("c");
186
- if (cIndex !== -1 && cIndex !== dims.length - 1) {
187
- // Need to transpose to move "c" to the end
188
- const permutation = dims.map((_, i) => i).filter((i) => i !== cIndex);
189
- permutation.push(cIndex);
190
- // Reorder dims
191
- _finalDims = permutation.map((i) => dims[i]);
192
- // Reorder shape
193
- shape = permutation.map((i) => result.shape[i]);
194
- // Transpose the data
195
- data = transposeArray(result.data, result.shape, permutation, getItkComponentType(result.data));
196
- }
197
- else {
198
- // "c" already at end or not present, just copy data
199
- data = copyTypedArray(result.data);
200
- }
201
- }
202
- else {
203
- // Not a vector image, just copy data
204
- data = copyTypedArray(result.data);
205
- }
206
- // For vector images, the last dimension is the component count, not a spatial dimension
207
- const spatialShape = isVector ? shape.slice(0, -1) : shape;
208
- const components = isVector ? shape[shape.length - 1] : 1;
209
- // ITK expects size in physical space order [x, y, z], but spatialShape is in array order [z, y, x]
210
- // So we need to reverse it
211
- const itkSize = [...spatialShape].reverse();
212
- // Create ITK-Wasm image
213
- const itkImage = {
214
- imageType: {
215
- dimension: spatialShape.length,
216
- componentType: getItkComponentType(data),
217
- pixelType: isVector ? "VariableLengthVector" : "Scalar",
218
- components,
219
- },
220
- name: "image",
221
- origin: spatialShape.map(() => 0),
222
- spacing: spatialShape.map(() => 1),
223
- direction: createIdentityMatrix(spatialShape.length),
224
- size: itkSize,
225
- data: data,
226
- metadata: new Map(),
227
- };
228
- return itkImage;
229
- }
230
- /**
231
- * Copy typed array to appropriate type
232
- */
233
- function copyTypedArray(data) {
234
- if (data instanceof Float32Array) {
235
- return new Float32Array(data);
236
- }
237
- else if (data instanceof Float64Array) {
238
- return new Float64Array(data);
239
- }
240
- else if (data instanceof Uint8Array) {
241
- return new Uint8Array(data);
242
- }
243
- else if (data instanceof Int8Array) {
244
- return new Int8Array(data);
245
- }
246
- else if (data instanceof Uint16Array) {
247
- return new Uint16Array(data);
248
- }
249
- else if (data instanceof Int16Array) {
250
- return new Int16Array(data);
251
- }
252
- else if (data instanceof Uint32Array) {
253
- return new Uint32Array(data);
254
- }
255
- else if (data instanceof Int32Array) {
256
- return new Int32Array(data);
257
- }
258
- else {
259
- // Convert to Float32Array as fallback
260
- return new Float32Array(data);
261
- }
262
- }
263
- /**
264
- * Transpose array data according to permutation
265
- */
266
- function transposeArray(data, shape, permutation, componentType) {
267
- const typedData = data;
268
- // Create output array of same type
269
- let output;
270
- const totalSize = typedData.length;
271
- switch (componentType) {
272
- case "uint8":
273
- output = new Uint8Array(totalSize);
274
- break;
275
- case "int8":
276
- output = new Int8Array(totalSize);
277
- break;
278
- case "uint16":
279
- output = new Uint16Array(totalSize);
280
- break;
281
- case "int16":
282
- output = new Int16Array(totalSize);
283
- break;
284
- case "uint32":
285
- output = new Uint32Array(totalSize);
286
- break;
287
- case "int32":
288
- output = new Int32Array(totalSize);
289
- break;
290
- case "float64":
291
- output = new Float64Array(totalSize);
292
- break;
293
- case "float32":
294
- default:
295
- output = new Float32Array(totalSize);
296
- break;
297
- }
298
- // Calculate strides for source
299
- const sourceStride = calculateStride(shape);
300
- // Calculate new shape after permutation
301
- const newShape = permutation.map((i) => shape[i]);
302
- const targetStride = calculateStride(newShape);
303
- // Perform transpose
304
- const indices = new Array(shape.length).fill(0);
305
- for (let i = 0; i < totalSize; i++) {
306
- // Calculate source index from multi-dimensional indices
307
- let sourceIdx = 0;
308
- for (let j = 0; j < shape.length; j++) {
309
- sourceIdx += indices[j] * sourceStride[j];
310
- }
311
- // Calculate target index with permuted dimensions
312
- let targetIdx = 0;
313
- for (let j = 0; j < permutation.length; j++) {
314
- targetIdx += indices[permutation[j]] * targetStride[j];
315
- }
316
- output[targetIdx] = typedData[sourceIdx];
317
- // Increment indices
318
- for (let j = shape.length - 1; j >= 0; j--) {
319
- indices[j]++;
320
- if (indices[j] < shape[j])
321
- break;
322
- indices[j] = 0;
323
- }
324
- }
325
- return output;
326
- }
327
- /**
328
- * Get ITK component type from typed array
329
- */
330
- function getItkComponentType(data) {
331
- if (data instanceof Uint8Array)
332
- return "uint8";
333
- if (data instanceof Int8Array)
334
- return "int8";
335
- if (data instanceof Uint16Array)
336
- return "uint16";
337
- if (data instanceof Int16Array)
338
- return "int16";
339
- if (data instanceof Uint32Array)
340
- return "uint32";
341
- if (data instanceof Int32Array)
342
- return "int32";
343
- if (data instanceof Float64Array)
344
- return "float64";
345
- return "float32";
346
- }
347
- /**
348
- * Create identity matrix for ITK direction
349
- */
350
- function createIdentityMatrix(dimension) {
351
- const matrix = new Float64Array(dimension * dimension);
352
- for (let i = 0; i < dimension * dimension; i++) {
353
- matrix[i] = i % (dimension + 1) === 0 ? 1 : 0;
354
- }
355
- return matrix;
356
- }
357
- /**
358
- * Convert ITK-Wasm Image back to zarr array
359
- * Uses the provided store instead of creating a new one
7
+ * ITK-Wasm downsampling support for multiscale generation
360
8
  *
361
- * Important: ITK-Wasm stores size in physical space order [x, y, z], but data in
362
- * column-major order (x contiguous). This column-major layout with size [x, y, z]
363
- * is equivalent to C-order (row-major) with shape [z, y, x]. We reverse the size
364
- * to get the zarr shape and use C-order strides for that reversed shape.
9
+ * This module provides conditional exports for browser and Node environments.
10
+ * The actual implementation is delegated to environment-specific modules:
11
+ * - itkwasm-browser.ts: Uses WebWorker-based functions for browser environments
12
+ * - itkwasm-node.ts: Uses native WASM functions for Node/Deno environments
365
13
  *
366
- * @param itkImage - The ITK-Wasm image to convert
367
- * @param store - The zarr store to write to
368
- * @param path - The path within the store
369
- * @param chunkShape - The chunk shape (in spatial dimension order, will be adjusted for components)
370
- * @param targetDims - The target dimension order (e.g., ["c", "z", "y", "x"])
371
- */
372
- async function itkImageToZarr(itkImage, store, path, chunkShape, targetDims) {
373
- const root = zarr.root(store);
374
- if (!itkImage.data) {
375
- throw new Error("ITK image data is null or undefined");
376
- }
377
- // Determine data type - support all ITK TypedArray types
378
- let dataType;
379
- if (itkImage.data instanceof Uint8Array) {
380
- dataType = "uint8";
381
- }
382
- else if (itkImage.data instanceof Int8Array) {
383
- dataType = "int8";
384
- }
385
- else if (itkImage.data instanceof Uint16Array) {
386
- dataType = "uint16";
387
- }
388
- else if (itkImage.data instanceof Int16Array) {
389
- dataType = "int16";
390
- }
391
- else if (itkImage.data instanceof Uint32Array) {
392
- dataType = "uint32";
393
- }
394
- else if (itkImage.data instanceof Int32Array) {
395
- dataType = "int32";
396
- }
397
- else if (itkImage.data instanceof Float32Array) {
398
- dataType = "float32";
399
- }
400
- else if (itkImage.data instanceof Float64Array) {
401
- dataType = "float64";
402
- }
403
- else {
404
- throw new Error(`Unsupported data type: ${itkImage.data.constructor.name}`);
405
- }
406
- // ITK stores size/spacing/origin in physical space order [x, y, z],
407
- // but the data buffer is in C-order (row-major) which means [z, y, x] indexing.
408
- // We need to reverse the size to match the data layout, just like we do for spacing/origin.
409
- const shape = [...itkImage.size].reverse();
410
- // For vector images, the components are stored in the data but not in the size
411
- // The actual data length includes components
412
- const components = itkImage.imageType.components || 1;
413
- const isVector = components > 1;
414
- // Validate data length matches expected shape (including components for vector images)
415
- const spatialElements = shape.reduce((a, b) => a * b, 1);
416
- const expectedLength = spatialElements * components;
417
- if (itkImage.data.length !== expectedLength) {
418
- console.error(`[ERROR] Data length mismatch in itkImageToZarr:`);
419
- console.error(` ITK image size (physical order):`, itkImage.size);
420
- console.error(` Shape (reversed):`, shape);
421
- console.error(` Components:`, components);
422
- console.error(` Expected data length:`, expectedLength);
423
- console.error(` Actual data length:`, itkImage.data.length);
424
- throw new Error(`Data length (${itkImage.data.length}) doesn't match expected shape ${shape} with ${components} components (${expectedLength} elements)`);
425
- }
426
- // Determine the final shape and whether we need to transpose
427
- // ITK image data has shape [...spatialDimsReversed, components] (with c at end)
428
- // If targetDims is provided, we need to match that order
429
- let zarrShape;
430
- let zarrChunkShape;
431
- let finalData = itkImage.data;
432
- if (isVector && targetDims) {
433
- // Find where "c" should be in targetDims
434
- const cIndex = targetDims.indexOf("c");
435
- if (cIndex === -1) {
436
- throw new Error("Vector image but 'c' not found in targetDims");
437
- }
438
- // Current shape is [z, y, x, c] (spatial reversed + c at end)
439
- // Target shape should match targetDims order
440
- const currentShape = [...shape, components];
441
- // Build target shape based on targetDims
442
- zarrShape = new Array(targetDims.length);
443
- const spatialDims = shape.slice(); // [z, y, x]
444
- let spatialIdx = 0;
445
- for (let i = 0; i < targetDims.length; i++) {
446
- if (targetDims[i] === "c") {
447
- zarrShape[i] = components;
448
- }
449
- else {
450
- zarrShape[i] = spatialDims[spatialIdx++];
451
- }
452
- }
453
- // If c is not at the end, we need to transpose
454
- if (cIndex !== targetDims.length - 1) {
455
- // Build permutation: where does each target dim come from in current shape?
456
- const permutation = [];
457
- spatialIdx = 0;
458
- for (let i = 0; i < targetDims.length; i++) {
459
- if (targetDims[i] === "c") {
460
- permutation.push(currentShape.length - 1); // c is at end of current
461
- }
462
- else {
463
- permutation.push(spatialIdx++);
464
- }
465
- }
466
- // Transpose the data
467
- finalData = transposeArray(itkImage.data, currentShape, permutation, getItkComponentType(itkImage.data));
468
- }
469
- // Chunk shape should match zarrShape
470
- zarrChunkShape = new Array(zarrShape.length);
471
- spatialIdx = 0;
472
- for (let i = 0; i < targetDims.length; i++) {
473
- if (targetDims[i] === "c") {
474
- zarrChunkShape[i] = components;
475
- }
476
- else {
477
- zarrChunkShape[i] = chunkShape[spatialIdx++];
478
- }
479
- }
480
- }
481
- else {
482
- // No targetDims or not a vector - use default behavior
483
- zarrShape = isVector ? [...shape, components] : shape;
484
- zarrChunkShape = isVector ? [...chunkShape, components] : chunkShape;
485
- }
486
- // Chunk shape should match the dimensionality of zarrShape
487
- if (zarrChunkShape.length !== zarrShape.length) {
488
- throw new Error(`chunkShape length (${zarrChunkShape.length}) must match shape length (${zarrShape.length})`);
489
- }
490
- const array = await zarr.create(root.resolve(path), {
491
- shape: zarrShape,
492
- chunk_shape: zarrChunkShape,
493
- data_type: dataType,
494
- fill_value: 0,
495
- });
496
- // Write data - preserve the actual data type, don't cast to Float32Array
497
- // Shape and stride should match the ITK image size order
498
- // Use null for each dimension to select the entire array
499
- const selection = zarrShape.map(() => null);
500
- await zarr.set(array, selection, {
501
- data: finalData,
502
- shape: zarrShape,
503
- stride: calculateStride(zarrShape),
504
- });
505
- return array;
506
- }
507
- /**
508
- * Calculate stride for array
509
- */
510
- function calculateStride(shape) {
511
- const stride = new Array(shape.length);
512
- stride[shape.length - 1] = 1;
513
- for (let i = shape.length - 2; i >= 0; i--) {
514
- stride[i] = stride[i + 1] * shape[i + 1];
515
- }
516
- return stride;
517
- }
518
- /**
519
- * Perform Gaussian downsampling using ITK-Wasm
520
- */
521
- async function downsampleGaussian(image, dimFactors, spatialDims) {
522
- // Handle time dimension by processing each time slice independently
523
- if (image.dims.includes("t")) {
524
- const tDimIndex = image.dims.indexOf("t");
525
- const tSize = image.data.shape[tDimIndex];
526
- const newDims = image.dims.filter((dim) => dim !== "t");
527
- // Downsample each time slice
528
- const downsampledSlices = [];
529
- for (let t = 0; t < tSize; t++) {
530
- // Extract time slice
531
- const selection = new Array(image.data.shape.length).fill(null);
532
- selection[tDimIndex] = t;
533
- const sliceData = await zarr.get(image.data, selection);
534
- // Create temporary zarr array for this slice
535
- const sliceStore = new Map();
536
- const sliceRoot = zarr.root(sliceStore);
537
- const sliceShape = image.data.shape.filter((_, i) => i !== tDimIndex);
538
- const sliceChunkShape = sliceShape.map((s) => Math.min(s, 256));
539
- const sliceArray = await zarr.create(sliceRoot.resolve("slice"), {
540
- shape: sliceShape,
541
- chunk_shape: sliceChunkShape,
542
- data_type: image.data.dtype,
543
- fill_value: 0,
544
- });
545
- const fullSelection = new Array(sliceShape.length).fill(null);
546
- await zarr.set(sliceArray, fullSelection, sliceData);
547
- // Create NgffImage for this slice (without 't' dimension)
548
- const sliceImage = new ngff_image_js_1.NgffImage({
549
- data: sliceArray,
550
- dims: newDims,
551
- scale: Object.fromEntries(Object.entries(image.scale).filter(([dim]) => dim !== "t")),
552
- translation: Object.fromEntries(Object.entries(image.translation).filter(([dim]) => dim !== "t")),
553
- name: image.name,
554
- axesUnits: image.axesUnits
555
- ? Object.fromEntries(Object.entries(image.axesUnits).filter(([dim]) => dim !== "t"))
556
- : undefined,
557
- computedCallbacks: image.computedCallbacks,
558
- });
559
- // Recursively downsample this slice (without 't', so no infinite loop)
560
- const downsampledSlice = await downsampleGaussian(sliceImage, dimFactors, spatialDims);
561
- downsampledSlices.push(downsampledSlice.data);
562
- }
563
- // Combine downsampled slices back into a single array with 't' dimension
564
- const firstSlice = downsampledSlices[0];
565
- const combinedShape = [...image.data.shape];
566
- combinedShape[tDimIndex] = tSize;
567
- // Update spatial dimensions based on downsampled size
568
- for (let i = 0; i < image.dims.length; i++) {
569
- if (i !== tDimIndex) {
570
- const sliceIndex = i < tDimIndex ? i : i - 1;
571
- combinedShape[i] = firstSlice.shape[sliceIndex];
572
- }
573
- }
574
- // Create combined array
575
- const combinedStore = new Map();
576
- const combinedRoot = zarr.root(combinedStore);
577
- const combinedArray = await zarr.create(combinedRoot.resolve("combined"), {
578
- shape: combinedShape,
579
- chunk_shape: combinedShape.map((s) => Math.min(s, 256)),
580
- data_type: image.data.dtype,
581
- fill_value: 0,
582
- });
583
- // Copy each downsampled slice into the combined array
584
- for (let t = 0; t < tSize; t++) {
585
- const sliceData = await zarr.get(downsampledSlices[t]);
586
- const targetSelection = new Array(combinedShape.length).fill(null);
587
- targetSelection[tDimIndex] = t;
588
- await zarr.set(combinedArray, targetSelection, sliceData);
589
- }
590
- // Compute new metadata (time dimension unchanged, spatial dimensions downsampled)
591
- const [translation, scale] = nextScaleMetadata(image, dimFactors, spatialDims);
592
- return new ngff_image_js_1.NgffImage({
593
- data: combinedArray,
594
- dims: image.dims,
595
- scale: { ...image.scale, ...scale },
596
- translation: { ...image.translation, ...translation },
597
- name: image.name,
598
- axesUnits: image.axesUnits,
599
- computedCallbacks: image.computedCallbacks,
600
- });
601
- }
602
- const isVector = image.dims.includes("c");
603
- // Convert to ITK-Wasm format
604
- const itkImage = await zarrToItkImage(image.data, image.dims, isVector);
605
- // Prepare shrink factors - need to be for ALL dimensions in ITK order (reversed)
606
- const shrinkFactors = [];
607
- for (let i = image.dims.length - 1; i >= 0; i--) {
608
- const dim = image.dims[i];
609
- if (SPATIAL_DIMS.includes(dim)) {
610
- shrinkFactors.push(dimFactors[dim] || 1);
611
- }
612
- }
613
- // Use all zeros for cropRadius
614
- const cropRadius = new Array(shrinkFactors.length).fill(0);
615
- // Perform downsampling
616
- const { downsampled } = await (0, downsample_1.downsampleNode)(itkImage, {
617
- shrinkFactors,
618
- cropRadius: cropRadius,
619
- });
620
- // Compute new metadata
621
- const [translation, scale] = nextScaleMetadata(image, dimFactors, spatialDims);
622
- // Convert back to zarr array in a new in-memory store
623
- // Each downsampled image gets its own store - toNgffZarr will handle copying to target
624
- const store = new Map();
625
- // Chunk shape needs to be in zarr order (reversed from ITK order)
626
- const chunkShape = downsampled.size.map((s) => Math.min(s, 256)).reverse();
627
- const array = await itkImageToZarr(downsampled, store, "image", chunkShape, image.dims);
628
- return new ngff_image_js_1.NgffImage({
629
- data: array,
630
- dims: image.dims,
631
- scale,
632
- translation,
633
- name: image.name,
634
- axesUnits: image.axesUnits,
635
- computedCallbacks: image.computedCallbacks,
636
- });
637
- }
638
- /**
639
- * Perform bin shrink downsampling using ITK-Wasm
640
- */
641
- async function downsampleBinShrinkImpl(image, dimFactors, spatialDims) {
642
- // Handle time dimension by processing each time slice independently
643
- if (image.dims.includes("t")) {
644
- const tDimIndex = image.dims.indexOf("t");
645
- const tSize = image.data.shape[tDimIndex];
646
- const newDims = image.dims.filter((dim) => dim !== "t");
647
- // Downsample each time slice
648
- const downsampledSlices = [];
649
- for (let t = 0; t < tSize; t++) {
650
- // Extract time slice
651
- const selection = new Array(image.data.shape.length).fill(null);
652
- selection[tDimIndex] = t;
653
- const sliceData = await zarr.get(image.data, selection);
654
- // Create temporary zarr array for this slice
655
- const sliceStore = new Map();
656
- const sliceRoot = zarr.root(sliceStore);
657
- const sliceShape = image.data.shape.filter((_, i) => i !== tDimIndex);
658
- const sliceChunkShape = sliceShape.map((s) => Math.min(s, 256));
659
- const sliceArray = await zarr.create(sliceRoot.resolve("slice"), {
660
- shape: sliceShape,
661
- chunk_shape: sliceChunkShape,
662
- data_type: image.data.dtype,
663
- fill_value: 0,
664
- });
665
- const fullSelection = new Array(sliceShape.length).fill(null);
666
- await zarr.set(sliceArray, fullSelection, sliceData);
667
- // Create NgffImage for this slice (without 't' dimension)
668
- const sliceImage = new ngff_image_js_1.NgffImage({
669
- data: sliceArray,
670
- dims: newDims,
671
- scale: Object.fromEntries(Object.entries(image.scale).filter(([dim]) => dim !== "t")),
672
- translation: Object.fromEntries(Object.entries(image.translation).filter(([dim]) => dim !== "t")),
673
- name: image.name,
674
- axesUnits: image.axesUnits
675
- ? Object.fromEntries(Object.entries(image.axesUnits).filter(([dim]) => dim !== "t"))
676
- : undefined,
677
- computedCallbacks: image.computedCallbacks,
678
- });
679
- // Recursively downsample this slice
680
- const downsampledSlice = await downsampleBinShrinkImpl(sliceImage, dimFactors, spatialDims);
681
- downsampledSlices.push(downsampledSlice.data);
682
- }
683
- // Combine downsampled slices back into a single array with 't' dimension
684
- const firstSlice = downsampledSlices[0];
685
- const combinedShape = [...image.data.shape];
686
- combinedShape[tDimIndex] = tSize;
687
- // Update spatial dimensions based on downsampled size
688
- for (let i = 0; i < image.dims.length; i++) {
689
- if (i !== tDimIndex) {
690
- const sliceIndex = i < tDimIndex ? i : i - 1;
691
- combinedShape[i] = firstSlice.shape[sliceIndex];
692
- }
693
- }
694
- // Create combined array
695
- const combinedStore = new Map();
696
- const combinedRoot = zarr.root(combinedStore);
697
- const combinedArray = await zarr.create(combinedRoot.resolve("combined"), {
698
- shape: combinedShape,
699
- chunk_shape: combinedShape.map((s) => Math.min(s, 256)),
700
- data_type: image.data.dtype,
701
- fill_value: 0,
702
- });
703
- // Copy each downsampled slice into the combined array
704
- for (let t = 0; t < tSize; t++) {
705
- const sliceData = await zarr.get(downsampledSlices[t]);
706
- const targetSelection = new Array(combinedShape.length).fill(null);
707
- targetSelection[tDimIndex] = t;
708
- await zarr.set(combinedArray, targetSelection, sliceData);
709
- }
710
- // Compute new metadata
711
- const [translation, scale] = nextScaleMetadata(image, dimFactors, spatialDims);
712
- return new ngff_image_js_1.NgffImage({
713
- data: combinedArray,
714
- dims: image.dims,
715
- scale: { ...image.scale, ...scale },
716
- translation: { ...image.translation, ...translation },
717
- name: image.name,
718
- axesUnits: image.axesUnits,
719
- computedCallbacks: image.computedCallbacks,
720
- });
721
- }
722
- const isVector = image.dims.includes("c");
723
- // Convert to ITK-Wasm format
724
- const itkImage = await zarrToItkImage(image.data, image.dims, isVector);
725
- // Prepare shrink factors - only for spatial dimensions in ITK order (reversed)
726
- // ITK bin shrink does not expect shrink factors for non-spatial dimensions like 'c'
727
- const shrinkFactors = [];
728
- for (let i = image.dims.length - 1; i >= 0; i--) {
729
- const dim = image.dims[i];
730
- if (SPATIAL_DIMS.includes(dim)) {
731
- shrinkFactors.push(dimFactors[dim] || 1);
732
- }
733
- }
734
- // Perform downsampling
735
- const { downsampled } = await (0, downsample_1.downsampleBinShrinkNode)(itkImage, {
736
- shrinkFactors,
737
- });
738
- // Compute new metadata
739
- const [translation, scale] = nextScaleMetadata(image, dimFactors, spatialDims);
740
- // Convert back to zarr array in a new in-memory store
741
- // Each downsampled image gets its own store - toNgffZarr will handle copying to target
742
- const store = new Map();
743
- // Chunk shape needs to be in zarr order (reversed from ITK order)
744
- const chunkShape = downsampled.size.map((s) => Math.min(s, 256)).reverse();
745
- const array = await itkImageToZarr(downsampled, store, "image", chunkShape, image.dims);
746
- return new ngff_image_js_1.NgffImage({
747
- data: array,
748
- dims: image.dims,
749
- scale,
750
- translation,
751
- name: image.name,
752
- axesUnits: image.axesUnits,
753
- computedCallbacks: image.computedCallbacks,
754
- });
755
- }
756
- /**
757
- * Perform label image downsampling using ITK-Wasm
758
- */
759
- async function downsampleLabelImageImpl(image, dimFactors, spatialDims) {
760
- // Handle time dimension by processing each time slice independently
761
- if (image.dims.includes("t")) {
762
- const tDimIndex = image.dims.indexOf("t");
763
- const tSize = image.data.shape[tDimIndex];
764
- const newDims = image.dims.filter((dim) => dim !== "t");
765
- // Downsample each time slice
766
- const downsampledSlices = [];
767
- for (let t = 0; t < tSize; t++) {
768
- // Extract time slice
769
- const selection = new Array(image.data.shape.length).fill(null);
770
- selection[tDimIndex] = t;
771
- const sliceData = await zarr.get(image.data, selection);
772
- // Create temporary zarr array for this slice
773
- const sliceStore = new Map();
774
- const sliceRoot = zarr.root(sliceStore);
775
- const sliceShape = image.data.shape.filter((_, i) => i !== tDimIndex);
776
- const sliceChunkShape = sliceShape.map((s) => Math.min(s, 256));
777
- const sliceArray = await zarr.create(sliceRoot.resolve("slice"), {
778
- shape: sliceShape,
779
- chunk_shape: sliceChunkShape,
780
- data_type: image.data.dtype,
781
- fill_value: 0,
782
- });
783
- const fullSelection = new Array(sliceShape.length).fill(null);
784
- await zarr.set(sliceArray, fullSelection, sliceData);
785
- // Create NgffImage for this slice (without 't' dimension)
786
- const sliceImage = new ngff_image_js_1.NgffImage({
787
- data: sliceArray,
788
- dims: newDims,
789
- scale: Object.fromEntries(Object.entries(image.scale).filter(([dim]) => dim !== "t")),
790
- translation: Object.fromEntries(Object.entries(image.translation).filter(([dim]) => dim !== "t")),
791
- name: image.name,
792
- axesUnits: image.axesUnits
793
- ? Object.fromEntries(Object.entries(image.axesUnits).filter(([dim]) => dim !== "t"))
794
- : undefined,
795
- computedCallbacks: image.computedCallbacks,
796
- });
797
- // Recursively downsample this slice
798
- const downsampledSlice = await downsampleLabelImageImpl(sliceImage, dimFactors, spatialDims);
799
- downsampledSlices.push(downsampledSlice.data);
800
- }
801
- // Combine downsampled slices back into a single array with 't' dimension
802
- const firstSlice = downsampledSlices[0];
803
- const combinedShape = [...image.data.shape];
804
- combinedShape[tDimIndex] = tSize;
805
- // Update spatial dimensions based on downsampled size
806
- for (let i = 0; i < image.dims.length; i++) {
807
- if (i !== tDimIndex) {
808
- const sliceIndex = i < tDimIndex ? i : i - 1;
809
- combinedShape[i] = firstSlice.shape[sliceIndex];
810
- }
811
- }
812
- // Create combined array
813
- const combinedStore = new Map();
814
- const combinedRoot = zarr.root(combinedStore);
815
- const combinedArray = await zarr.create(combinedRoot.resolve("combined"), {
816
- shape: combinedShape,
817
- chunk_shape: combinedShape.map((s) => Math.min(s, 256)),
818
- data_type: image.data.dtype,
819
- fill_value: 0,
820
- });
821
- // Copy each downsampled slice into the combined array
822
- for (let t = 0; t < tSize; t++) {
823
- const sliceData = await zarr.get(downsampledSlices[t]);
824
- const targetSelection = new Array(combinedShape.length).fill(null);
825
- targetSelection[tDimIndex] = t;
826
- await zarr.set(combinedArray, targetSelection, sliceData);
827
- }
828
- // Compute new metadata
829
- const [translation, scale] = nextScaleMetadata(image, dimFactors, spatialDims);
830
- return new ngff_image_js_1.NgffImage({
831
- data: combinedArray,
832
- dims: image.dims,
833
- scale: { ...image.scale, ...scale },
834
- translation: { ...image.translation, ...translation },
835
- name: image.name,
836
- axesUnits: image.axesUnits,
837
- computedCallbacks: image.computedCallbacks,
838
- });
839
- }
840
- const isVector = image.dims.includes("c");
841
- // Convert to ITK-Wasm format
842
- const itkImage = await zarrToItkImage(image.data, image.dims, isVector);
843
- // Prepare shrink factors - need to be for ALL dimensions in ITK order (reversed)
844
- const shrinkFactors = [];
845
- for (let i = image.dims.length - 1; i >= 0; i--) {
846
- const dim = image.dims[i];
847
- if (SPATIAL_DIMS.includes(dim)) {
848
- shrinkFactors.push(dimFactors[dim] || 1);
849
- }
850
- else {
851
- shrinkFactors.push(1); // Non-spatial dimensions don't shrink
852
- }
853
- }
854
- // Use all zeros for cropRadius
855
- const cropRadius = new Array(shrinkFactors.length).fill(0);
856
- // Perform downsampling
857
- const { downsampled } = await (0, downsample_1.downsampleLabelImageNode)(itkImage, {
858
- shrinkFactors,
859
- cropRadius: cropRadius,
860
- });
861
- // Compute new metadata
862
- const [translation, scale] = nextScaleMetadata(image, dimFactors, spatialDims);
863
- // Convert back to zarr array in a new in-memory store
864
- // Each downsampled image gets its own store - toNgffZarr will handle copying to target
865
- const store = new Map();
866
- // Chunk shape needs to be in zarr order (reversed from ITK order)
867
- const chunkShape = downsampled.size.map((s) => Math.min(s, 256)).reverse();
868
- const array = await itkImageToZarr(downsampled, store, "image", chunkShape, image.dims);
869
- return new ngff_image_js_1.NgffImage({
870
- data: array,
871
- dims: image.dims,
872
- scale,
873
- translation,
874
- name: image.name,
875
- axesUnits: image.axesUnits,
876
- computedCallbacks: image.computedCallbacks,
877
- });
878
- }
879
- /**
880
- * Main downsampling function for ITK-Wasm
881
- */
882
- async function downsampleItkWasm(ngffImage, scaleFactors, smoothing) {
883
- const multiscales = [ngffImage];
884
- const dims = ngffImage.dims;
885
- const spatialDims = dims.filter((dim) => SPATIAL_DIMS.includes(dim));
886
- // Two strategies:
887
- // 1. gaussian / label_image: hybrid absolute scale factors (each element is absolute from original)
888
- // using dimScaleFactors to choose incremental vs from-original for exact sizes.
889
- // 2. bin_shrink: treat provided scaleFactors sequence as incremental factors applied successively.
890
- let previousImage = ngffImage;
891
- let previousDimFactors = {};
892
- for (const dim of dims)
893
- previousDimFactors[dim] = 1;
894
- for (let i = 0; i < scaleFactors.length; i++) {
895
- const scaleFactor = scaleFactors[i];
896
- let sourceImage;
897
- let sourceDimFactors;
898
- if (smoothing === "bin_shrink") {
899
- // Purely incremental: scaleFactor is the shrink for this step
900
- sourceImage = previousImage; // always from previous
901
- sourceDimFactors = {};
902
- if (typeof scaleFactor === "number") {
903
- for (const dim of spatialDims)
904
- sourceDimFactors[dim] = scaleFactor;
905
- }
906
- else {
907
- for (const dim of spatialDims) {
908
- sourceDimFactors[dim] = scaleFactor[dim] || 1;
909
- }
910
- }
911
- // Non-spatial dims factor 1
912
- for (const dim of dims) {
913
- if (!(dim in sourceDimFactors))
914
- sourceDimFactors[dim] = 1;
915
- }
916
- }
917
- else {
918
- // Hybrid absolute strategy
919
- const dimFactors = dimScaleFactors(dims, scaleFactor, previousDimFactors, ngffImage, previousImage);
920
- // Decide if we can be incremental
921
- let canDownsampleIncrementally = true;
922
- for (const dim of Object.keys(dimFactors)) {
923
- const dimIndex = ngffImage.dims.indexOf(dim);
924
- if (dimIndex >= 0) {
925
- const originalSize = ngffImage.data.shape[dimIndex];
926
- const targetSize = Math.floor(originalSize /
927
- (typeof scaleFactor === "number"
928
- ? scaleFactor
929
- : scaleFactor[dim]));
930
- const prevDimIndex = previousImage.dims.indexOf(dim);
931
- const previousSize = previousImage.data.shape[prevDimIndex];
932
- if (Math.floor(previousSize / dimFactors[dim]) !== targetSize) {
933
- canDownsampleIncrementally = false;
934
- break;
935
- }
936
- }
937
- }
938
- if (canDownsampleIncrementally) {
939
- sourceImage = previousImage;
940
- sourceDimFactors = dimFactors;
941
- }
942
- else {
943
- sourceImage = ngffImage;
944
- const originalDimFactors = {};
945
- for (const dim of dims)
946
- originalDimFactors[dim] = 1;
947
- sourceDimFactors = dimScaleFactors(dims, scaleFactor, originalDimFactors);
948
- }
949
- }
950
- let downsampled;
951
- if (smoothing === "gaussian") {
952
- downsampled = await downsampleGaussian(sourceImage, sourceDimFactors, spatialDims);
953
- }
954
- else if (smoothing === "bin_shrink") {
955
- downsampled = await downsampleBinShrinkImpl(sourceImage, sourceDimFactors, spatialDims);
956
- }
957
- else if (smoothing === "label_image") {
958
- downsampled = await downsampleLabelImageImpl(sourceImage, sourceDimFactors, spatialDims);
959
- }
960
- else {
961
- throw new Error(`Unknown smoothing method: ${smoothing}`);
962
- }
963
- multiscales.push(downsampled);
964
- // Update for next iteration
965
- previousImage = downsampled;
966
- if (smoothing === "bin_shrink") {
967
- // Accumulate cumulative factors (multiply) for bin_shrink to reflect total shrink so far
968
- if (typeof scaleFactor === "number") {
969
- for (const dim of spatialDims) {
970
- previousDimFactors[dim] *= scaleFactor;
971
- }
972
- }
973
- else {
974
- for (const dim of spatialDims) {
975
- previousDimFactors[dim] *= scaleFactor[dim] || 1;
976
- }
977
- }
978
- }
979
- else {
980
- previousDimFactors = updatePreviousDimFactors(scaleFactor, spatialDims, previousDimFactors);
981
- }
982
- }
983
- return multiscales;
984
- }
14
+ * For Deno runtime, we default to the node implementation.
15
+ * For browser bundlers, they should use conditional exports in package.json
16
+ * to resolve to the browser implementation.
17
+ */
18
+ // Default to Node implementation for Deno and Node.js environments
19
+ // Browser bundlers should use conditional exports to get itkwasm-browser.ts
20
+ var itkwasm_node_js_1 = require("./itkwasm-node.js");
21
+ Object.defineProperty(exports, "downsampleItkWasm", { enumerable: true, get: function () { return itkwasm_node_js_1.downsampleItkWasm; } });