@loaders.gl/scientific 5.0.0-alpha.14 → 5.0.0-beta.2

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.
Files changed (87) hide show
  1. package/LICENSE +2 -30
  2. package/README.md +10 -2
  3. package/THIRD-PARTY-NOTICES.md +21 -0
  4. package/dist/index.cjs +78 -4106
  5. package/dist/index.cjs.map +4 -3
  6. package/dist/index.d.ts +4 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +2 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/lib/parsers/parse-npy.d.ts +15 -0
  11. package/dist/lib/parsers/parse-npy.d.ts.map +1 -0
  12. package/dist/lib/parsers/parse-npy.js +81 -0
  13. package/dist/lib/parsers/parse-npy.js.map +1 -0
  14. package/dist/netcdf/bundled.cjs +1 -2
  15. package/dist/netcdf/index.cjs +1 -2
  16. package/dist/netcdf/index.cjs.map +2 -2
  17. package/dist/netcdf/netcdf-loader-with-parser.cjs +1 -2
  18. package/dist/netcdf/netcdf-loader-with-parser.js +1 -1
  19. package/dist/netcdf/netcdf-loader-with-parser.js.map +1 -1
  20. package/dist/netcdf/netcdf-loader.cjs +5 -4
  21. package/dist/netcdf/netcdf-loader.cjs.map +7 -0
  22. package/dist/netcdf/netcdf-loader.js +1 -1
  23. package/dist/netcdf/netcdf-loader.js.map +1 -1
  24. package/dist/netcdf/netcdf-source-loader-types.js +1 -1
  25. package/dist/netcdf/netcdf-source-loader-types.js.map +1 -1
  26. package/dist/netcdf/netcdf-source-loader.js +1 -1
  27. package/dist/netcdf/netcdf-source-loader.js.map +1 -1
  28. package/dist/netcdf/unbundled.cjs +1 -2
  29. package/dist/netcdf.min.js +3 -3
  30. package/dist/npy-format.d.ts +12 -0
  31. package/dist/npy-format.d.ts.map +1 -0
  32. package/dist/npy-format.js +15 -0
  33. package/dist/npy-format.js.map +1 -0
  34. package/dist/npy-loader-types.cjs +80 -0
  35. package/dist/npy-loader-types.cjs.map +7 -0
  36. package/dist/npy-loader-types.d.ts +73 -0
  37. package/dist/npy-loader-types.d.ts.map +1 -0
  38. package/dist/npy-loader-types.js +34 -0
  39. package/dist/npy-loader-types.js.map +1 -0
  40. package/dist/npy-loader.cjs +273 -0
  41. package/dist/npy-loader.cjs.map +6 -0
  42. package/dist/npy-loader.d.ts +27 -0
  43. package/dist/npy-loader.d.ts.map +1 -0
  44. package/dist/npy-loader.js +15 -0
  45. package/dist/npy-loader.js.map +1 -0
  46. package/dist/npy-worker.d.ts +2 -0
  47. package/dist/npy-worker.d.ts.map +1 -0
  48. package/dist/npy-worker.js +750 -0
  49. package/dist/npy-worker.js.map +1 -0
  50. package/dist/vtk/index.cjs +4 -4118
  51. package/dist/vtk/index.cjs.map +2 -2
  52. package/dist/vtk/vtk-xml.js +4 -4
  53. package/dist/vtk/vtk-xml.js.map +1 -1
  54. package/dist/workers/npy-worker.d.ts +2 -0
  55. package/dist/workers/npy-worker.d.ts.map +1 -0
  56. package/dist/workers/npy-worker.js +7 -0
  57. package/dist/workers/npy-worker.js.map +1 -0
  58. package/dist/zarr/geo-zarr-source-loader.d.ts.map +1 -1
  59. package/dist/zarr/geo-zarr-source-loader.js +162 -43
  60. package/dist/zarr/geo-zarr-source-loader.js.map +1 -1
  61. package/dist/zarr/index.cjs +194 -43
  62. package/dist/zarr/index.cjs.map +2 -2
  63. package/dist/zarr/lib/spatial-multiscales.d.ts +13 -2
  64. package/dist/zarr/lib/spatial-multiscales.d.ts.map +1 -1
  65. package/dist/zarr/lib/spatial-multiscales.js +94 -8
  66. package/dist/zarr/lib/spatial-multiscales.js.map +1 -1
  67. package/dist/zarr/ome-zarr-source-loader.js +1 -1
  68. package/dist/zarr/ome-zarr-source-loader.js.map +1 -1
  69. package/dist/zarr/zarr-loader-types.cjs +161 -0
  70. package/dist/zarr/zarr-loader-types.cjs.map +7 -0
  71. package/dist/zarr/zarr-loader-types.js +1 -1
  72. package/dist/zarr/zarr-loader-types.js.map +1 -1
  73. package/dist/zarr.dev.js +205 -47
  74. package/dist/zarr.min.js +50 -50
  75. package/package.json +46 -8
  76. package/src/index.ts +5 -0
  77. package/src/lib/parsers/parse-npy.ts +123 -0
  78. package/src/netcdf/netcdf-loader-with-parser.ts +1 -1
  79. package/src/npy-format.ts +17 -0
  80. package/src/npy-loader-types.ts +50 -0
  81. package/src/npy-loader.ts +21 -0
  82. package/src/npy-worker.ts +6 -0
  83. package/src/vtk/vtk-xml.ts +4 -4
  84. package/src/workers/npy-worker.ts +8 -0
  85. package/src/zarr/geo-zarr-source-loader.ts +195 -44
  86. package/src/zarr/lib/spatial-multiscales.ts +104 -8
  87. package/third-party-licenses/iobuffer-LICENSE +21 -0
@@ -26,6 +26,7 @@ import {
26
26
  } from '@loaders.gl/core/loader-utils';
27
27
 
28
28
  import {getSpatialMultiscaleLevels} from './lib/spatial-multiscales';
29
+ import type {SpatialMultiscaleLevel} from './lib/spatial-multiscales';
29
30
  import type {SupportedTypedArray} from './types';
30
31
  import {ZarrSource, type ZarrSourceLoaderOptions} from './ome-zarr-source-loader';
31
32
  import {
@@ -119,6 +120,8 @@ type GeoZarrInit = {
119
120
  xDimensionIndex: number;
120
121
  /** Physical position of the logical y dimension. */
121
122
  yDimensionIndex: number;
123
+ /** Multiscale levels of the selected array, resolved once by `initialize`. */
124
+ layout: SpatialMultiscaleLevel[];
122
125
  };
123
126
 
124
127
  type PixelWindow = {
@@ -219,9 +222,7 @@ export class GeoZarrRasterSource
219
222
 
220
223
  /** Opens sibling array metadata without selecting or decoding their samples. */
221
224
  private async loadGridMetadata(): Promise<GeoZarrSourceMetadata> {
222
- const {metadata, group} = await this.getInitializationPromise();
223
- const groupAttributes = metadata.metadata?.groupAttributes as GeoZarrAttributes;
224
- const layout = getSpatialMultiscaleLevels(groupAttributes, metadata.array);
225
+ const {metadata, group, layout} = await this.getInitializationPromise();
225
226
  const levels: GeoZarrLevelMetadata[] = [];
226
227
  for (const level of layout) {
227
228
  if (level.array === metadata.array) {
@@ -245,6 +246,17 @@ export class GeoZarrRasterSource
245
246
  levels.push({id: level.id, array: level.array});
246
247
  }
247
248
  }
249
+ const selectedScale = layout.find(level => level.array === metadata.array)?.scale;
250
+ if (selectedScale) {
251
+ for (const [index, level] of levels.entries()) {
252
+ const scale = layout[index].scale!;
253
+ if (level.metadata && !isConsistentOMELevel(scale, selectedScale, level.metadata, metadata)) {
254
+ // A level without metadata has no grid geometry, so the source does not publish a
255
+ // complete tile matrix set: one inconsistent level must not mislabel the others.
256
+ delete level.metadata;
257
+ }
258
+ }
259
+ }
248
260
  const normalizedLevels = levels.length
249
261
  ? levels
250
262
  : [{id: metadata.array, array: metadata.array, metadata}];
@@ -406,13 +418,31 @@ export class GeoZarrRasterSource
406
418
  const array = await zarrita.open(group.resolve(arrayPath), {kind: 'array', signal});
407
419
  const groupAttributes = normalizeAttributes(group.attrs);
408
420
  const arrayAttributes = normalizeAttributes(array.attrs);
409
- const layout = getSpatialMultiscaleLevels(groupAttributes, arrayPath);
410
- const level = layout.find(candidate => candidate.array === arrayPath);
411
- const levelGroupAttributes = level?.group
412
- ? normalizeAttributes(
413
- (await zarrita.open(group.resolve(level.group), {kind: 'group', signal})).attrs
414
- )
415
- : {};
421
+ const openGroupAttributes = async (path: string) =>
422
+ normalizeAttributes((await zarrita.open(group.resolve(path), {kind: 'group', signal})).attrs);
423
+ let layout = getSpatialMultiscaleLevels(groupAttributes, arrayPath, {
424
+ spatialOME: declaresCoordinateReferenceSystem({...groupAttributes, ...arrayAttributes})
425
+ });
426
+ let level = layout.find(candidate => candidate.array === arrayPath);
427
+ let levelGroupAttributes = level?.group ? await openGroupAttributes(level.group) : {};
428
+ if (!layout.length) {
429
+ // A CRS can be declared only on each OME-NGFF level group. That group is known only from the
430
+ // OME levels, so read the selected level group and accept the levels if it declares a CRS.
431
+ const omeLayout = getOMELevelsOrEmpty(groupAttributes, arrayPath);
432
+ const omeLevel = omeLayout.find(candidate => candidate.array === arrayPath);
433
+ const omeLevelGroupAttributes = omeLevel?.group
434
+ ? await openGroupAttributes(omeLevel.group).catch(error => {
435
+ // An implicit v2 group has no metadata, so it declares no CRS.
436
+ rethrowUnlessAbsent(error);
437
+ return {};
438
+ })
439
+ : {};
440
+ if (declaresCoordinateReferenceSystem(omeLevelGroupAttributes)) {
441
+ layout = omeLayout;
442
+ level = omeLevel;
443
+ levelGroupAttributes = omeLevelGroupAttributes;
444
+ }
445
+ }
416
446
  const attributes = {
417
447
  ...groupAttributes,
418
448
  ...levelGroupAttributes,
@@ -449,13 +479,22 @@ export class GeoZarrRasterSource
449
479
  const xDimensionIndex = dimensions.indexOf(spatialDimensions[1]);
450
480
  const width = array.shape[xDimensionIndex];
451
481
  const height = array.shape[yDimensionIndex];
482
+ let gridMappingPromise: Promise<CFGridMapping | null> | undefined;
483
+ const getGridMapping = () =>
484
+ (gridMappingPromise ||= loadCFGridMapping(group, arrayPath, attributes, signal));
452
485
  const coordinateTransform =
453
486
  options?.transform ||
454
487
  normalizeAffineTransform(attributes['spatial:transform']) ||
455
- (!metadataOnly ? await loadCFCoordinateTransform(group, spatialDimensions, signal) : null);
488
+ // An ancestor grid mapping can be shared by several multiscale levels: it gives the CRS only.
489
+ normalizeGDALGeoTransform(
490
+ await getGridMapping().then(mapping => (mapping?.local ? mapping.attributes.GeoTransform : null))
491
+ ) ||
492
+ (!metadataOnly
493
+ ? await loadCFCoordinateTransform(group, arrayPath, spatialDimensions, signal)
494
+ : null);
456
495
  if (!coordinateTransform) {
457
496
  throw new Error(
458
- 'GeoZarrRasterSource requires spatial:transform metadata, explicit geozarr.transform, or regular 1D CF coordinate arrays.'
497
+ 'GeoZarrRasterSource requires spatial:transform metadata, explicit geozarr.transform, a CF grid-mapping GeoTransform, or regular 1D CF coordinate arrays.'
459
498
  );
460
499
  }
461
500
 
@@ -472,7 +511,10 @@ export class GeoZarrRasterSource
472
511
  const coordinateReferenceSystem =
473
512
  options?.coordinateReferenceSystem ||
474
513
  normalizeDeclaredCoordinateReferenceSystem(attributes) ||
475
- await loadCFCoordinateReferenceSystem(group, attributes, spatialDimensions, signal);
514
+ getCFCoordinateReferenceSystem(
515
+ (await getGridMapping())?.attributes || null,
516
+ spatialDimensions
517
+ );
476
518
  const defaultSelection = options?.defaultSelection || {};
477
519
  const selectionDimensions = dimensions
478
520
  .map((dimensionName, dimensionIndex) => ({
@@ -517,7 +559,7 @@ export class GeoZarrRasterSource
517
559
  registration: declaredRegistration
518
560
  };
519
561
 
520
- return {group, array, metadata, xDimensionIndex, yDimensionIndex};
562
+ return {group, array, metadata, xDimensionIndex, yDimensionIndex, layout};
521
563
  }
522
564
  }
523
565
 
@@ -633,18 +675,27 @@ function convertNodeTransformToPixelTransform(
633
675
  /** Loads regular one-dimensional CF coordinate variables and derives a pixel-corner transform. */
634
676
  async function loadCFCoordinateTransform(
635
677
  group: zarrita.Group<Readable>,
678
+ arrayPath: string,
636
679
  spatialDimensions: [y: string, x: string],
637
680
  signal?: AbortSignal
638
681
  ): Promise<GeoZarrAffineTransform | null> {
682
+ let coordinates: [number[], number[]];
639
683
  try {
640
- const [yCoordinates, xCoordinates] = await Promise.all([
641
- loadCoordinateValues(group, spatialDimensions[0], signal),
642
- loadCoordinateValues(group, spatialDimensions[1], signal)
684
+ coordinates = await Promise.all([
685
+ loadCoordinateValues(group, arrayPath, spatialDimensions[0], signal),
686
+ loadCoordinateValues(group, arrayPath, spatialDimensions[1], signal)
643
687
  ]);
688
+ } catch (error) {
689
+ rethrowUnlessAbsent(error);
690
+ return null;
691
+ }
692
+ const [yCoordinates, xCoordinates] = coordinates;
693
+ try {
644
694
  const scaleX = getRegularCoordinateSpacing(xCoordinates, spatialDimensions[1]);
645
695
  const scaleY = getRegularCoordinateSpacing(yCoordinates, spatialDimensions[0]);
646
696
  return [scaleX, 0, xCoordinates[0] - scaleX / 2, 0, scaleY, yCoordinates[0] - scaleY / 2];
647
697
  } catch {
698
+ // Irregular coordinates give no affine transform.
648
699
  return null;
649
700
  }
650
701
  }
@@ -652,13 +703,11 @@ async function loadCFCoordinateTransform(
652
703
  /** Loads all values from one one-dimensional coordinate variable. */
653
704
  async function loadCoordinateValues(
654
705
  group: zarrita.Group<Readable>,
706
+ arrayPath: string,
655
707
  coordinateName: string,
656
708
  signal?: AbortSignal
657
709
  ): Promise<number[]> {
658
- const coordinateArray = await zarrita.open(group.resolve(coordinateName), {
659
- kind: 'array',
660
- signal
661
- });
710
+ const {array: coordinateArray} = await openNearestArray(group, arrayPath, coordinateName, signal);
662
711
  if (coordinateArray.shape.length !== 1 || coordinateArray.shape[0] < 2) {
663
712
  throw new Error(
664
713
  `Coordinate ${coordinateName} must be a one-dimensional array with at least two values.`
@@ -671,6 +720,36 @@ async function loadCoordinateValues(
671
720
  return Array.from(coordinateChunk.data as ArrayLike<number>);
672
721
  }
673
722
 
723
+ /**
724
+ * Opens a CF variable referenced by name from a data array, searching the array's own group and
725
+ * then each ancestor up to the selected group, as CF 1.8 search by proximity specifies. `local`
726
+ * is true when the variable is in the array's own group.
727
+ */
728
+ async function openNearestArray(
729
+ group: zarrita.Group<Readable>,
730
+ arrayPath: string,
731
+ name: string,
732
+ signal?: AbortSignal
733
+ ): Promise<{array: zarrita.Array<zarrita.DataType, Readable>; local: boolean}> {
734
+ const segments = arrayPath.split('/').slice(0, -1);
735
+ let lastError: unknown;
736
+ for (let depth = segments.length; depth >= 0; depth--) {
737
+ const path = [...segments.slice(0, depth), name].join('/');
738
+ try {
739
+ const array = await zarrita.open(group.resolve(path), {kind: 'array', signal});
740
+ return {array, local: depth === segments.length};
741
+ } catch (error) {
742
+ // Only an absent variable continues the search. A local variable that exists but cannot be
743
+ // read must fail, not be replaced by an ancestor of the same name.
744
+ if (!zarrita.isZarritaError(error, 'NotFoundError')) {
745
+ throw error;
746
+ }
747
+ lastError = error;
748
+ }
749
+ }
750
+ throw lastError;
751
+ }
752
+
674
753
  /** Validates that coordinate values are finite and regularly spaced. */
675
754
  function getRegularCoordinateSpacing(coordinates: number[], coordinateName: string): number {
676
755
  const spacing = (coordinates.at(-1)! - coordinates[0]) / (coordinates.length - 1);
@@ -691,33 +770,51 @@ function getRegularCoordinateSpacing(coordinates: number[], coordinateName: stri
691
770
  return spacing;
692
771
  }
693
772
 
694
- /** Resolves CRS metadata from a CF grid-mapping variable or longitude/latitude dimensions. */
695
- async function loadCFCoordinateReferenceSystem(
773
+ /** Attributes of a CF grid-mapping variable, and whether it is in the data array's own group. */
774
+ type CFGridMapping = {attributes: GeoZarrAttributes; local: boolean};
775
+
776
+ /** Loads the CF grid-mapping variable named by a data array, if any. */
777
+ async function loadCFGridMapping(
696
778
  group: zarrita.Group<Readable>,
779
+ arrayPath: string,
697
780
  attributes: GeoZarrAttributes,
698
- spatialDimensions: [y: string, x: string],
699
781
  signal?: AbortSignal
700
- ): Promise<string | undefined> {
782
+ ): Promise<CFGridMapping | null> {
701
783
  const gridMapping = normalizeString(attributes.grid_mapping);
702
- if (gridMapping) {
703
- const gridMappingName = gridMapping.trim().split(/[\s:]/, 1)[0];
704
- try {
705
- const gridMappingArray = await zarrita.open(group.resolve(gridMappingName), {
706
- kind: 'array',
707
- signal
708
- });
709
- const gridMappingAttributes = normalizeAttributes(gridMappingArray.attrs);
710
- const coordinateReferenceSystem =
711
- normalizeString(gridMappingAttributes.crs_wkt) ||
712
- normalizeString(gridMappingAttributes.spatial_ref) ||
713
- normalizeString(gridMappingAttributes['proj:wkt2']) ||
714
- normalizeString(gridMappingAttributes['proj:code']);
715
- if (coordinateReferenceSystem) {
716
- return coordinateReferenceSystem;
717
- }
718
- } catch {
719
- // Fall through to the common longitude/latitude CRS below.
720
- }
784
+ if (!gridMapping) return null;
785
+ const gridMappingName = gridMapping.trim().split(/[\s:]/, 1)[0];
786
+ try {
787
+ const {array, local} = await openNearestArray(group, arrayPath, gridMappingName, signal);
788
+ return {attributes: normalizeAttributes(array.attrs), local};
789
+ } catch (error) {
790
+ rethrowUnlessAbsent(error);
791
+ return null;
792
+ }
793
+ }
794
+
795
+ /**
796
+ * Rethrows every error except an absent node. An absent CF variable means "no georeference"; a
797
+ * variable that exists but cannot be read must fail, not give a plausible but wrong result.
798
+ */
799
+ function rethrowUnlessAbsent(error: unknown): void {
800
+ if (!zarrita.isZarritaError(error, 'NotFoundError')) {
801
+ throw error;
802
+ }
803
+ }
804
+
805
+ /** Resolves CRS metadata from CF grid-mapping attributes or longitude/latitude dimensions. */
806
+ function getCFCoordinateReferenceSystem(
807
+ gridMappingAttributes: GeoZarrAttributes | null,
808
+ spatialDimensions: [y: string, x: string]
809
+ ): string | undefined {
810
+ const coordinateReferenceSystem =
811
+ gridMappingAttributes &&
812
+ (normalizeString(gridMappingAttributes.crs_wkt) ||
813
+ normalizeString(gridMappingAttributes.spatial_ref) ||
814
+ normalizeString(gridMappingAttributes['proj:wkt2']) ||
815
+ normalizeString(gridMappingAttributes['proj:code']));
816
+ if (coordinateReferenceSystem) {
817
+ return coordinateReferenceSystem;
721
818
  }
722
819
 
723
820
  const normalizedDimensions = spatialDimensions.map(dimension => dimension.toLowerCase());
@@ -730,6 +827,60 @@ async function loadCFCoordinateReferenceSystem(
730
827
  return undefined;
731
828
  }
732
829
 
830
+ /**
831
+ * Reads a GDAL `GeoTransform` (`originX pixelWidth rotationX originY rotationY pixelHeight`, a
832
+ * pixel-corner affine) from a CF grid-mapping variable, as written by GDAL and rioxarray.
833
+ */
834
+ function normalizeGDALGeoTransform(value: unknown): GeoZarrAffineTransform | null {
835
+ const coefficients = typeof value === 'string' ? value.trim().split(/\s+/).map(Number) : value;
836
+ if (
837
+ !Array.isArray(coefficients) || coefficients.length !== 6 ||
838
+ coefficients.some(coefficient => typeof coefficient !== 'number' || !Number.isFinite(coefficient))
839
+ ) {
840
+ return null;
841
+ }
842
+ const [originX, pixelWidth, rotationX, originY, rotationY, pixelHeight] = coefficients as number[];
843
+ if (pixelWidth === 0 || pixelHeight === 0) return null;
844
+ return [pixelWidth, rotationX, originX, rotationY, pixelHeight, originY];
845
+ }
846
+
847
+ /** Whether attributes declare a CRS through GeoZarr `proj:*` metadata or a CF grid mapping. */
848
+ /**
849
+ * OME-NGFF levels read as spatial levels, or none. Native OME metadata that is not valid as
850
+ * spatial levels stays native: this probe must not make an existing microscopy store fail.
851
+ */
852
+ function getOMELevelsOrEmpty(attributes: GeoZarrAttributes, arrayPath: string) {
853
+ try {
854
+ return getSpatialMultiscaleLevels(attributes, arrayPath, {spatialOME: true});
855
+ } catch {
856
+ return [];
857
+ }
858
+ }
859
+
860
+ function declaresCoordinateReferenceSystem(attributes: GeoZarrAttributes): boolean {
861
+ return Boolean(
862
+ normalizeDeclaredCoordinateReferenceSystem(attributes) || normalizeString(attributes.grid_mapping)
863
+ );
864
+ }
865
+
866
+ /**
867
+ * Whether a level's cell size relative to the selected level matches its OME-NGFF scale relative
868
+ * to the selected level. The OME frame may differ from the CRS frame, so only ratios are compared.
869
+ */
870
+ function isConsistentOMELevel(
871
+ scale: Readonly<Record<string, number>>,
872
+ selectedScale: Readonly<Record<string, number>>,
873
+ level: Pick<GeoZarrSourceMetadata, 'transform'>,
874
+ selected: Pick<GeoZarrSourceMetadata, 'transform' | 'spatialDimensions'>
875
+ ): boolean {
876
+ return selected.spatialDimensions.every((dimension, index) => {
877
+ const coefficient = index === 0 ? 4 : 0;
878
+ const expected = Math.abs(scale[dimension] / selectedScale[dimension]);
879
+ const actual = Math.abs(level.transform[coefficient] / selected.transform[coefficient]);
880
+ return Number.isFinite(expected) && Math.abs(actual - expected) <= expected * 1e-6;
881
+ });
882
+ }
883
+
733
884
  /** Computes a bounding box from all four transformed raster corners. */
734
885
  function getTransformBoundingBox(
735
886
  transform: GeoZarrAffineTransform,
@@ -12,13 +12,25 @@ export type SpatialMultiscaleLevel = {
12
12
  group?: string;
13
13
  /** Absolute spatial metadata advertised on the layout entry. */
14
14
  attributes: Record<string, unknown>;
15
+ /**
16
+ * OME-NGFF scale per axis name, composed from the dataset and multiscale transforms. Only its
17
+ * ratios between levels are checked against georeferencing; it never georeferences a level.
18
+ */
19
+ scale?: Readonly<Record<string, number>>;
15
20
  };
16
21
 
17
- /** Resolves direct-array or common-variable group layouts without following external paths. */
22
+ /**
23
+ * Resolves direct-array or common-variable group layouts without following external paths.
24
+ * OME-NGFF `datasets[]` are read as spatial levels only with `spatialOME`, which callers set when
25
+ * the selected array declares a CRS; native OME metadata is otherwise not recast as spatial.
26
+ */
18
27
  export function getSpatialMultiscaleLevels(
19
28
  attributes: Record<string, unknown>,
20
- array: string
29
+ array: string,
30
+ {spatialOME = false}: {spatialOME?: boolean} = {}
21
31
  ): SpatialMultiscaleLevel[] {
32
+ const omeMultiscales = spatialOME ? getOMEMultiscales(attributes) : null;
33
+ if (omeMultiscales) return getOMEMultiscaleLevels(omeMultiscales, array);
22
34
  const multiscales = attributes?.multiscales as {layout?: unknown} | undefined;
23
35
  const layout = multiscales?.layout;
24
36
  if (!Array.isArray(layout) || !layout.length) return [];
@@ -28,20 +40,104 @@ export function getSpatialMultiscaleLevels(
28
40
  }
29
41
  const assets = entries.map(entry => entry.asset as string);
30
42
  if (new Set(assets).size !== assets.length) throw new Error('Duplicate spatial multiscales asset.');
43
+ return resolveLevels(assets, array, entries);
44
+ }
45
+
46
+ /** Returns OME-NGFF v0.4 root `multiscales` or v0.5 `ome.multiscales`, if declared. */
47
+ function getOMEMultiscales(attributes: Record<string, unknown>): unknown[] | null {
48
+ if (Array.isArray(attributes?.multiscales)) return attributes.multiscales;
49
+ const ome = attributes?.ome as {multiscales?: unknown} | undefined;
50
+ return Array.isArray(ome?.multiscales) ? ome.multiscales : null;
51
+ }
52
+
53
+ /**
54
+ * Resolves OME-NGFF `datasets[]` as levels. Only the multiscale whose dataset paths contain the
55
+ * selected array is used. Scales are composed for validation; translations are allowed and
56
+ * ignored, and any other transform is rejected.
57
+ */
58
+ function getOMEMultiscaleLevels(multiscales: unknown[], array: string): SpatialMultiscaleLevel[] {
59
+ const candidates = multiscales.filter(multiscale => {
60
+ const datasets = (multiscale as {datasets?: unknown})?.datasets;
61
+ return Array.isArray(datasets) && datasets.some(dataset =>
62
+ isChildPath(dataset?.path) && (array === dataset.path || array.startsWith(`${dataset.path}/`)));
63
+ }) as Array<Record<string, unknown>>;
64
+ if (!candidates.length) return [];
65
+ if (candidates.length > 1) throw new Error('Array belongs to more than one OME-NGFF multiscale.');
66
+ const multiscale = candidates[0];
67
+ const datasets = multiscale.datasets as Array<Record<string, unknown>>;
68
+ if (datasets.some(dataset => !dataset || !isChildPath(dataset.path))) {
69
+ throw new Error('OME-NGFF dataset paths must be relative child paths.');
70
+ }
71
+ const paths = datasets.map(dataset => dataset.path as string);
72
+ if (new Set(paths).size !== paths.length) throw new Error('Duplicate OME-NGFF dataset path.');
73
+ const axes = getOMEAxisNames(multiscale.axes);
74
+ return resolveLevels(paths, array, datasets.map(() => ({}))).map((level, index) => ({
75
+ ...level,
76
+ scale: getOMEScale(axes, [
77
+ datasets[index].coordinateTransformations,
78
+ multiscale.coordinateTransformations
79
+ ])
80
+ }));
81
+ }
82
+
83
+ /** Maps every asset to the selected variable's path at that level. */
84
+ function resolveLevels(
85
+ assets: string[],
86
+ array: string,
87
+ attributes: Array<Record<string, unknown>>
88
+ ): SpatialMultiscaleLevel[] {
31
89
  const matches = assets.filter(asset => array === asset || array.startsWith(`${asset}/`));
32
90
  if (matches.length !== 1) return [];
33
91
  const suffix = array.slice(matches[0].length);
34
- return entries.map((entry, index) => ({
35
- id: assets[index],
36
- array: `${assets[index]}${suffix}`,
37
- ...(suffix ? {group: assets[index]} : {}),
38
- attributes: entry
92
+ return assets.map((asset, index) => ({
93
+ id: asset,
94
+ array: `${asset}${suffix}`,
95
+ ...(suffix ? {group: asset} : {}),
96
+ attributes: attributes[index]
39
97
  }));
40
98
  }
41
99
 
100
+ /** Reads axis names from v0.4+ axis objects or v0.3 axis strings. */
101
+ function getOMEAxisNames(axes: unknown): string[] {
102
+ const names = Array.isArray(axes)
103
+ ? axes.map(axis => (typeof axis === 'string' ? axis : (axis as {name?: unknown})?.name))
104
+ : [];
105
+ if (!names.length || names.some(name => typeof name !== 'string' || !name)) {
106
+ throw new Error('OME-NGFF multiscales require named axes.');
107
+ }
108
+ if (new Set(names).size !== names.length) throw new Error('Duplicate OME-NGFF axis name.');
109
+ return names as string[];
110
+ }
111
+
112
+ /** Composes scale transforms in the specified order: dataset first, then multiscale. */
113
+ function getOMEScale(axes: string[], transformLists: unknown[]): Record<string, number> {
114
+ const scale = axes.map(() => 1);
115
+ for (const transforms of transformLists) {
116
+ if (transforms === undefined) continue;
117
+ if (!Array.isArray(transforms)) {
118
+ throw new Error('OME-NGFF coordinateTransformations must be a list.');
119
+ }
120
+ for (const transform of transforms as Array<Record<string, unknown>>) {
121
+ if (transform?.type === 'translation') continue;
122
+ if (transform?.type !== 'scale') {
123
+ throw new Error(`Unsupported OME-NGFF coordinate transformation ${String(transform?.type)}.`);
124
+ }
125
+ const values = transform.scale;
126
+ if (
127
+ !Array.isArray(values) || values.length !== axes.length ||
128
+ values.some(value => typeof value !== 'number' || !Number.isFinite(value) || value === 0)
129
+ ) {
130
+ throw new Error('OME-NGFF scale must give one finite non-zero value per axis.');
131
+ }
132
+ values.forEach((value, index) => (scale[index] *= value as number));
133
+ }
134
+ }
135
+ return Object.fromEntries(axes.map((axis, index) => [axis, scale[index]]));
136
+ }
137
+
42
138
  /** Accepts literal relative child paths, rejecting URL, encoded, and traversal syntax. */
43
139
  function isChildPath(value: unknown): value is string {
44
140
  return typeof value === 'string' && value.length > 0 &&
45
- !/[\\%:?#\u0000-\u0020]/.test(value) &&
141
+ !/[\\%:?#\u0000- ]/.test(value) &&
46
142
  value.split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..');
47
143
  }
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Michaël Zasso
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.