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

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 (176) hide show
  1. package/LICENSE +2 -30
  2. package/README.md +15 -3
  3. package/THIRD-PARTY-NOTICES.md +21 -0
  4. package/dist/hdf5/http-range-reader.d.ts.map +1 -1
  5. package/dist/hdf5/http-range-reader.js +2 -12
  6. package/dist/hdf5/http-range-reader.js.map +1 -1
  7. package/dist/hdf5/index.cjs +2 -11
  8. package/dist/hdf5/index.cjs.map +2 -2
  9. package/dist/index.cjs +136 -4148
  10. package/dist/index.cjs.map +4 -3
  11. package/dist/index.d.ts +14 -7
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +7 -4
  14. package/dist/index.js.map +1 -1
  15. package/dist/lib/parsers/parse-npy.d.ts +15 -0
  16. package/dist/lib/parsers/parse-npy.d.ts.map +1 -0
  17. package/dist/lib/parsers/parse-npy.js +81 -0
  18. package/dist/lib/parsers/parse-npy.js.map +1 -0
  19. package/dist/netcdf/bundled.cjs +47 -46
  20. package/dist/netcdf/index.cjs +47 -46
  21. package/dist/netcdf/index.cjs.map +3 -3
  22. package/dist/netcdf/index.d.ts +2 -1
  23. package/dist/netcdf/index.d.ts.map +1 -1
  24. package/dist/netcdf/index.js +2 -1
  25. package/dist/netcdf/index.js.map +1 -1
  26. package/dist/netcdf/netcdf-loader-with-parser.cjs +396 -2
  27. package/dist/netcdf/netcdf-loader-with-parser.d.ts +10 -0
  28. package/dist/netcdf/netcdf-loader-with-parser.d.ts.map +1 -1
  29. package/dist/netcdf/netcdf-loader-with-parser.js +3 -1
  30. package/dist/netcdf/netcdf-loader-with-parser.js.map +1 -1
  31. package/dist/netcdf/netcdf-loader.cjs +12 -9
  32. package/dist/netcdf/netcdf-loader.cjs.map +7 -0
  33. package/dist/netcdf/netcdf-loader.d.ts +10 -21
  34. package/dist/netcdf/netcdf-loader.d.ts.map +1 -1
  35. package/dist/netcdf/netcdf-loader.js +6 -3
  36. package/dist/netcdf/netcdf-loader.js.map +1 -1
  37. package/dist/netcdf/netcdf-source-loader.cjs +17 -31
  38. package/dist/netcdf/netcdf-source-loader.d.ts +2 -20
  39. package/dist/netcdf/netcdf-source-loader.d.ts.map +1 -1
  40. package/dist/netcdf/netcdf-source-loader.js +22 -20
  41. package/dist/netcdf/netcdf-source-loader.js.map +1 -1
  42. package/dist/netcdf/unbundled.cjs +47 -46
  43. package/dist/netcdf.dev.js +3095 -2654
  44. package/dist/netcdf.min.js +4 -4
  45. package/dist/npy-format.d.ts +12 -0
  46. package/dist/npy-format.d.ts.map +1 -0
  47. package/dist/npy-format.js +15 -0
  48. package/dist/npy-format.js.map +1 -0
  49. package/dist/{netcdf/netcdf-source-loader-types.cjs → npy-loader-types.cjs} +34 -35
  50. package/dist/npy-loader-types.cjs.map +7 -0
  51. package/dist/npy-loader-types.d.ts +53 -0
  52. package/dist/npy-loader-types.d.ts.map +1 -0
  53. package/dist/npy-loader-types.js +32 -0
  54. package/dist/npy-loader-types.js.map +1 -0
  55. package/dist/npy-loader.cjs +273 -0
  56. package/dist/npy-loader.cjs.map +6 -0
  57. package/dist/npy-loader.d.ts +27 -0
  58. package/dist/npy-loader.d.ts.map +1 -0
  59. package/dist/npy-loader.js +15 -0
  60. package/dist/npy-loader.js.map +1 -0
  61. package/dist/npy-worker.d.ts +2 -0
  62. package/dist/npy-worker.d.ts.map +1 -0
  63. package/dist/npy-worker.js +1285 -0
  64. package/dist/npy-worker.js.map +1 -0
  65. package/dist/nrrd/parse-nrrd.d.ts +22 -0
  66. package/dist/nrrd/parse-nrrd.d.ts.map +1 -0
  67. package/dist/nrrd/parse-nrrd.js +228 -0
  68. package/dist/nrrd/parse-nrrd.js.map +1 -0
  69. package/dist/nrrd-loader-types.cjs +58 -0
  70. package/dist/nrrd-loader-types.cjs.map +7 -0
  71. package/dist/nrrd-loader-types.d.ts +31 -0
  72. package/dist/nrrd-loader-types.d.ts.map +1 -0
  73. package/dist/nrrd-loader-types.js +25 -0
  74. package/dist/nrrd-loader-types.js.map +1 -0
  75. package/dist/nrrd-loader.cjs +252 -0
  76. package/dist/nrrd-loader.cjs.map +6 -0
  77. package/dist/nrrd-loader.d.ts +16 -0
  78. package/dist/nrrd-loader.d.ts.map +1 -0
  79. package/dist/nrrd-loader.js +8 -0
  80. package/dist/nrrd-loader.js.map +1 -0
  81. package/dist/vtk/index.cjs +26 -4117
  82. package/dist/vtk/index.cjs.map +3 -3
  83. package/dist/vtk/vtk-xml.js +4 -4
  84. package/dist/vtk/vtk-xml.js.map +1 -1
  85. package/dist/vtk/vtk.d.ts.map +1 -1
  86. package/dist/vtk/vtk.js +19 -1
  87. package/dist/vtk/vtk.js.map +1 -1
  88. package/dist/vtk-loader-types.cjs +58 -0
  89. package/dist/vtk-loader-types.cjs.map +7 -0
  90. package/dist/vtk-loader-types.d.ts +34 -0
  91. package/dist/vtk-loader-types.d.ts.map +1 -0
  92. package/dist/vtk-loader-types.js +25 -0
  93. package/dist/vtk-loader-types.js.map +1 -0
  94. package/dist/vtk-loader.cjs +384 -0
  95. package/dist/vtk-loader.cjs.map +6 -0
  96. package/dist/vtk-loader.d.ts +21 -0
  97. package/dist/vtk-loader.d.ts.map +1 -0
  98. package/dist/vtk-loader.js +21 -0
  99. package/dist/vtk-loader.js.map +1 -0
  100. package/dist/workers/npy-worker.d.ts +2 -0
  101. package/dist/workers/npy-worker.d.ts.map +1 -0
  102. package/dist/workers/npy-worker.js +7 -0
  103. package/dist/workers/npy-worker.js.map +1 -0
  104. package/dist/zarr/{geo-zarr-source-loader.d.ts → geo-zarr-loader.d.ts} +9 -9
  105. package/dist/zarr/geo-zarr-loader.d.ts.map +1 -0
  106. package/dist/zarr/{geo-zarr-source-loader.js → geo-zarr-loader.js} +167 -48
  107. package/dist/zarr/geo-zarr-loader.js.map +1 -0
  108. package/dist/zarr/index.cjs +221 -70
  109. package/dist/zarr/index.cjs.map +3 -3
  110. package/dist/zarr/index.d.ts +8 -8
  111. package/dist/zarr/index.d.ts.map +1 -1
  112. package/dist/zarr/index.js +4 -4
  113. package/dist/zarr/index.js.map +1 -1
  114. package/dist/zarr/lib/spatial-multiscales.d.ts +13 -2
  115. package/dist/zarr/lib/spatial-multiscales.d.ts.map +1 -1
  116. package/dist/zarr/lib/spatial-multiscales.js +94 -8
  117. package/dist/zarr/lib/spatial-multiscales.js.map +1 -1
  118. package/dist/zarr/{ome-zarr-source-loader.d.ts → ome-zarr-loader.d.ts} +9 -9
  119. package/dist/zarr/ome-zarr-loader.d.ts.map +1 -0
  120. package/dist/zarr/{ome-zarr-source-loader.js → ome-zarr-loader.js} +5 -5
  121. package/dist/zarr/ome-zarr-loader.js.map +1 -0
  122. package/dist/zarr/{spatial-data-source.d.ts → spatial-data-loader.d.ts} +11 -11
  123. package/dist/zarr/spatial-data-loader.d.ts.map +1 -0
  124. package/dist/zarr/{spatial-data-source.js → spatial-data-loader.js} +7 -7
  125. package/dist/zarr/spatial-data-loader.js.map +1 -0
  126. package/dist/zarr/{zarr-array-source.d.ts → zarr-array-loader.d.ts} +9 -9
  127. package/dist/zarr/{zarr-array-source.d.ts.map → zarr-array-loader.d.ts.map} +1 -1
  128. package/dist/zarr/{zarr-array-source.js → zarr-array-loader.js} +5 -5
  129. package/dist/zarr/{zarr-array-source.js.map → zarr-array-loader.js.map} +1 -1
  130. package/dist/zarr/zarr-loader-types.cjs +161 -0
  131. package/dist/zarr/zarr-loader-types.cjs.map +7 -0
  132. package/dist/zarr/zarr-loader-types.d.ts +32 -32
  133. package/dist/zarr/zarr-loader-types.d.ts.map +1 -1
  134. package/dist/zarr/zarr-loader-types.js +24 -24
  135. package/dist/zarr/zarr-loader-types.js.map +1 -1
  136. package/dist/zarr.dev.js +305 -84
  137. package/dist/zarr.min.js +50 -50
  138. package/package.json +58 -8
  139. package/src/hdf5/http-range-reader.ts +3 -11
  140. package/src/index.ts +27 -16
  141. package/src/lib/parsers/parse-npy.ts +123 -0
  142. package/src/netcdf/index.ts +2 -5
  143. package/src/netcdf/netcdf-loader-with-parser.ts +3 -1
  144. package/src/netcdf/netcdf-loader.ts +5 -3
  145. package/src/netcdf/netcdf-source-loader.ts +32 -24
  146. package/src/npy-format.ts +17 -0
  147. package/src/npy-loader-types.ts +47 -0
  148. package/src/npy-loader.ts +21 -0
  149. package/src/npy-worker.ts +6 -0
  150. package/src/nrrd/parse-nrrd.ts +267 -0
  151. package/src/nrrd-loader-types.ts +25 -0
  152. package/src/nrrd-loader.ts +7 -0
  153. package/src/vtk/vtk-xml.ts +4 -4
  154. package/src/vtk/vtk.ts +28 -1
  155. package/src/vtk-loader-types.ts +25 -0
  156. package/src/vtk-loader.ts +19 -0
  157. package/src/workers/npy-worker.ts +8 -0
  158. package/src/zarr/{geo-zarr-source-loader.ts → geo-zarr-loader.ts} +206 -55
  159. package/src/zarr/index.ts +17 -17
  160. package/src/zarr/lib/spatial-multiscales.ts +104 -8
  161. package/src/zarr/{ome-zarr-source-loader.ts → ome-zarr-loader.ts} +11 -11
  162. package/src/zarr/{spatial-data-source.ts → spatial-data-loader.ts} +16 -16
  163. package/src/zarr/{zarr-array-source.ts → zarr-array-loader.ts} +10 -10
  164. package/src/zarr/zarr-loader-types.ts +35 -35
  165. package/third-party-licenses/iobuffer-LICENSE +21 -0
  166. package/dist/netcdf/netcdf-source-loader-types.d.ts +0 -28
  167. package/dist/netcdf/netcdf-source-loader-types.d.ts.map +0 -1
  168. package/dist/netcdf/netcdf-source-loader-types.js +0 -32
  169. package/dist/netcdf/netcdf-source-loader-types.js.map +0 -1
  170. package/dist/zarr/geo-zarr-source-loader.d.ts.map +0 -1
  171. package/dist/zarr/geo-zarr-source-loader.js.map +0 -1
  172. package/dist/zarr/ome-zarr-source-loader.d.ts.map +0 -1
  173. package/dist/zarr/ome-zarr-source-loader.js.map +0 -1
  174. package/dist/zarr/spatial-data-source.d.ts.map +0 -1
  175. package/dist/zarr/spatial-data-source.js.map +0 -1
  176. package/src/netcdf/netcdf-source-loader-types.ts +0 -45
@@ -26,8 +26,9 @@ 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
- import {ZarrSource, type ZarrSourceLoaderOptions} from './ome-zarr-source-loader';
31
+ import {ZarrSource, type ZarrLoaderOptions} from './ome-zarr-loader';
31
32
  import {
32
33
  cloneZarrSelection,
33
34
  getCachedZarrSelection,
@@ -86,8 +87,8 @@ export type GeoZarrSourceMetadata = RasterSourceMetadata & {
86
87
  registration: 'pixel' | 'node';
87
88
  };
88
89
 
89
- /** Options for {@link GeoZarrSourceLoader}. */
90
- export type GeoZarrSourceLoaderOptions = ZarrSourceLoaderOptions & {
90
+ /** Options for {@link GeoZarrLoader}. */
91
+ export type GeoZarrLoaderOptions = ZarrLoaderOptions & {
91
92
  /** GeoZarr and CF data-variable options. */
92
93
  geozarr?: {
93
94
  /** Data-array path relative to `zarr.path`. */
@@ -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 = {
@@ -133,12 +136,12 @@ type PixelWindow = {
133
136
  };
134
137
 
135
138
  /** Source factory for GeoZarr and regular CF/xarray Zarr raster arrays. */
136
- export const GeoZarrSourceLoaderWithParser = {
139
+ export const GeoZarrLoaderWithParser = {
137
140
  dataType: null as unknown as GeoZarrRasterSource,
138
141
  /** Runtime source type marker used by `createDataSource()` type inference. */
139
142
  dataSource: null as unknown as GeoZarrRasterSource,
140
143
  batchType: null as never,
141
- name: 'GeoZarrSourceLoader',
144
+ name: 'GeoZarrLoader',
142
145
  id: 'geozarr',
143
146
  module: 'scientific',
144
147
  version: VERSION,
@@ -162,7 +165,7 @@ export const GeoZarrSourceLoaderWithParser = {
162
165
  coordinateReferenceSystem: undefined!,
163
166
  defaultSelection: undefined!
164
167
  }
165
- } as GeoZarrSourceLoaderOptions,
168
+ } as GeoZarrLoaderOptions,
166
169
 
167
170
  defaultOptions: {
168
171
  zarr: {
@@ -181,9 +184,9 @@ export const GeoZarrSourceLoaderWithParser = {
181
184
  },
182
185
 
183
186
  testURL: (url: string): boolean => /\.zarr(?:$|[/?#])/i.test(url),
184
- createDataSource: (
187
+ createDataSourceSync: (
185
188
  data: string,
186
- options: GeoZarrSourceLoaderOptions,
189
+ options: GeoZarrLoaderOptions,
187
190
  coreApi?: CoreAPI
188
191
  ): GeoZarrRasterSource => new GeoZarrRasterSource(data, options, coreApi)
189
192
  } as const satisfies SourceLoader<GeoZarrRasterSource>;
@@ -202,7 +205,7 @@ export class GeoZarrRasterSource
202
205
  private metadataPromise: Promise<GeoZarrSourceMetadata> | null = null;
203
206
 
204
207
  /** Creates a GeoZarr raster source. */
205
- constructor(data: string, options: GeoZarrSourceLoaderOptions, coreApi?: CoreAPI) {
208
+ constructor(data: string, options: GeoZarrLoaderOptions, coreApi?: CoreAPI) {
206
209
  super(data, options, coreApi);
207
210
  }
208
211
 
@@ -219,16 +222,14 @@ 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) {
228
229
  levels.push({id: level.id, array: level.array, metadata});
229
230
  continue;
230
231
  }
231
- const options = this.options as GeoZarrSourceLoaderOptions;
232
+ const options = this.options as GeoZarrLoaderOptions;
232
233
  const source = new GeoZarrRasterSource(
233
234
  this.data,
234
235
  {
@@ -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}];
@@ -397,7 +409,7 @@ export class GeoZarrRasterSource
397
409
  validatedGroup?: zarrita.Group<Readable>
398
410
  ): Promise<GeoZarrInit> {
399
411
  const group = validatedGroup || await this.openGroup(signal);
400
- const options = (this.options as GeoZarrSourceLoaderOptions).geozarr;
412
+ const options = (this.options as GeoZarrLoaderOptions).geozarr;
401
413
  const arrayPath = options?.array;
402
414
  if (!arrayPath) {
403
415
  throw new Error('GeoZarrRasterSource requires a geozarr.array data-variable path.');
@@ -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,
package/src/zarr/index.ts CHANGED
@@ -5,38 +5,38 @@
5
5
  export {loadZarr} from './lib/load-zarr';
6
6
  export {default as ZarrPixelSource} from './lib/zarr-pixel-source';
7
7
  export {
8
- OMEZarrSourceLoaderWithParser as OMEZarrSourceLoader,
8
+ OMEZarrLoaderWithParser as OMEZarrLoader,
9
9
  OMEZarrImageSource,
10
10
  loadZarrConsolidatedMetadata
11
- } from './ome-zarr-source-loader';
11
+ } from './ome-zarr-loader';
12
12
  export {
13
- GeoZarrSourceLoaderWithParser as GeoZarrSourceLoader,
13
+ GeoZarrLoaderWithParser as GeoZarrLoader,
14
14
  GeoZarrRasterSource
15
- } from './geo-zarr-source-loader';
15
+ } from './geo-zarr-loader';
16
16
  export {
17
- ZarrArraySourceLoaderWithParser as ZarrArraySourceLoader,
17
+ ZarrArrayLoaderWithParser as ZarrArrayLoader,
18
18
  ZarrArraySource
19
- } from './zarr-array-source';
19
+ } from './zarr-array-loader';
20
20
  export {
21
- SpatialDataSourceLoaderWithParser as SpatialDataSourceLoader,
21
+ SpatialDataLoaderWithParser as SpatialDataLoader,
22
22
  SpatialDataSource
23
- } from './spatial-data-source';
23
+ } from './spatial-data-loader';
24
24
  export type {
25
25
  GetZarrArrayParameters,
26
26
  ZarrArrayData,
27
27
  ZarrArraySelection,
28
28
  ZarrArraySlice,
29
- ZarrArraySourceLoaderOptions,
29
+ ZarrArrayLoaderOptions,
30
30
  ZarrArraySourceMetadata
31
- } from './zarr-array-source';
31
+ } from './zarr-array-loader';
32
32
  export type {
33
33
  SpatialDataElementFormat,
34
34
  SpatialDataElementKind,
35
35
  SpatialDataElementMetadata,
36
- SpatialDataSourceLoaderOptions,
36
+ SpatialDataLoaderOptions,
37
37
  SpatialDataSourceMetadata,
38
38
  SpatialDataZarrElementSource
39
- } from './spatial-data-source';
39
+ } from './spatial-data-loader';
40
40
  export type {
41
41
  GetOMEZarrParameters,
42
42
  LoadConsolidatedMetadataOptions,
@@ -47,14 +47,14 @@ export type {
47
47
  ZarrConsolidatedFormat,
48
48
  ZarrConsolidatedMetadata,
49
49
  ZarrMetadataPath,
50
- ZarrSourceLoader,
51
- ZarrSourceLoaderOptions
52
- } from './ome-zarr-source-loader';
50
+ ZarrLoader,
51
+ ZarrLoaderOptions
52
+ } from './ome-zarr-loader';
53
53
  export type {
54
54
  GeoZarrLevelMetadata,
55
55
  GeoZarrAffineTransform,
56
56
  GeoZarrSelectionDimension,
57
- GeoZarrSourceLoaderOptions,
57
+ GeoZarrLoaderOptions,
58
58
  GeoZarrSourceMetadata,
59
59
  GetGeoZarrParameters
60
- } from './geo-zarr-source-loader';
60
+ } from './geo-zarr-loader';
@@ -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 === 'identity' || 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
  }