@loaders.gl/scientific 0.0.0-stage → 5.0.0-alpha.13

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 (175) hide show
  1. package/README.md +21 -2
  2. package/dist/index.cjs +4313 -0
  3. package/dist/index.cjs.map +6 -0
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +8 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/netcdf/bundled.cjs +1394 -0
  9. package/dist/netcdf/bundled.d.ts +2 -0
  10. package/dist/netcdf/bundled.d.ts.map +1 -0
  11. package/dist/netcdf/bundled.js +5 -0
  12. package/dist/netcdf/bundled.js.map +1 -0
  13. package/dist/netcdf/index.cjs +1394 -0
  14. package/dist/netcdf/index.cjs.map +6 -0
  15. package/dist/netcdf/index.d.ts +7 -0
  16. package/dist/netcdf/index.d.ts.map +1 -0
  17. package/dist/netcdf/index.js +8 -0
  18. package/dist/netcdf/index.js.map +1 -0
  19. package/dist/netcdf/iobuffer/iobuffer.d.ts +253 -0
  20. package/dist/netcdf/iobuffer/iobuffer.d.ts.map +1 -0
  21. package/dist/netcdf/iobuffer/iobuffer.js +450 -0
  22. package/dist/netcdf/iobuffer/iobuffer.js.map +1 -0
  23. package/dist/netcdf/netcdf-format.cjs +39 -0
  24. package/dist/netcdf/netcdf-format.d.ts +11 -0
  25. package/dist/netcdf/netcdf-format.d.ts.map +1 -0
  26. package/dist/netcdf/netcdf-format.js +14 -0
  27. package/dist/netcdf/netcdf-format.js.map +1 -0
  28. package/dist/netcdf/netcdf-loader-with-parser.cjs +995 -0
  29. package/dist/netcdf/netcdf-loader-with-parser.d.ts +60 -0
  30. package/dist/netcdf/netcdf-loader-with-parser.d.ts.map +1 -0
  31. package/dist/netcdf/netcdf-loader-with-parser.js +35 -0
  32. package/dist/netcdf/netcdf-loader-with-parser.js.map +1 -0
  33. package/dist/netcdf/netcdf-loader.cjs +84 -0
  34. package/dist/netcdf/netcdf-loader.d.ts +81 -0
  35. package/dist/netcdf/netcdf-loader.d.ts.map +1 -0
  36. package/dist/netcdf/netcdf-loader.js +41 -0
  37. package/dist/netcdf/netcdf-loader.js.map +1 -0
  38. package/dist/netcdf/netcdf-source-loader-types.cjs +78 -0
  39. package/dist/netcdf/netcdf-source-loader-types.d.ts +28 -0
  40. package/dist/netcdf/netcdf-source-loader-types.d.ts.map +1 -0
  41. package/dist/netcdf/netcdf-source-loader-types.js +32 -0
  42. package/dist/netcdf/netcdf-source-loader-types.js.map +1 -0
  43. package/dist/netcdf/netcdf-source-loader.cjs +1319 -0
  44. package/dist/netcdf/netcdf-source-loader.d.ts +59 -0
  45. package/dist/netcdf/netcdf-source-loader.d.ts.map +1 -0
  46. package/dist/netcdf/netcdf-source-loader.js +421 -0
  47. package/dist/netcdf/netcdf-source-loader.js.map +1 -0
  48. package/dist/netcdf/netcdfjs/netcdf-reader.d.ts +68 -0
  49. package/dist/netcdf/netcdfjs/netcdf-reader.d.ts.map +1 -0
  50. package/dist/netcdf/netcdfjs/netcdf-reader.js +172 -0
  51. package/dist/netcdf/netcdfjs/netcdf-reader.js.map +1 -0
  52. package/dist/netcdf/netcdfjs/netcdf-types.d.ts +70 -0
  53. package/dist/netcdf/netcdfjs/netcdf-types.d.ts.map +1 -0
  54. package/dist/netcdf/netcdfjs/netcdf-types.js +3 -0
  55. package/dist/netcdf/netcdfjs/netcdf-types.js.map +1 -0
  56. package/dist/netcdf/netcdfjs/read-data.d.ts +19 -0
  57. package/dist/netcdf/netcdfjs/read-data.d.ts.map +1 -0
  58. package/dist/netcdf/netcdfjs/read-data.js +51 -0
  59. package/dist/netcdf/netcdfjs/read-data.js.map +1 -0
  60. package/dist/netcdf/netcdfjs/read-header.d.ts +16 -0
  61. package/dist/netcdf/netcdfjs/read-header.d.ts.map +1 -0
  62. package/dist/netcdf/netcdfjs/read-header.js +227 -0
  63. package/dist/netcdf/netcdfjs/read-header.js.map +1 -0
  64. package/dist/netcdf/netcdfjs/read-type.d.ts +36 -0
  65. package/dist/netcdf/netcdfjs/read-type.d.ts.map +1 -0
  66. package/dist/netcdf/netcdfjs/read-type.js +135 -0
  67. package/dist/netcdf/netcdfjs/read-type.js.map +1 -0
  68. package/dist/netcdf/unbundled.cjs +1394 -0
  69. package/dist/netcdf/unbundled.d.ts +2 -0
  70. package/dist/netcdf/unbundled.d.ts.map +1 -0
  71. package/dist/netcdf/unbundled.js +5 -0
  72. package/dist/netcdf/unbundled.js.map +1 -0
  73. package/dist/netcdf.dev.js +3153 -0
  74. package/dist/netcdf.min.js +12 -0
  75. package/dist/zarr/bundled.d.ts +2 -0
  76. package/dist/zarr/bundled.d.ts.map +1 -0
  77. package/dist/zarr/bundled.js +5 -0
  78. package/dist/zarr/bundled.js.map +1 -0
  79. package/dist/zarr/geo-zarr-source-loader.d.ts +121 -0
  80. package/dist/zarr/geo-zarr-source-loader.d.ts.map +1 -0
  81. package/dist/zarr/geo-zarr-source-loader.js +692 -0
  82. package/dist/zarr/geo-zarr-source-loader.js.map +1 -0
  83. package/dist/zarr/index.cjs +14747 -0
  84. package/dist/zarr/index.cjs.map +6 -0
  85. package/dist/zarr/index.d.ts +11 -0
  86. package/dist/zarr/index.d.ts.map +1 -0
  87. package/dist/zarr/index.js +10 -0
  88. package/dist/zarr/index.js.map +1 -0
  89. package/dist/zarr/lib/consolidated-zarr.d.ts +31 -0
  90. package/dist/zarr/lib/consolidated-zarr.d.ts.map +1 -0
  91. package/dist/zarr/lib/consolidated-zarr.js +113 -0
  92. package/dist/zarr/lib/consolidated-zarr.js.map +1 -0
  93. package/dist/zarr/lib/load-zarr.d.ts +11 -0
  94. package/dist/zarr/lib/load-zarr.d.ts.map +1 -0
  95. package/dist/zarr/lib/load-zarr.js +22 -0
  96. package/dist/zarr/lib/load-zarr.js.map +1 -0
  97. package/dist/zarr/lib/spatial-multiscales.d.ts +14 -0
  98. package/dist/zarr/lib/spatial-multiscales.d.ts.map +1 -0
  99. package/dist/zarr/lib/spatial-multiscales.js +34 -0
  100. package/dist/zarr/lib/spatial-multiscales.js.map +1 -0
  101. package/dist/zarr/lib/utils.d.ts +28 -0
  102. package/dist/zarr/lib/utils.d.ts.map +1 -0
  103. package/dist/zarr/lib/utils.js +137 -0
  104. package/dist/zarr/lib/utils.js.map +1 -0
  105. package/dist/zarr/lib/zarr-data-cache.d.ts +13 -0
  106. package/dist/zarr/lib/zarr-data-cache.d.ts.map +1 -0
  107. package/dist/zarr/lib/zarr-data-cache.js +70 -0
  108. package/dist/zarr/lib/zarr-data-cache.js.map +1 -0
  109. package/dist/zarr/lib/zarr-pixel-source.d.ts +41 -0
  110. package/dist/zarr/lib/zarr-pixel-source.d.ts.map +1 -0
  111. package/dist/zarr/lib/zarr-pixel-source.js +97 -0
  112. package/dist/zarr/lib/zarr-pixel-source.js.map +1 -0
  113. package/dist/zarr/lib/zarrita-pixel-source.d.ts +40 -0
  114. package/dist/zarr/lib/zarrita-pixel-source.d.ts.map +1 -0
  115. package/dist/zarr/lib/zarrita-pixel-source.js +96 -0
  116. package/dist/zarr/lib/zarrita-pixel-source.js.map +1 -0
  117. package/dist/zarr/ome-zarr-source-loader.d.ts +195 -0
  118. package/dist/zarr/ome-zarr-source-loader.d.ts.map +1 -0
  119. package/dist/zarr/ome-zarr-source-loader.js +523 -0
  120. package/dist/zarr/ome-zarr-source-loader.js.map +1 -0
  121. package/dist/zarr/spatial-data-source.d.ts +95 -0
  122. package/dist/zarr/spatial-data-source.d.ts.map +1 -0
  123. package/dist/zarr/spatial-data-source.js +242 -0
  124. package/dist/zarr/spatial-data-source.js.map +1 -0
  125. package/dist/zarr/types.d.ts +105 -0
  126. package/dist/zarr/types.d.ts.map +1 -0
  127. package/dist/zarr/types.js +5 -0
  128. package/dist/zarr/types.js.map +1 -0
  129. package/dist/zarr/unbundled.d.ts +2 -0
  130. package/dist/zarr/unbundled.d.ts.map +1 -0
  131. package/dist/zarr/unbundled.js +5 -0
  132. package/dist/zarr/unbundled.js.map +1 -0
  133. package/dist/zarr/zarr-array-source.d.ts +102 -0
  134. package/dist/zarr/zarr-array-source.d.ts.map +1 -0
  135. package/dist/zarr/zarr-array-source.js +132 -0
  136. package/dist/zarr/zarr-array-source.js.map +1 -0
  137. package/dist/zarr/zarr-loader-types.d.ts +236 -0
  138. package/dist/zarr/zarr-loader-types.d.ts.map +1 -0
  139. package/dist/zarr/zarr-loader-types.js +128 -0
  140. package/dist/zarr/zarr-loader-types.js.map +1 -0
  141. package/dist/zarr.dev.js +16574 -0
  142. package/dist/zarr.min.js +79 -0
  143. package/package.json +62 -4
  144. package/src/index.ts +52 -0
  145. package/src/netcdf/bundled.ts +5 -0
  146. package/src/netcdf/index.ts +14 -0
  147. package/src/netcdf/iobuffer/iobuffer.ts +510 -0
  148. package/src/netcdf/netcdf-format.ts +16 -0
  149. package/src/netcdf/netcdf-loader-with-parser.ts +54 -0
  150. package/src/netcdf/netcdf-loader.ts +62 -0
  151. package/src/netcdf/netcdf-source-loader-types.ts +45 -0
  152. package/src/netcdf/netcdf-source-loader.ts +526 -0
  153. package/src/netcdf/netcdfjs/LICENSE +24 -0
  154. package/src/netcdf/netcdfjs/netcdf-reader.ts +196 -0
  155. package/src/netcdf/netcdfjs/netcdf-types.ts +75 -0
  156. package/src/netcdf/netcdfjs/read-data.ts +71 -0
  157. package/src/netcdf/netcdfjs/read-header.ts +277 -0
  158. package/src/netcdf/netcdfjs/read-type.ts +147 -0
  159. package/src/netcdf/unbundled.ts +5 -0
  160. package/src/zarr/bundled.ts +5 -0
  161. package/src/zarr/geo-zarr-source-loader.ts +998 -0
  162. package/src/zarr/index.ts +60 -0
  163. package/src/zarr/lib/consolidated-zarr.ts +190 -0
  164. package/src/zarr/lib/load-zarr.ts +31 -0
  165. package/src/zarr/lib/spatial-multiscales.ts +47 -0
  166. package/src/zarr/lib/utils.ts +162 -0
  167. package/src/zarr/lib/zarr-data-cache.ts +91 -0
  168. package/src/zarr/lib/zarr-pixel-source.ts +134 -0
  169. package/src/zarr/lib/zarrita-pixel-source.ts +141 -0
  170. package/src/zarr/ome-zarr-source-loader.ts +837 -0
  171. package/src/zarr/spatial-data-source.ts +370 -0
  172. package/src/zarr/types.ts +129 -0
  173. package/src/zarr/unbundled.ts +5 -0
  174. package/src/zarr/zarr-array-source.ts +225 -0
  175. package/src/zarr/zarr-loader-types.ts +166 -0
@@ -0,0 +1,998 @@
1
+ // loaders.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import * as zarrita from 'zarrita';
6
+ import type {Readable} from 'zarrita';
7
+ import type {
8
+ TileGridMatrix,
9
+ CoreAPI,
10
+ GetRasterParameters,
11
+ RasterBoundingBox,
12
+ RasterChannelDataType,
13
+ RasterData,
14
+ RasterSource,
15
+ RasterSourceMetadata,
16
+ SourceLoader,
17
+ ScanQueryMetadata,
18
+ ScanQueryMetadataOptions,
19
+ ScanQueryMetadataProvider
20
+ } from '@loaders.gl/core/loader-utils';
21
+ import type {CRSDefinition} from '@math.gl/geospatial/crs';
22
+ import {
23
+ createTileGrid,
24
+ createScanQueryMetadata,
25
+ getRasterViewportBoundingBox
26
+ } from '@loaders.gl/core/loader-utils';
27
+
28
+ import {getSpatialMultiscaleLevels} from './lib/spatial-multiscales';
29
+ import type {SupportedTypedArray} from './types';
30
+ import {ZarrSource, type ZarrSourceLoaderOptions} from './ome-zarr-source-loader';
31
+ import {
32
+ cloneZarrSelection,
33
+ getCachedZarrSelection,
34
+ getZarrSelectionKey
35
+ } from './lib/zarr-data-cache';
36
+
37
+ // __VERSION__ is injected by babel-plugin-version-inline
38
+ // @ts-ignore TS2304: Cannot find name '__VERSION__'.
39
+ const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';
40
+
41
+ /** Six Rasterio/Affine coefficients `[scaleX, rotationX, translateX, rotationY, scaleY, translateY]`. */
42
+ export type GeoZarrAffineTransform = [
43
+ scaleX: number,
44
+ rotationX: number,
45
+ translateX: number,
46
+ rotationY: number,
47
+ scaleY: number,
48
+ translateY: number
49
+ ];
50
+
51
+ /** One non-spatial dimension that can be selected before reading a 2D raster window. */
52
+ export type GeoZarrSelectionDimension = {
53
+ /** Dimension name declared by Zarr or xarray. */
54
+ name: string;
55
+ /** Number of indices in this dimension. */
56
+ size: number;
57
+ /** Index used when a raster request omits this dimension. */
58
+ defaultIndex: number;
59
+ };
60
+
61
+ /** Native array geometry for one advertised spatial multiscale level. */
62
+ export type GeoZarrLevelMetadata = {
63
+ /** Advertised asset identifier, preserved verbatim. */
64
+ id: string;
65
+ /** Data-array path relative to the selected group. */
66
+ array: string;
67
+ /** Resolved array metadata; absent when this level cannot be normalized. */
68
+ metadata?: Omit<GeoZarrSourceMetadata, 'levels' | 'tileGrid'>;
69
+ };
70
+
71
+ /** Normalized metadata exposed by {@link GeoZarrRasterSource}. */
72
+ export type GeoZarrSourceMetadata = RasterSourceMetadata & {
73
+ /** Data-array path relative to the selected Zarr group. */
74
+ array: string;
75
+ /** Advertised spatial multiscales; reads still use the selected `array`. */
76
+ levels?: GeoZarrLevelMetadata[];
77
+ /** Ordered names matching the data array shape. */
78
+ dimensions: string[];
79
+ /** Logical `[y, x]` spatial dimension names. */
80
+ spatialDimensions: [y: string, x: string];
81
+ /** Selectable time, vertical, band, or other non-spatial dimensions. */
82
+ selectionDimensions: GeoZarrSelectionDimension[];
83
+ /** Normalized pixel-corner affine transform used for spatial window reads. */
84
+ transform: GeoZarrAffineTransform;
85
+ /** Registration declared by GeoZarr, or `pixel` for a transform derived from CF coordinates. */
86
+ registration: 'pixel' | 'node';
87
+ };
88
+
89
+ /** Options for {@link GeoZarrSourceLoader}. */
90
+ export type GeoZarrSourceLoaderOptions = ZarrSourceLoaderOptions & {
91
+ /** GeoZarr and CF data-variable options. */
92
+ geozarr?: {
93
+ /** Data-array path relative to `zarr.path`. */
94
+ array?: string;
95
+ /** Explicit logical `[y, x]` dimension names. */
96
+ spatialDimensions?: [y: string, x: string];
97
+ /** Explicit affine transform when the store does not provide one. */
98
+ transform?: GeoZarrAffineTransform;
99
+ /** Explicit coordinate reference system definition or identifier. */
100
+ coordinateReferenceSystem?: CRSDefinition;
101
+ /** Default indices for non-spatial dimensions such as `time` or `level`. */
102
+ defaultSelection?: Record<string, number>;
103
+ };
104
+ };
105
+
106
+ /** Parameters used to request a native-resolution spatial window from a GeoZarr array. */
107
+ export type GetGeoZarrParameters = Omit<GetRasterParameters, 'bands' | 'interleaved'>;
108
+
109
+ type GeoZarrAttributes = Record<string, unknown>;
110
+
111
+ type GeoZarrInit = {
112
+ /** Validated parent group and shared store used by sibling metadata reads. */
113
+ group: zarrita.Group<Readable>;
114
+ /** Open Zarrita data array. */
115
+ array: zarrita.Array<zarrita.DataType, Readable>;
116
+ /** Normalized source metadata. */
117
+ metadata: GeoZarrSourceMetadata;
118
+ /** Physical position of the logical x dimension. */
119
+ xDimensionIndex: number;
120
+ /** Physical position of the logical y dimension. */
121
+ yDimensionIndex: number;
122
+ };
123
+
124
+ type PixelWindow = {
125
+ /** First included column. */
126
+ columnStart: number;
127
+ /** First excluded column. */
128
+ columnStop: number;
129
+ /** First included row. */
130
+ rowStart: number;
131
+ /** First excluded row. */
132
+ rowStop: number;
133
+ };
134
+
135
+ /** Source factory for GeoZarr and regular CF/xarray Zarr raster arrays. */
136
+ export const GeoZarrSourceLoaderWithParser = {
137
+ dataType: null as unknown as GeoZarrRasterSource,
138
+ /** Runtime source type marker used by `createDataSource()` type inference. */
139
+ dataSource: null as unknown as GeoZarrRasterSource,
140
+ batchType: null as never,
141
+ name: 'GeoZarrSourceLoader',
142
+ id: 'geozarr',
143
+ module: 'scientific',
144
+ version: VERSION,
145
+ extensions: ['zarr'],
146
+ mimeTypes: [],
147
+ type: 'geozarr',
148
+ fromUrl: true,
149
+ fromBlob: false,
150
+
151
+ options: {
152
+ zarr: {
153
+ metadataPath: 'auto',
154
+ path: null,
155
+ labels: undefined!,
156
+ requireConsolidatedMetadata: true
157
+ },
158
+ geozarr: {
159
+ array: undefined!,
160
+ spatialDimensions: undefined!,
161
+ transform: undefined!,
162
+ coordinateReferenceSystem: undefined!,
163
+ defaultSelection: undefined!
164
+ }
165
+ } as GeoZarrSourceLoaderOptions,
166
+
167
+ defaultOptions: {
168
+ zarr: {
169
+ metadataPath: 'auto',
170
+ path: null,
171
+ labels: undefined!,
172
+ requireConsolidatedMetadata: true
173
+ },
174
+ geozarr: {
175
+ array: undefined!,
176
+ spatialDimensions: undefined!,
177
+ transform: undefined!,
178
+ coordinateReferenceSystem: undefined!,
179
+ defaultSelection: undefined!
180
+ }
181
+ },
182
+
183
+ testURL: (url: string): boolean => /\.zarr(?:$|[/?#])/i.test(url),
184
+ createDataSource: (
185
+ data: string,
186
+ options: GeoZarrSourceLoaderOptions,
187
+ coreApi?: CoreAPI
188
+ ): GeoZarrRasterSource => new GeoZarrRasterSource(data, options, coreApi)
189
+ } as const satisfies SourceLoader<GeoZarrRasterSource>;
190
+
191
+ /** Viewport-driven raster source for GeoZarr and regular CF/xarray Zarr data variables. */
192
+ export class GeoZarrRasterSource
193
+ extends ZarrSource
194
+ implements
195
+ RasterSource<RasterData, GetGeoZarrParameters, GeoZarrSourceMetadata>,
196
+ ScanQueryMetadataProvider
197
+ {
198
+ /** Shared source initialization request. */
199
+ private initializationPromise: Promise<GeoZarrInit> | null = null;
200
+
201
+ /** Shared metadata-only multiscale discovery request. */
202
+ private metadataPromise: Promise<GeoZarrSourceMetadata> | null = null;
203
+
204
+ /** Creates a GeoZarr raster source. */
205
+ constructor(data: string, options: GeoZarrSourceLoaderOptions, coreApi?: CoreAPI) {
206
+ super(data, options, coreApi);
207
+ }
208
+
209
+ /** Returns normalized geospatial, array, and selectable-dimension metadata. */
210
+ async getMetadata(): Promise<GeoZarrSourceMetadata> {
211
+ if (!this.metadataPromise) {
212
+ this.metadataPromise = this.loadGridMetadata().catch(error => {
213
+ this.metadataPromise = null;
214
+ throw error;
215
+ });
216
+ }
217
+ return await this.metadataPromise;
218
+ }
219
+
220
+ /** Opens sibling array metadata without selecting or decoding their samples. */
221
+ 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 levels: GeoZarrLevelMetadata[] = [];
226
+ for (const level of layout) {
227
+ if (level.array === metadata.array) {
228
+ levels.push({id: level.id, array: level.array, metadata});
229
+ continue;
230
+ }
231
+ const options = this.options as GeoZarrSourceLoaderOptions;
232
+ const source = new GeoZarrRasterSource(
233
+ this.data,
234
+ {
235
+ ...options,
236
+ geozarr: {...options.geozarr, array: level.array, transform: undefined}
237
+ },
238
+ this.hasCoreApi ? this.coreApi : undefined
239
+ );
240
+ try {
241
+ const initialization = await source.initialize(undefined, true, group);
242
+ levels.push({id: level.id, array: level.array, metadata: initialization.metadata});
243
+ } catch {
244
+ // Unsupported siblings remain advertised; never publish a complete set with missing levels.
245
+ levels.push({id: level.id, array: level.array});
246
+ }
247
+ }
248
+ const normalizedLevels = levels.length
249
+ ? levels
250
+ : [{id: metadata.array, array: metadata.array, metadata}];
251
+ const matrices = normalizedLevels.map(level => getSpatialChunkMatrix(level.id, level.metadata));
252
+ const commonCoordinateReferenceSystem =
253
+ typeof metadata.crs === 'string' &&
254
+ normalizedLevels.every(level => level.metadata?.crs === metadata.crs)
255
+ ? metadata.crs
256
+ : undefined;
257
+ return {
258
+ ...metadata,
259
+ ...(levels.length ? {levels} : {}),
260
+ tileGrid: createTileGrid(commonCoordinateReferenceSystem, matrices)
261
+ };
262
+ }
263
+
264
+ /** Discovers GeoZarr variables, spatial bounds, and selectable dimensions. */
265
+ async getQueryMetadata(options: ScanQueryMetadataOptions = {}): Promise<ScanQueryMetadata> {
266
+ if (options.signal?.aborted) throw new DOMException('The operation was aborted', 'AbortError');
267
+ const metadata = await this.getMetadata();
268
+ if (options.signal?.aborted) throw new DOMException('The operation was aborted', 'AbortError');
269
+ const fields = [{name: metadata.array, type: metadata.dtype, nullable: true, metadata: {}}];
270
+ return createScanQueryMetadata({
271
+ sourceType: 'geozarr',
272
+ queryType: 'raster',
273
+ execution: {status: 'supported', method: 'getRaster'},
274
+ name: metadata.name,
275
+ schema: {fields, metadata: {}},
276
+ capabilities: {
277
+ bounds: 'pushdown',
278
+ levelOfDetail: 'unsupported'
279
+ },
280
+ spatial: metadata.boundingBox
281
+ ? {
282
+ bounds: {minimum: metadata.boundingBox[0], maximum: metadata.boundingBox[1]},
283
+ coordinateReferenceSystems:
284
+ typeof metadata.crs === 'string' ? [metadata.crs] : undefined
285
+ }
286
+ : undefined
287
+ });
288
+ }
289
+
290
+ /** Loads a clipped native-resolution 2D window for the requested viewport and named selection. */
291
+ async getRaster(parameters: GetGeoZarrParameters): Promise<RasterData> {
292
+ const initialization = await this.getInitializationPromise(parameters.signal);
293
+ const {array, metadata, xDimensionIndex, yDimensionIndex} = initialization;
294
+ const requestedBoundingBox = getRasterViewportBoundingBox(parameters.viewport);
295
+ const viewportCoordinateReferenceSystem = parameters.viewport.crs;
296
+
297
+ if (
298
+ metadata.crs &&
299
+ viewportCoordinateReferenceSystem &&
300
+ metadata.crs !== viewportCoordinateReferenceSystem
301
+ ) {
302
+ throw new Error(
303
+ `GeoZarrRasterSource does not support reprojection. Requested ${viewportCoordinateReferenceSystem}, source ${metadata.crs}.`
304
+ );
305
+ }
306
+ if (parameters.resampleMethod === 'bilinear') {
307
+ throw new Error(
308
+ 'GeoZarrRasterSource currently supports native nearest-neighbor windows only.'
309
+ );
310
+ }
311
+
312
+ const clippedBoundingBox = intersectBoundingBoxes(requestedBoundingBox, metadata.boundingBox);
313
+ if (!clippedBoundingBox) {
314
+ return createEmptyRaster(metadata, requestedBoundingBox);
315
+ }
316
+
317
+ const pixelWindow = getPixelWindow(clippedBoundingBox, metadata);
318
+ if (
319
+ pixelWindow.columnStart === pixelWindow.columnStop ||
320
+ pixelWindow.rowStart === pixelWindow.rowStop
321
+ ) {
322
+ return createEmptyRaster(metadata, clippedBoundingBox);
323
+ }
324
+
325
+ const selection = normalizeSelection(parameters.selection, metadata.selectionDimensions);
326
+ const zarritaSelection = metadata.dimensions.map((dimensionName, dimensionIndex) => {
327
+ if (dimensionIndex === xDimensionIndex) {
328
+ return zarrita.slice(pixelWindow.columnStart, pixelWindow.columnStop);
329
+ }
330
+ if (dimensionIndex === yDimensionIndex) {
331
+ return zarrita.slice(pixelWindow.rowStart, pixelWindow.rowStop);
332
+ }
333
+ return selection[dimensionName];
334
+ });
335
+ const chunk = await getCachedZarrSelection(
336
+ array,
337
+ getZarrSelectionKey(zarritaSelection),
338
+ () =>
339
+ zarrita.get(array, zarritaSelection) as Promise<{
340
+ data: SupportedTypedArray;
341
+ shape: number[];
342
+ }>,
343
+ parameters.signal
344
+ );
345
+ if (!chunk || typeof chunk !== 'object' || !('data' in chunk) || !('shape' in chunk)) {
346
+ throw new Error('Failed to read GeoZarr raster selection.');
347
+ }
348
+
349
+ const width = pixelWindow.columnStop - pixelWindow.columnStart;
350
+ const height = pixelWindow.rowStop - pixelWindow.rowStart;
351
+ const typedData = cloneZarrSelection(chunk).data as SupportedTypedArray;
352
+ const data =
353
+ xDimensionIndex < yDimensionIndex ? transposeRaster(typedData, width, height) : typedData;
354
+ const outputBoundingBox = getPixelWindowBoundingBox(pixelWindow, metadata.transform);
355
+
356
+ return {
357
+ data,
358
+ width,
359
+ height,
360
+ bandCount: 1,
361
+ dtype: metadata.dtype,
362
+ interleaved: false,
363
+ noData: metadata.noData,
364
+ boundingBox: outputBoundingBox,
365
+ crs: metadata.crs,
366
+ metadata: {
367
+ ...metadata.metadata,
368
+ array: metadata.array,
369
+ dimensions: metadata.dimensions,
370
+ selection,
371
+ pixelWindow
372
+ }
373
+ };
374
+ }
375
+
376
+ /** Returns the shared initialization request for this source. */
377
+ private async getInitializationPromise(signal?: AbortSignal): Promise<GeoZarrInit> {
378
+ if (!this.initializationPromise) {
379
+ this.initializationPromise = this.initialize(signal);
380
+ }
381
+
382
+ const initializationPromise = this.initializationPromise;
383
+ try {
384
+ return await initializationPromise;
385
+ } catch (error) {
386
+ if (this.initializationPromise === initializationPromise) {
387
+ this.initializationPromise = null;
388
+ }
389
+ throw error;
390
+ }
391
+ }
392
+
393
+ /** Opens the selected data array and resolves GeoZarr or CF/xarray geospatial metadata. */
394
+ private async initialize(
395
+ signal?: AbortSignal,
396
+ metadataOnly = false,
397
+ validatedGroup?: zarrita.Group<Readable>
398
+ ): Promise<GeoZarrInit> {
399
+ const group = validatedGroup || await this.openGroup(signal);
400
+ const options = (this.options as GeoZarrSourceLoaderOptions).geozarr;
401
+ const arrayPath = options?.array;
402
+ if (!arrayPath) {
403
+ throw new Error('GeoZarrRasterSource requires a geozarr.array data-variable path.');
404
+ }
405
+
406
+ const array = await zarrita.open(group.resolve(arrayPath), {kind: 'array', signal});
407
+ const groupAttributes = normalizeAttributes(group.attrs);
408
+ 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
+ : {};
416
+ const attributes = {
417
+ ...groupAttributes,
418
+ ...levelGroupAttributes,
419
+ ...level?.attributes,
420
+ ...arrayAttributes
421
+ };
422
+ const coordinateReferenceSystemKeys = ['proj:code', 'proj:wkt2', 'proj:projjson', 'proj:epsg'];
423
+ const coordinateReferenceSystemAttributes = [
424
+ arrayAttributes, level?.attributes, levelGroupAttributes
425
+ ].find(candidate => candidate &&
426
+ coordinateReferenceSystemKeys.some(key => Object.hasOwn(candidate, key)));
427
+ if (coordinateReferenceSystemAttributes) {
428
+ for (const key of coordinateReferenceSystemKeys) {
429
+ delete attributes[key];
430
+ if (Object.hasOwn(coordinateReferenceSystemAttributes, key)) {
431
+ attributes[key] = coordinateReferenceSystemAttributes[key];
432
+ }
433
+ }
434
+ }
435
+ if (level) {
436
+ // A root affine does not establish the geometry of each differently sampled child.
437
+ attributes['spatial:transform'] =
438
+ arrayAttributes['spatial:transform'] ??
439
+ level.attributes['spatial:transform'] ??
440
+ levelGroupAttributes['spatial:transform'];
441
+ }
442
+ const dimensions = getDimensionNames(array, attributes);
443
+ const spatialDimensions = getSpatialDimensions(
444
+ dimensions,
445
+ attributes,
446
+ options?.spatialDimensions
447
+ );
448
+ const yDimensionIndex = dimensions.indexOf(spatialDimensions[0]);
449
+ const xDimensionIndex = dimensions.indexOf(spatialDimensions[1]);
450
+ const width = array.shape[xDimensionIndex];
451
+ const height = array.shape[yDimensionIndex];
452
+ const coordinateTransform =
453
+ options?.transform ||
454
+ normalizeAffineTransform(attributes['spatial:transform']) ||
455
+ (!metadataOnly ? await loadCFCoordinateTransform(group, spatialDimensions, signal) : null);
456
+ if (!coordinateTransform) {
457
+ throw new Error(
458
+ 'GeoZarrRasterSource requires spatial:transform metadata, explicit geozarr.transform, or regular 1D CF coordinate arrays.'
459
+ );
460
+ }
461
+
462
+ const declaredRegistration = normalizeRegistration(attributes['spatial:registration']);
463
+ const transform =
464
+ declaredRegistration === 'node'
465
+ ? convertNodeTransformToPixelTransform(coordinateTransform)
466
+ : coordinateTransform;
467
+ const declaredBoundingBox = normalizeBoundingBox(attributes['spatial:bbox']);
468
+ const boundingBox =
469
+ declaredRegistration === 'pixel' && declaredBoundingBox
470
+ ? toRasterBoundingBox(declaredBoundingBox)
471
+ : getTransformBoundingBox(transform, width, height);
472
+ const coordinateReferenceSystem =
473
+ options?.coordinateReferenceSystem ||
474
+ normalizeDeclaredCoordinateReferenceSystem(attributes) ||
475
+ await loadCFCoordinateReferenceSystem(group, attributes, spatialDimensions, signal);
476
+ const defaultSelection = options?.defaultSelection || {};
477
+ const selectionDimensions = dimensions
478
+ .map((dimensionName, dimensionIndex) => ({
479
+ name: dimensionName,
480
+ size: array.shape[dimensionIndex],
481
+ defaultIndex: defaultSelection[dimensionName] ?? 0
482
+ }))
483
+ .filter(dimension => !spatialDimensions.includes(dimension.name));
484
+ normalizeSelection(undefined, selectionDimensions);
485
+ const dtype = normalizeDtype(array.dtype);
486
+ const noData =
487
+ normalizeNumber(attributes._FillValue) ?? normalizeNumber(attributes.missing_value);
488
+ const metadata: GeoZarrSourceMetadata = {
489
+ name: normalizeString(attributes.long_name) || normalizeString(attributes.title) || arrayPath,
490
+ title: normalizeString(attributes.title) || normalizeString(groupAttributes.title),
491
+ abstract:
492
+ normalizeString(attributes.description) || normalizeString(groupAttributes.description),
493
+ keywords: normalizeStringArray(groupAttributes.keywords),
494
+ attributions: this.options.core?.attributions || [],
495
+ crs: coordinateReferenceSystem,
496
+ boundingBox,
497
+ width,
498
+ height,
499
+ bandCount: 1,
500
+ dtype,
501
+ tileSize: {
502
+ width: array.chunks[xDimensionIndex],
503
+ height: array.chunks[yDimensionIndex]
504
+ },
505
+ noData,
506
+ metadata: {
507
+ groupAttributes,
508
+ arrayAttributes,
509
+ sourceTransform: coordinateTransform,
510
+ sourceBoundingBox: declaredBoundingBox
511
+ },
512
+ array: arrayPath,
513
+ dimensions,
514
+ spatialDimensions,
515
+ selectionDimensions,
516
+ transform,
517
+ registration: declaredRegistration
518
+ };
519
+
520
+ return {group, array, metadata, xDimensionIndex, yDimensionIndex};
521
+ }
522
+ }
523
+
524
+ /** Converts arbitrary Zarrita attributes into a plain object. */
525
+ function normalizeAttributes(attributes: unknown): GeoZarrAttributes {
526
+ return attributes && typeof attributes === 'object' ? (attributes as GeoZarrAttributes) : {};
527
+ }
528
+
529
+ /** Resolves array dimension names from Zarr v3 or xarray's Zarr v2 convention. */
530
+ function getDimensionNames(
531
+ array: zarrita.Array<zarrita.DataType, Readable>,
532
+ attributes: GeoZarrAttributes
533
+ ): string[] {
534
+ const dimensions = array.dimensionNames?.length
535
+ ? [...array.dimensionNames]
536
+ : normalizeStringArray(attributes._ARRAY_DIMENSIONS);
537
+
538
+ if (
539
+ !dimensions ||
540
+ dimensions.length !== array.shape.length ||
541
+ new Set(dimensions).size !== dimensions.length
542
+ ) {
543
+ throw new Error(
544
+ 'GeoZarrRasterSource requires unique Zarr dimension_names or xarray _ARRAY_DIMENSIONS matching the array shape.'
545
+ );
546
+ }
547
+ return dimensions;
548
+ }
549
+
550
+ /** Resolves logical y/x dimensions from options, GeoZarr metadata, or common CF names. */
551
+ function getSpatialDimensions(
552
+ dimensions: string[],
553
+ attributes: GeoZarrAttributes,
554
+ optionDimensions?: [y: string, x: string]
555
+ ): [y: string, x: string] {
556
+ const declaredDimensions =
557
+ optionDimensions || normalizeSpatialDimensions(attributes['spatial:dimensions']);
558
+ const spatialDimensions = declaredDimensions || [
559
+ findDimension(dimensions, ['y', 'lat', 'latitude']),
560
+ findDimension(dimensions, ['x', 'lon', 'longitude'])
561
+ ];
562
+
563
+ if (
564
+ spatialDimensions.length !== 2 ||
565
+ !spatialDimensions[0] ||
566
+ !spatialDimensions[1] ||
567
+ !dimensions.includes(spatialDimensions[0]) ||
568
+ !dimensions.includes(spatialDimensions[1]) ||
569
+ spatialDimensions[0] === spatialDimensions[1]
570
+ ) {
571
+ throw new Error(
572
+ 'GeoZarrRasterSource could not resolve two spatial dimensions. Set spatial:dimensions or geozarr.spatialDimensions.'
573
+ );
574
+ }
575
+
576
+ return spatialDimensions as [string, string];
577
+ }
578
+
579
+ /** Finds the first dimension whose case-insensitive name matches a candidate. */
580
+ function findDimension(dimensions: string[], candidates: string[]): string {
581
+ return dimensions.find(dimension => candidates.includes(dimension.toLowerCase())) || '';
582
+ }
583
+
584
+ /** Normalizes a two-string logical spatial-dimension tuple. */
585
+ function normalizeSpatialDimensions(value: unknown): [y: string, x: string] | null {
586
+ return Array.isArray(value) && value.length === 2 && value.every(item => typeof item === 'string')
587
+ ? [value[0], value[1]]
588
+ : null;
589
+ }
590
+
591
+ /** Normalizes a six-number affine transform tuple. */
592
+ function normalizeAffineTransform(value: unknown): GeoZarrAffineTransform | null {
593
+ return Array.isArray(value) && value.length === 6 && value.every(Number.isFinite)
594
+ ? (value as GeoZarrAffineTransform)
595
+ : null;
596
+ }
597
+
598
+ /** Normalizes a flat four-number bounding box. */
599
+ function normalizeBoundingBox(value: unknown): [number, number, number, number] | null {
600
+ return Array.isArray(value) && value.length === 4 && value.every(Number.isFinite)
601
+ ? (value as [number, number, number, number])
602
+ : null;
603
+ }
604
+
605
+ /** Converts a flat `[minimumX, minimumY, maximumX, maximumY]` box to RasterSource form. */
606
+ function toRasterBoundingBox(boundingBox: [number, number, number, number]): RasterBoundingBox {
607
+ return [
608
+ [boundingBox[0], boundingBox[1]],
609
+ [boundingBox[2], boundingBox[3]]
610
+ ];
611
+ }
612
+
613
+ /** Normalizes GeoZarr grid registration. */
614
+ function normalizeRegistration(value: unknown): 'pixel' | 'node' {
615
+ return value === 'node' ? 'node' : 'pixel';
616
+ }
617
+
618
+ /** Converts a node-centered GeoZarr transform to the pixel-corner transform used by RasterSource. */
619
+ function convertNodeTransformToPixelTransform(
620
+ transform: GeoZarrAffineTransform
621
+ ): GeoZarrAffineTransform {
622
+ const [scaleX, rotationX, translateX, rotationY, scaleY, translateY] = transform;
623
+ return [
624
+ scaleX,
625
+ rotationX,
626
+ translateX - (scaleX + rotationX) / 2,
627
+ rotationY,
628
+ scaleY,
629
+ translateY - (rotationY + scaleY) / 2
630
+ ];
631
+ }
632
+
633
+ /** Loads regular one-dimensional CF coordinate variables and derives a pixel-corner transform. */
634
+ async function loadCFCoordinateTransform(
635
+ group: zarrita.Group<Readable>,
636
+ spatialDimensions: [y: string, x: string],
637
+ signal?: AbortSignal
638
+ ): Promise<GeoZarrAffineTransform | null> {
639
+ try {
640
+ const [yCoordinates, xCoordinates] = await Promise.all([
641
+ loadCoordinateValues(group, spatialDimensions[0], signal),
642
+ loadCoordinateValues(group, spatialDimensions[1], signal)
643
+ ]);
644
+ const scaleX = getRegularCoordinateSpacing(xCoordinates, spatialDimensions[1]);
645
+ const scaleY = getRegularCoordinateSpacing(yCoordinates, spatialDimensions[0]);
646
+ return [scaleX, 0, xCoordinates[0] - scaleX / 2, 0, scaleY, yCoordinates[0] - scaleY / 2];
647
+ } catch {
648
+ return null;
649
+ }
650
+ }
651
+
652
+ /** Loads all values from one one-dimensional coordinate variable. */
653
+ async function loadCoordinateValues(
654
+ group: zarrita.Group<Readable>,
655
+ coordinateName: string,
656
+ signal?: AbortSignal
657
+ ): Promise<number[]> {
658
+ const coordinateArray = await zarrita.open(group.resolve(coordinateName), {
659
+ kind: 'array',
660
+ signal
661
+ });
662
+ if (coordinateArray.shape.length !== 1 || coordinateArray.shape[0] < 2) {
663
+ throw new Error(
664
+ `Coordinate ${coordinateName} must be a one-dimensional array with at least two values.`
665
+ );
666
+ }
667
+ const coordinateChunk = await zarrita.get(coordinateArray, [null], {signal});
668
+ if (!coordinateChunk || typeof coordinateChunk !== 'object' || !('data' in coordinateChunk)) {
669
+ throw new Error(`Could not read coordinate ${coordinateName}.`);
670
+ }
671
+ return Array.from(coordinateChunk.data as ArrayLike<number>);
672
+ }
673
+
674
+ /** Validates that coordinate values are finite and regularly spaced. */
675
+ function getRegularCoordinateSpacing(coordinates: number[], coordinateName: string): number {
676
+ const spacing = (coordinates.at(-1)! - coordinates[0]) / (coordinates.length - 1);
677
+ if (!Number.isFinite(spacing) || spacing === 0) {
678
+ throw new Error(`Coordinate ${coordinateName} does not have finite non-zero spacing.`);
679
+ }
680
+
681
+ const tolerance = Math.max(Math.abs(spacing) * 1e-6, Number.EPSILON);
682
+ for (let index = 0; index < coordinates.length; index++) {
683
+ const expectedCoordinate = coordinates[0] + spacing * index;
684
+ if (
685
+ !Number.isFinite(coordinates[index]) ||
686
+ Math.abs(coordinates[index] - expectedCoordinate) > tolerance
687
+ ) {
688
+ throw new Error(`Coordinate ${coordinateName} is not regularly spaced.`);
689
+ }
690
+ }
691
+ return spacing;
692
+ }
693
+
694
+ /** Resolves CRS metadata from a CF grid-mapping variable or longitude/latitude dimensions. */
695
+ async function loadCFCoordinateReferenceSystem(
696
+ group: zarrita.Group<Readable>,
697
+ attributes: GeoZarrAttributes,
698
+ spatialDimensions: [y: string, x: string],
699
+ signal?: AbortSignal
700
+ ): Promise<string | undefined> {
701
+ 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
+ }
721
+ }
722
+
723
+ const normalizedDimensions = spatialDimensions.map(dimension => dimension.toLowerCase());
724
+ if (
725
+ ['lat', 'latitude'].includes(normalizedDimensions[0]) &&
726
+ ['lon', 'longitude'].includes(normalizedDimensions[1])
727
+ ) {
728
+ return 'EPSG:4326';
729
+ }
730
+ return undefined;
731
+ }
732
+
733
+ /** Computes a bounding box from all four transformed raster corners. */
734
+ function getTransformBoundingBox(
735
+ transform: GeoZarrAffineTransform,
736
+ width: number,
737
+ height: number
738
+ ): RasterBoundingBox {
739
+ const corners = [
740
+ transformPosition(transform, 0, 0),
741
+ transformPosition(transform, width, 0),
742
+ transformPosition(transform, 0, height),
743
+ transformPosition(transform, width, height)
744
+ ];
745
+ const xCoordinates = corners.map(position => position[0]);
746
+ const yCoordinates = corners.map(position => position[1]);
747
+ return [
748
+ [Math.min(...xCoordinates), Math.min(...yCoordinates)],
749
+ [Math.max(...xCoordinates), Math.max(...yCoordinates)]
750
+ ];
751
+ }
752
+
753
+ /** Applies an affine transform to one column/row position. */
754
+ function transformPosition(
755
+ transform: GeoZarrAffineTransform,
756
+ column: number,
757
+ row: number
758
+ ): [x: number, y: number] {
759
+ const [scaleX, rotationX, translateX, rotationY, scaleY, translateY] = transform;
760
+ return [
761
+ scaleX * column + rotationX * row + translateX,
762
+ rotationY * column + scaleY * row + translateY
763
+ ];
764
+ }
765
+
766
+ /** Intersects two source-coordinate bounding boxes. */
767
+ function intersectBoundingBoxes(
768
+ leftBoundingBox: RasterBoundingBox,
769
+ rightBoundingBox?: RasterBoundingBox
770
+ ): RasterBoundingBox | null {
771
+ if (!rightBoundingBox) {
772
+ return null;
773
+ }
774
+ const minimumX = Math.max(leftBoundingBox[0][0], rightBoundingBox[0][0]);
775
+ const minimumY = Math.max(leftBoundingBox[0][1], rightBoundingBox[0][1]);
776
+ const maximumX = Math.min(leftBoundingBox[1][0], rightBoundingBox[1][0]);
777
+ const maximumY = Math.min(leftBoundingBox[1][1], rightBoundingBox[1][1]);
778
+ return maximumX > minimumX && maximumY > minimumY
779
+ ? [
780
+ [minimumX, minimumY],
781
+ [maximumX, maximumY]
782
+ ]
783
+ : null;
784
+ }
785
+
786
+ /** Converts an axis-aligned source bounding box into a clipped integer pixel window. */
787
+ function getPixelWindow(
788
+ boundingBox: RasterBoundingBox,
789
+ metadata: GeoZarrSourceMetadata
790
+ ): PixelWindow {
791
+ const [scaleX, rotationX, translateX, rotationY, scaleY, translateY] = metadata.transform;
792
+ if (rotationX !== 0 || rotationY !== 0) {
793
+ throw new Error('GeoZarrRasterSource does not yet support rotated affine window reads.');
794
+ }
795
+
796
+ const columnCoordinates = [
797
+ (boundingBox[0][0] - translateX) / scaleX,
798
+ (boundingBox[1][0] - translateX) / scaleX
799
+ ];
800
+ const rowCoordinates = [
801
+ (boundingBox[0][1] - translateY) / scaleY,
802
+ (boundingBox[1][1] - translateY) / scaleY
803
+ ];
804
+ return {
805
+ columnStart: clamp(Math.floor(Math.min(...columnCoordinates)), 0, metadata.width),
806
+ columnStop: clamp(Math.ceil(Math.max(...columnCoordinates)), 0, metadata.width),
807
+ rowStart: clamp(Math.floor(Math.min(...rowCoordinates)), 0, metadata.height),
808
+ rowStop: clamp(Math.ceil(Math.max(...rowCoordinates)), 0, metadata.height)
809
+ };
810
+ }
811
+
812
+ /** Computes exact source bounds for an integer pixel window. */
813
+ function getPixelWindowBoundingBox(
814
+ pixelWindow: PixelWindow,
815
+ transform: GeoZarrAffineTransform
816
+ ): RasterBoundingBox {
817
+ return getTransformBoundingBox(
818
+ [
819
+ transform[0],
820
+ transform[1],
821
+ transformPosition(transform, pixelWindow.columnStart, pixelWindow.rowStart)[0],
822
+ transform[3],
823
+ transform[4],
824
+ transformPosition(transform, pixelWindow.columnStart, pixelWindow.rowStart)[1]
825
+ ],
826
+ pixelWindow.columnStop - pixelWindow.columnStart,
827
+ pixelWindow.rowStop - pixelWindow.rowStart
828
+ );
829
+ }
830
+
831
+ /** Normalizes and validates indices for all non-spatial dimensions. */
832
+ function normalizeSelection(
833
+ requestedSelection: Record<string, number> | undefined,
834
+ dimensions: GeoZarrSelectionDimension[]
835
+ ): Record<string, number> {
836
+ const knownDimensions = new Set(dimensions.map(dimension => dimension.name));
837
+ for (const requestedDimension of Object.keys(requestedSelection || {})) {
838
+ if (!knownDimensions.has(requestedDimension)) {
839
+ throw new Error(`Unknown GeoZarr selection dimension ${requestedDimension}.`);
840
+ }
841
+ }
842
+
843
+ return Object.fromEntries(
844
+ dimensions.map(dimension => {
845
+ const index = requestedSelection?.[dimension.name] ?? dimension.defaultIndex;
846
+ if (!Number.isInteger(index) || index < 0 || index >= dimension.size) {
847
+ throw new Error(
848
+ `GeoZarr ${dimension.name} index ${index} is out of bounds for dimension size ${dimension.size}.`
849
+ );
850
+ }
851
+ return [dimension.name, index];
852
+ })
853
+ );
854
+ }
855
+
856
+ /** Transposes a C-order 2D raster whose physical dimensions are `[x, y]`. */
857
+ function transposeRaster(
858
+ source: SupportedTypedArray,
859
+ width: number,
860
+ height: number
861
+ ): SupportedTypedArray {
862
+ const TypedArrayConstructor = source.constructor as new (length: number) => SupportedTypedArray;
863
+ const target = new TypedArrayConstructor(source.length);
864
+ for (let row = 0; row < height; row++) {
865
+ for (let column = 0; column < width; column++) {
866
+ target[row * width + column] = source[column * height + row];
867
+ }
868
+ }
869
+ return target;
870
+ }
871
+
872
+ /** Creates a zero-sized raster for a viewport outside the source extent. */
873
+ function createEmptyRaster(
874
+ metadata: GeoZarrSourceMetadata,
875
+ boundingBox: RasterBoundingBox
876
+ ): RasterData {
877
+ const TypedArrayConstructor = getTypedArrayConstructor(metadata.dtype);
878
+ return {
879
+ data: new TypedArrayConstructor(0),
880
+ width: 0,
881
+ height: 0,
882
+ bandCount: 1,
883
+ dtype: metadata.dtype,
884
+ interleaved: false,
885
+ noData: metadata.noData,
886
+ boundingBox,
887
+ crs: metadata.crs,
888
+ metadata: metadata.metadata
889
+ };
890
+ }
891
+
892
+ /** Converts a Zarrita dtype into the raster-source dtype union. */
893
+ function normalizeDtype(dtype: string): RasterChannelDataType {
894
+ switch (dtype) {
895
+ case 'uint8':
896
+ case 'uint16':
897
+ case 'uint32':
898
+ case 'int8':
899
+ case 'int16':
900
+ case 'int32':
901
+ case 'float32':
902
+ case 'float64':
903
+ return dtype;
904
+ default:
905
+ throw new Error(`GeoZarr dtype ${dtype} is not currently supported.`);
906
+ }
907
+ }
908
+
909
+ /** Returns the typed-array constructor represented by a raster dtype. */
910
+ function getTypedArrayConstructor(
911
+ dtype: RasterChannelDataType
912
+ ): new (
913
+ length: number
914
+ ) => SupportedTypedArray {
915
+ switch (dtype) {
916
+ case 'uint8':
917
+ return Uint8Array;
918
+ case 'uint16':
919
+ return Uint16Array;
920
+ case 'uint32':
921
+ return Uint32Array;
922
+ case 'int8':
923
+ return Int8Array;
924
+ case 'int16':
925
+ return Int16Array;
926
+ case 'int32':
927
+ return Int32Array;
928
+ case 'float32':
929
+ return Float32Array;
930
+ case 'float64':
931
+ return Float64Array;
932
+ default:
933
+ throw new Error(`Unsupported GeoZarr dtype ${dtype}.`);
934
+ }
935
+ }
936
+
937
+ /** Returns a finite number or `undefined`. */
938
+ function normalizeNumber(value: unknown): number | undefined {
939
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
940
+ }
941
+
942
+ /** Returns a non-empty string or `undefined`. */
943
+ function normalizeString(value: unknown): string | undefined {
944
+ return typeof value === 'string' && value.length ? value : undefined;
945
+ }
946
+
947
+ /** Returns a string array or `undefined`. */
948
+ function normalizeStringArray(value: unknown): string[] | undefined {
949
+ return Array.isArray(value) && value.every(item => typeof item === 'string')
950
+ ? [...value]
951
+ : undefined;
952
+ }
953
+
954
+ /** Clamps a number to an inclusive range. */
955
+ function clamp(value: number, minimum: number, maximum: number): number {
956
+ return Math.min(maximum, Math.max(minimum, value));
957
+ }
958
+
959
+ /** Describes spatial storage chunks only when the affine is axis aligned and rightward. */
960
+ function getSpatialChunkMatrix(
961
+ id: string,
962
+ metadata?: Omit<GeoZarrSourceMetadata, 'levels' | 'tileGrid'>
963
+ ): TileGridMatrix {
964
+ if (!metadata) return {id};
965
+ const {transform, tileSize, width, height} = metadata;
966
+ const [scaleX, rotationX, translateX, rotationY, scaleY, translateY] = transform;
967
+ if (
968
+ rotationX !== 0 || rotationY !== 0 || scaleX <= 0 || scaleY === 0 ||
969
+ !transform.every(Number.isFinite) || !tileSize || !width || !height
970
+ ) {
971
+ return {id};
972
+ }
973
+ return {
974
+ id,
975
+ resolution: scaleX,
976
+ resolutionY: Math.abs(scaleY),
977
+ origin: [translateX, translateY],
978
+ cornerOfOrigin: scaleY < 0 ? 'topLeft' : 'bottomLeft',
979
+ tileSize: [tileSize.width, tileSize.height],
980
+ matrixSize: [Math.ceil(width / tileSize.width), Math.ceil(height / tileSize.height)]
981
+ };
982
+ }
983
+
984
+ /** Retains declared CRS definitions without resolving them, and normalizes numeric EPSG identifiers. */
985
+ function normalizeDeclaredCoordinateReferenceSystem(
986
+ attributes: GeoZarrAttributes
987
+ ): CRSDefinition | undefined {
988
+ const wellKnownText = normalizeString(attributes['proj:wkt2']);
989
+ if (wellKnownText) return wellKnownText;
990
+ const code = normalizeString(attributes['proj:code']);
991
+ if (code) return code;
992
+ const epsg = attributes['proj:epsg'];
993
+ if (typeof epsg === 'number' && Number.isSafeInteger(epsg) && epsg > 0) return `EPSG:${epsg}`;
994
+ const projection = attributes['proj:projjson'];
995
+ return projection && typeof projection === 'object' && !Array.isArray(projection)
996
+ ? projection as CRSDefinition
997
+ : undefined;
998
+ }