simon-donike commited on
Commit
b293748
·
verified ·
1 Parent(s): a773ea3

Add files using upload-large-folder tool

Browse files
Files changed (45) hide show
  1. LICENSE +110 -4
  2. README.md +227 -7
  3. argo/argo_profiles_on_grid.zarr/.zmetadata +1 -1
  4. argo/argo_profiles_on_grid.zarr/source_profile_idx/1 +0 -0
  5. argo/argo_profiles_on_grid.zarr/source_profile_idx/101 +0 -0
  6. argo/argo_profiles_on_grid.zarr/source_profile_idx/108 +0 -0
  7. argo/argo_profiles_on_grid.zarr/source_profile_idx/110 +0 -0
  8. argo/argo_profiles_on_grid.zarr/source_profile_idx/12 +0 -0
  9. argo/argo_profiles_on_grid.zarr/source_profile_idx/129 +0 -0
  10. argo/argo_profiles_on_grid.zarr/source_profile_idx/158 +0 -0
  11. argo/argo_profiles_on_grid.zarr/source_profile_idx/162 +0 -0
  12. argo/argo_profiles_on_grid.zarr/source_profile_idx/167 +0 -0
  13. argo/argo_profiles_on_grid.zarr/source_profile_idx/177 +0 -0
  14. argo/argo_profiles_on_grid.zarr/source_profile_idx/18 +0 -0
  15. argo/argo_profiles_on_grid.zarr/source_profile_idx/186 +0 -0
  16. argo/argo_profiles_on_grid.zarr/source_profile_idx/189 +0 -0
  17. argo/argo_profiles_on_grid.zarr/source_profile_idx/2 +0 -0
  18. argo/argo_profiles_on_grid.zarr/source_profile_idx/23 +0 -0
  19. argo/argo_profiles_on_grid.zarr/source_profile_idx/30 +0 -0
  20. argo/argo_profiles_on_grid.zarr/source_profile_idx/31 +0 -0
  21. argo/argo_profiles_on_grid.zarr/source_profile_idx/37 +0 -0
  22. argo/argo_profiles_on_grid.zarr/source_profile_idx/42 +0 -0
  23. argo/argo_profiles_on_grid.zarr/source_profile_idx/5 +0 -0
  24. argo/argo_profiles_on_grid.zarr/source_profile_idx/50 +0 -0
  25. argo/argo_profiles_on_grid.zarr/source_profile_idx/51 +0 -0
  26. argo/argo_profiles_on_grid.zarr/source_profile_idx/62 +0 -0
  27. argo/argo_profiles_on_grid.zarr/source_profile_idx/64 +0 -0
  28. argo/argo_profiles_on_grid.zarr/source_profile_idx/7 +0 -0
  29. argo/argo_profiles_on_grid.zarr/source_profile_idx/71 +0 -0
  30. argo/argo_profiles_on_grid.zarr/source_profile_idx/77 +0 -0
  31. argo/argo_profiles_on_grid.zarr/source_profile_idx/84 +0 -0
  32. argo/argo_profiles_on_grid.zarr/source_profile_idx/91 +0 -0
  33. argo/argo_profiles_on_grid.zarr/source_profile_idx/92 +0 -0
  34. argo/argo_profiles_on_grid.zarr/source_profile_idx/93 +0 -0
  35. depthdif_dataset/__init__.py +28 -0
  36. depthdif_dataset/dataloaders.py +159 -0
  37. depthdif_dataset/dataset.py +1781 -0
  38. depthdif_dataset/grid_utils.py +443 -0
  39. depthdif_dataset/normalizations.py +119 -0
  40. examples/torch_dataloader.py +86 -0
  41. manifest.yaml +0 -0
  42. metadata/citation.cff +1 -1
  43. metadata/dataset_description.json +83 -80
  44. metadata/stac-item.json +8 -5
  45. requirements-loader.txt +9 -0
LICENSE CHANGED
@@ -1,5 +1,111 @@
1
- This package aggregates collocated oceanographic data derived from upstream public products.
 
2
 
3
- Use is subject to the terms and citation requirements of the upstream EN4/ARGO,
4
- GLORYS, OSTIA, sea-level, and sea-surface-salinity products. This file is a
5
- dataset license notice, not a replacement for upstream product licenses.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DepthDif GeoTIFF Raster and Aligned ARGO Dataset
2
+ Dataset license notice
3
 
4
+ SPDX-License-Identifier: CC-BY-4.0
5
+
6
+ This dataset package is released by the DepthDif contributors under the
7
+ Creative Commons Attribution 4.0 International license (CC BY 4.0).
8
+
9
+ You may share and adapt this dataset package, including for commercial use,
10
+ provided that you give appropriate credit, provide a link to the license, and
11
+ indicate whether changes were made. The full license text is available at:
12
+ https://creativecommons.org/licenses/by/4.0/legalcode
13
+
14
+ Suggested citation for this package:
15
+ DepthDif contributors. DepthDif GeoTIFF Raster and Aligned ARGO Dataset.
16
+ Hugging Face dataset repository, 2026.
17
+
18
+ Please cite or acknowledge DepthDif together with the upstream data products
19
+ that are relevant to your use. This package contains transformed, collocated,
20
+ and rasterized products derived from public oceanographic data sources. It does
21
+ not replace the licenses, terms of use, or citation requirements attached to
22
+ those upstream products. Where an upstream provider applies additional terms,
23
+ those provider terms continue to apply to the corresponding source-derived
24
+ content.
25
+
26
+ Source-provider acknowledgments and citations
27
+ ============================================
28
+
29
+ Copernicus Marine Service
30
+ -------------------------
31
+ This dataset uses Copernicus Marine Service products for GLORYS ocean
32
+ reanalysis, OSTIA sea-surface temperature, gridded sea-level fields, and
33
+ multi-observation sea-surface salinity/density. When using these derived fields,
34
+ include the Copernicus Marine attribution statement:
35
+
36
+ Generated using E.U. Copernicus Marine Service Information.
37
+
38
+ Relevant Copernicus Marine products include:
39
+
40
+ - GLOBAL_MULTIYEAR_PHY_001_030, Global Ocean Physics Reanalysis / GLORYS12V1,
41
+ doi:10.48670/moi-00021.
42
+ - SST_GLO_SST_L4_REP_OBSERVATIONS_010_011, Global Ocean OSTIA Sea Surface
43
+ Temperature and Sea Ice Reprocessed, doi:10.48670/moi-00168.
44
+ - SEALEVEL_GLO_PHY_L4_MY_008_047, Global Ocean Gridded L4 Sea Surface Heights
45
+ and derived variables, doi:10.48670/moi-00148.
46
+ - MULTIOBS_GLO_PHY_S_SURFACE_MYNRT_015_013, Global Ocean Multi Observation
47
+ sea-surface salinity products, doi:10.48670/moi-00051.
48
+
49
+ Copernicus Marine license information is available from the Copernicus Marine
50
+ Service Commitments and Licence page:
51
+ https://marine.copernicus.eu/user-corner/service-commitments-and-licence
52
+
53
+ EN4 profile archive and ARGO observations
54
+ -----------------------------------------
55
+ The in-situ profile source for this package is the UK Met Office Hadley Centre
56
+ EN4.2.2 profile archive. The source files identify EN4 as distributed under the
57
+ UK Non-Commercial Government Licence and request attribution to the data
58
+ providers. Users should check the current EN4 terms before any downstream use
59
+ that depends on the profile-derived content.
60
+
61
+ Please cite the EN4 dataset paper when using the profile component:
62
+ Good, S. A., M. J. Martin, and N. A. Rayner. 2013. EN4: quality controlled
63
+ ocean temperature and salinity profiles and monthly objective analyses with
64
+ uncertainty estimates. Journal of Geophysical Research: Oceans 118, 6704-6716.
65
+ doi:10.1002/2013JC009067.
66
+
67
+ The EN4 profile archive contains Argo-origin observations. When using those
68
+ profiles, also acknowledge the International Argo Program and the national
69
+ programs that contribute to it. Argo is part of the Global Ocean Observing
70
+ System. Useful references are:
71
+
72
+ - Argo. 2000. Argo float data and metadata from Global Data Assembly Centre
73
+ (Argo GDAC). SEANOE. doi:10.17882/42182.
74
+ - Wong, A. P. S., et al. 2020. Argo Data 1999-2019: Two Million
75
+ Temperature-Salinity Profiles and Subsurface Velocity Observations From a
76
+ Global Array of Profiling Floats. Frontiers in Marine Science 7:700.
77
+ doi:10.3389/fmars.2020.00700.
78
+
79
+ More information about acknowledging Argo is available at:
80
+ https://argo.ucsd.edu/data/acknowledging-argo/
81
+
82
+ OSTIA, GHRSST, and Met Office context
83
+ -------------------------------------
84
+ The OSTIA sea-surface temperature fields are provided through Copernicus Marine
85
+ and originate from the UK Met Office OSTIA/GHRSST product stream. For work that
86
+ uses the SST context, acknowledge GHRSST, the Met Office, and Copernicus Marine
87
+ as data providers where appropriate.
88
+
89
+ A commonly cited OSTIA reference is:
90
+ Donlon, C. J., M. Martin, J. D. Stark, J. Roberts-Jones, E. Fiedler, and
91
+ W. Wimmer. 2012. The Operational Sea Surface Temperature and Sea Ice Analysis
92
+ (OSTIA) system. Remote Sensing of Environment 116, 140-158.
93
+ doi:10.1016/j.rse.2010.10.017.
94
+
95
+ Sea-level and sea-surface-salinity context
96
+ ------------------------------------------
97
+ The sea-level fields are Copernicus Marine L4 products distributed by the Sea
98
+ Level Thematic Assembly Center. The sea-surface salinity and density fields are
99
+ Copernicus Marine multi-observation products. Cite the product identifiers and
100
+ DOIs listed above when those variables are used in analysis, training, or model
101
+ outputs.
102
+
103
+ Example acknowledgement
104
+ -----------------------
105
+ This work uses the DepthDif GeoTIFF Raster and Aligned ARGO Dataset, generated
106
+ from transformed and collocated EN4/ARGO profile data, GLORYS ocean reanalysis,
107
+ OSTIA sea-surface temperature, Copernicus Marine sea-level fields, and
108
+ Copernicus Marine sea-surface-salinity products. It was generated using E.U.
109
+ Copernicus Marine Service Information. Argo-origin observations were collected
110
+ and made freely available by the International Argo Program and contributing
111
+ national programs.
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- license: other
3
  pretty_name: DepthDif GeoTIFF raster and aligned ARGO dataset
4
  tags:
5
  - oceanography
@@ -53,6 +53,10 @@ assets/
53
  figures/depthdif_schema.png
54
  data/geotiff_dataset_random100_surface.png
55
  data/argo_on_glorys_grid_3D.gif
 
 
 
 
56
  data/profile_comparison_good_alignment.png
57
  data/profile_comparison_bad_alignment.png
58
  rasters/
@@ -76,8 +80,14 @@ metadata/
76
  examples/
77
  open_with_xarray.py
78
  subset_by_region_time.py
 
 
 
 
 
79
  manifest.yaml
80
  masks/
 
81
  ```
82
 
83
  The `rasters/` directory is intentionally at the repository root. It contains
@@ -97,8 +107,8 @@ sea-surface-salinity context.
97
 
98
  All GeoTIFF rasters are exported on the GLORYS 0.1 degree global grid
99
  (`EPSG:4326`, 3600 x 1800 pixels, west-to-east longitudes from -180 to 180 and
100
- north-to-south latitudes from 90 to -90). The current package contains 761
101
- weekly target dates per raster product, from 2010-01-01 through 2024-07-26.
102
  Files are named `<variable>_YYYYMMDD.tif`.
103
 
104
  The GLORYS variables are depth-resolved 50-band GeoTIFFs:
@@ -119,6 +129,211 @@ Raster pixels are stored as `uint8` with `255` reserved for nodata. Valid codes
119
  per-file statistics, source filenames, compression, target dates, and the full
120
  depth axis are also recorded there.
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  ## ARGO Alignment Examples
123
 
124
  ARGO profiles are projected onto the fixed 50-level GLORYS depth axis before
@@ -156,9 +371,14 @@ variables = pd.read_parquet("indices/variables.parquet")
156
 
157
  Coverage:
158
 
159
- - Raster target dates: 2010-01-01 to 2024-07-26
160
- - Enriched ARGO profile dates: 2010-01-01 to 2024-07-31
 
 
 
161
  - GLORYS depth levels: 50
162
 
163
- Upstream product licenses and citation requirements for EN4/ARGO, GLORYS,
164
- OSTIA, sea-level, and sea-surface-salinity products still apply.
 
 
 
1
  ---
2
+ license: cc-by-4.0
3
  pretty_name: DepthDif GeoTIFF raster and aligned ARGO dataset
4
  tags:
5
  - oceanography
 
53
  figures/depthdif_schema.png
54
  data/geotiff_dataset_random100_surface.png
55
  data/argo_on_glorys_grid_3D.gif
56
+ data/argo_valid_pixels_per_patch.webp
57
+ data/patch_grid/patch_grid_global_overview.webp
58
+ data/patch_grid/patch_overlap_regional_example.webp
59
+ data/patch_grid/land_fraction_filter_examples.webp
60
  data/profile_comparison_good_alignment.png
61
  data/profile_comparison_bad_alignment.png
62
  rasters/
 
80
  examples/
81
  open_with_xarray.py
82
  subset_by_region_time.py
83
+ torch_dataloader.py
84
+ depthdif_dataset/
85
+ dataset.py
86
+ dataloaders.py
87
+ normalizations.py
88
  manifest.yaml
89
  masks/
90
+ requirements-loader.txt
91
  ```
92
 
93
  The `rasters/` directory is intentionally at the repository root. It contains
 
107
 
108
  All GeoTIFF rasters are exported on the GLORYS 0.1 degree global grid
109
  (`EPSG:4326`, 3600 x 1800 pixels, west-to-east longitudes from -180 to 180 and
110
+ north-to-south latitudes from 90 to -90). The current package contains 1283
111
+ weekly target dates per raster product, from 2000-01-01 through 2024-07-26.
112
  Files are named `<variable>_YYYYMMDD.tif`.
113
 
114
  The GLORYS variables are depth-resolved 50-band GeoTIFFs:
 
129
  per-file statistics, source filenames, compression, target dates, and the full
130
  depth axis are also recorded there.
131
 
132
+ ## PyTorch Dataset and DataLoader
133
+
134
+ The repository includes a standalone loader package in `depthdif_dataset/`.
135
+ It is designed to work directly from a local Hugging Face dataset checkout
136
+ without installing the full DepthDif training repository.
137
+
138
+ Install the loader dependencies in your environment:
139
+
140
+ ```bash
141
+ pip install -r requirements-loader.txt
142
+ ```
143
+
144
+ Minimal PyTorch usage from the dataset repository root:
145
+
146
+ ```python
147
+ from depthdif_dataset import ArgoGeoTIFFGriddedPatchDataset, build_dataloader
148
+
149
+ dataset = ArgoGeoTIFFGriddedPatchDataset(
150
+ geotiff_root_dir=".",
151
+ split="all",
152
+ tile_size=128,
153
+ patch_stride=128,
154
+ max_dates=1,
155
+ metadata_cache_dir=None,
156
+ )
157
+ loader = build_dataloader(dataset, batch_size=2, num_workers=0)
158
+ batch = next(iter(loader))
159
+ print(batch["x"].shape, batch["eo"].shape, batch["land_mask"].shape)
160
+ ```
161
+
162
+ The default sample contains normalized tensors for sparse ARGO temperature
163
+ input (`x`), dense GLORYS temperature target (`y`), dense surface context
164
+ (`eo`), validity masks, the ocean `land_mask`, target `date`, patch
165
+ coordinates, and a small `info` dictionary. Set `include_salinity=True` to
166
+ add `x_salinity`, `y_salinity`, and their masks. Use `eo_source="sss"` with
167
+ `eo_var_name="sos"` to use sea-surface salinity as the surface context
168
+ instead of OSTIA SST.
169
+
170
+ A runnable smoke test is included:
171
+
172
+ ```bash
173
+ python examples/torch_dataloader.py --root . --date-start 20000101 --max-dates 1 --batch-size 2
174
+ ```
175
+
176
+ ARGO-support filtering for train/validation splits requires counting profile
177
+ overlap per patch/date. The loader skips that scan for `split="all"` unless
178
+ `count_argo_support=True` or `--require-argo` is set in the example script.
179
+
180
+ ### Patch Grid, Overlap, and Land Filtering
181
+
182
+ The loader builds square patches on the fixed 0.1 degree GLORYS grid. With the
183
+ default `tile_size=128`, one sample covers a 12.8 x 12.8 degree region and has
184
+ 50 depth bands. `patch_stride` controls how far the next patch starts:
185
+
186
+ - `patch_stride=128`: non-overlapping global tiles.
187
+ - `patch_stride=96`: 32-pixel overlap, or 3.2 degrees at 0.1 degree resolution.
188
+ - `patch_stride=32`: 96-pixel overlap, or 9.6 degrees at 0.1 degree resolution.
189
+
190
+ Smaller strides create more samples and make neighboring patches share more
191
+ context, but they also increase row-index size and training time. If you use
192
+ overlap for train/validation splits, prefer a temporal validation split such as
193
+ `val_year=2018`; spatial random splits with overlapping patches can leak nearly
194
+ identical context between train and validation.
195
+
196
+ <p align="center">
197
+ <img src="assets/data/patch_grid/patch_grid_global_overview.webp" width="78%" alt="Global patch grid overview" />
198
+ </p>
199
+
200
+ <p align="center">
201
+ <img src="assets/data/patch_grid/patch_overlap_regional_example.webp" width="72%" alt="Regional example of overlapping patch windows" />
202
+ </p>
203
+
204
+ `max_land_fraction` filters out patches that are mostly land. The default
205
+ `max_land_fraction=0.30` keeps patches with at least 70 percent ocean pixels.
206
+ Increase it for coastal finetuning, or decrease it for open-ocean training.
207
+ The returned `land_mask` tensor uses `1` for ocean/support pixels and `0` for
208
+ land or unavailable support.
209
+
210
+ <p align="center">
211
+ <img src="assets/data/patch_grid/land_fraction_filter_examples.webp" width="72%" alt="Examples of patch filtering by land fraction" />
212
+ </p>
213
+
214
+ ### Common Loader Recipes
215
+
216
+ Use a small date slice for quick inspection without building a large metadata
217
+ cache:
218
+
219
+ ```python
220
+ dataset = ArgoGeoTIFFGriddedPatchDataset(
221
+ geotiff_root_dir=".",
222
+ split="all",
223
+ date_start=20000101,
224
+ max_dates=1,
225
+ tile_size=128,
226
+ patch_stride=128,
227
+ metadata_cache_dir=None,
228
+ )
229
+ ```
230
+
231
+ Use overlapping patches for training:
232
+
233
+ ```python
234
+ dataset = ArgoGeoTIFFGriddedPatchDataset(
235
+ geotiff_root_dir=".",
236
+ split="train",
237
+ tile_size=128,
238
+ patch_stride=32,
239
+ val_year=2018,
240
+ metadata_cache_dir="depthdif_cache",
241
+ )
242
+ ```
243
+
244
+ Use salinity targets and ARGO salinity inputs:
245
+
246
+ ```python
247
+ dataset = ArgoGeoTIFFGriddedPatchDataset(
248
+ geotiff_root_dir=".",
249
+ split="all",
250
+ include_salinity=True,
251
+ output_fields=("temperature", "salinity"),
252
+ metadata_cache_dir=None,
253
+ max_dates=1,
254
+ )
255
+ ```
256
+
257
+ Use sea-surface salinity as the surface context instead of OSTIA SST:
258
+
259
+ ```python
260
+ dataset = ArgoGeoTIFFGriddedPatchDataset(
261
+ geotiff_root_dir=".",
262
+ split="all",
263
+ eo_source="sss",
264
+ eo_var_name="sos",
265
+ include_salinity=True,
266
+ metadata_cache_dir=None,
267
+ max_dates=1,
268
+ )
269
+ ```
270
+
271
+ Use synthetic sparse observations sampled from the dense GLORYS target instead
272
+ of real ARGO profiles:
273
+
274
+ ```python
275
+ dataset = ArgoGeoTIFFGriddedPatchDataset(
276
+ geotiff_root_dir=".",
277
+ split="all",
278
+ synthetic_mode=True,
279
+ synthetic_pixel_count=250,
280
+ require_argo_for_all=False,
281
+ metadata_cache_dir=None,
282
+ max_dates=1,
283
+ )
284
+ ```
285
+
286
+ Filter samples to patch/date rows that contain ARGO support. This does extra
287
+ index work and is worth caching when used repeatedly:
288
+
289
+ ```python
290
+ dataset = ArgoGeoTIFFGriddedPatchDataset(
291
+ geotiff_root_dir=".",
292
+ split="all",
293
+ count_argo_support=True,
294
+ require_argo_for_all=True,
295
+ metadata_cache_dir="depthdif_cache",
296
+ date_start=20000101,
297
+ max_dates=1,
298
+ )
299
+ ```
300
+
301
+ The ARGO support map below shows why this filter changes the row distribution:
302
+ many open-ocean patches have dense support, while other valid ocean patches may
303
+ have no profiles for a given weekly target date.
304
+
305
+ <p align="center">
306
+ <img src="assets/data/argo_valid_pixels_per_patch.webp" width="78%" alt="ARGO valid pixels per training patch" />
307
+ </p>
308
+
309
+ ### Sample Dictionary
310
+
311
+ The default dataset returns normalized tensors:
312
+
313
+ - `x`: sparse ARGO temperature input, shape `(50, tile_size, tile_size)`.
314
+ - `y`: dense GLORYS temperature target, shape `(50, tile_size, tile_size)`.
315
+ - `eo`: dense surface context, shape `(1, tile_size, tile_size)`.
316
+ - `x_valid_mask` and `y_valid_mask`: boolean temperature masks.
317
+ - `x_valid_mask_1d`: depth-collapsed sparse-input support mask.
318
+ - `land_mask`: ocean/support mask, shape `(1, tile_size, tile_size)`.
319
+ - `date`: target date as `YYYYMMDD`.
320
+ - `coords`: patch center latitude and longitude when `return_coords=True`.
321
+ - `info`: patch/date metadata when `return_info=True`.
322
+
323
+ When `include_salinity=True`, samples also include `x_salinity`,
324
+ `y_salinity`, `x_salinity_valid_mask`, `y_salinity_valid_mask`, and
325
+ `x_salinity_valid_mask_1d`.
326
+
327
+ Temperatures are normalized from Celsius using the DepthDif training statistics;
328
+ salinity is normalized from PSU. To recover physical units:
329
+
330
+ ```python
331
+ from depthdif_dataset import salinity_normalize, temperature_normalize
332
+
333
+ temperature_c = temperature_normalize(mode="denorm", tensor=batch["y"])
334
+ salinity_psu = salinity_normalize(mode="denorm", tensor=batch["y_salinity"])
335
+ ```
336
+
337
  ## ARGO Alignment Examples
338
 
339
  ARGO profiles are projected onto the fixed 50-level GLORYS depth axis before
 
371
 
372
  Coverage:
373
 
374
+ - Raster target dates: 2000-01-01 to 2024-07-26
375
+ - Raster target date count per product: 1283
376
+ - Enriched ARGO profiles: 9485977
377
+ - Enriched ARGO profile dates: 2000-01-01 to 2024-07-31
378
+ - Compact grid-indexed ARGO profiles: 9451644
379
  - GLORYS depth levels: 50
380
 
381
+ The package is released as CC BY 4.0. Upstream product licenses and citation
382
+ requirements for EN4/ARGO, GLORYS, OSTIA, sea-level, and
383
+ sea-surface-salinity products still apply; see `LICENSE` for the attribution
384
+ notice.
argo/argo_profiles_on_grid.zarr/.zmetadata CHANGED
@@ -1 +1 @@
1
- {"metadata": {".zgroup": {"zarr_format": 2}, ".zattrs": {"created_by": "depth_recon.data.dataset_creation.export_dataset_geotiff.export_dataset_geotiff", "source_kind": "enriched", "temperature_units": "K", "temperature_stretch": {"name": "temperature_kelvin", "storage_dtype": "uint8", "minimum": 270.15, "maximum": 308.15, "units": "K", "nodata": 255, "valid_code_min": 0, "valid_code_max": 254, "valid_code_count": 255, "quantization_step": 0.14960629921259844, "max_abs_quantization_error": 0.07480314960629922, "decode": "minimum + code / 254 * (maximum - minimum)"}, "salinity_stretch": {"name": "salinity", "storage_dtype": "uint8", "minimum": 30.0, "maximum": 40.0, "units": "PSU", "nodata": 255, "valid_code_min": 0, "valid_code_max": 254, "valid_code_count": 255, "quantization_step": 0.03937007874015748, "max_abs_quantization_error": 0.01968503937007874, "decode": "minimum + code / 254 * (maximum - minimum)"}, "temporal_assignment": "nearest GLORYS target date inside centered 7-day window"}, "argo_psal_uint8/.zattrs": {"nodata": 255, "name": "salinity", "storage_dtype": "uint8", "minimum": 30.0, "maximum": 40.0, "units": "PSU", "valid_code_min": 0, "valid_code_max": 254, "valid_code_count": 255, "quantization_step": 0.03937007874015748, "max_abs_quantization_error": 0.01968503937007874, "decode": "minimum + code / 254 * (maximum - minimum)", "_ARRAY_DIMENSIONS": ["profile", "glorys_depth"]}, "argo_psal_uint8/.zarray": {"shape": [6608517, 50], "chunks": [50000, 50], "dtype": "|u1", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "argo_psal_valid/.zattrs": {"dtype": "bool", "_ARRAY_DIMENSIONS": ["profile", "glorys_depth"]}, "argo_psal_valid/.zarray": {"shape": [6608517, 50], "chunks": [50000, 50], "dtype": "|i1", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "argo_temp_kelvin_uint8/.zattrs": {"nodata": 255, "name": "temperature_kelvin", "storage_dtype": "uint8", "minimum": 270.15, "maximum": 308.15, "units": "K", "valid_code_min": 0, "valid_code_max": 254, "valid_code_count": 255, "quantization_step": 0.14960629921259844, "max_abs_quantization_error": 0.07480314960629922, "decode": "minimum + code / 254 * (maximum - minimum)", "_ARRAY_DIMENSIONS": ["profile", "glorys_depth"]}, "argo_temp_kelvin_uint8/.zarray": {"shape": [6608517, 50], "chunks": [50000, 50], "dtype": "|u1", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "argo_temp_valid/.zattrs": {"dtype": "bool", "_ARRAY_DIMENSIONS": ["profile", "glorys_depth"]}, "argo_temp_valid/.zarray": {"shape": [6608517, 50], "chunks": [50000, 50], "dtype": "|i1", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "glorys_depth/.zattrs": {"_ARRAY_DIMENSIONS": ["glorys_depth"]}, "glorys_depth/.zarray": {"shape": [50], "chunks": [50], "dtype": "<f4", "fill_value": "NaN", "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "grid_col/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "grid_col/.zarray": {"shape": [6608517], "chunks": [50000], "dtype": "<i4", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "grid_row/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "grid_row/.zarray": {"shape": [6608517], "chunks": [50000], "dtype": "<i4", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "latitude/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "latitude/.zarray": {"shape": [6608517], "chunks": [50000], "dtype": "<f4", "fill_value": "NaN", "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "longitude/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "longitude/.zarray": {"shape": [6608517], "chunks": [50000], "dtype": "<f4", "fill_value": "NaN", "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "profile/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "profile/.zarray": {"shape": [6608517], "chunks": [103259], "dtype": "<i8", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "profile_date/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "profile_date/.zarray": {"shape": [6608517], "chunks": [50000], "dtype": "<i4", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "profile_source_file/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "profile_source_file/.zarray": {"shape": [6608517], "chunks": [50000], "dtype": "<U33", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "source_profile_idx/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "source_profile_idx/.zarray": {"shape": [6608517], "chunks": [50000], "dtype": "<i4", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "target_date/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "target_date/.zarray": {"shape": [6608517], "chunks": [50000], "dtype": "<i4", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}}, "zarr_consolidated_format": 1}
 
1
+ {"metadata": {".zgroup": {"zarr_format": 2}, ".zattrs": {"created_by": "depth_recon.data.dataset_creation.export_dataset_geotiff.export_dataset_geotiff", "source_kind": "enriched", "temperature_units": "K", "temperature_stretch": {"name": "temperature_kelvin", "storage_dtype": "uint8", "minimum": 270.15, "maximum": 308.15, "units": "K", "nodata": 255, "valid_code_min": 0, "valid_code_max": 254, "valid_code_count": 255, "quantization_step": 0.14960629921259844, "max_abs_quantization_error": 0.07480314960629922, "decode": "minimum + code / 254 * (maximum - minimum)"}, "salinity_stretch": {"name": "salinity", "storage_dtype": "uint8", "minimum": 30.0, "maximum": 40.0, "units": "PSU", "nodata": 255, "valid_code_min": 0, "valid_code_max": 254, "valid_code_count": 255, "quantization_step": 0.03937007874015748, "max_abs_quantization_error": 0.01968503937007874, "decode": "minimum + code / 254 * (maximum - minimum)"}, "temporal_assignment": "nearest GLORYS target date inside centered 7-day window"}, "argo_psal_uint8/.zattrs": {"nodata": 255, "name": "salinity", "storage_dtype": "uint8", "minimum": 30.0, "maximum": 40.0, "units": "PSU", "valid_code_min": 0, "valid_code_max": 254, "valid_code_count": 255, "quantization_step": 0.03937007874015748, "max_abs_quantization_error": 0.01968503937007874, "decode": "minimum + code / 254 * (maximum - minimum)", "_ARRAY_DIMENSIONS": ["profile", "glorys_depth"]}, "argo_psal_uint8/.zarray": {"shape": [9451644, 50], "chunks": [50000, 50], "dtype": "|u1", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "argo_psal_valid/.zattrs": {"dtype": "bool", "_ARRAY_DIMENSIONS": ["profile", "glorys_depth"]}, "argo_psal_valid/.zarray": {"shape": [9451644, 50], "chunks": [50000, 50], "dtype": "|i1", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "argo_temp_kelvin_uint8/.zattrs": {"nodata": 255, "name": "temperature_kelvin", "storage_dtype": "uint8", "minimum": 270.15, "maximum": 308.15, "units": "K", "valid_code_min": 0, "valid_code_max": 254, "valid_code_count": 255, "quantization_step": 0.14960629921259844, "max_abs_quantization_error": 0.07480314960629922, "decode": "minimum + code / 254 * (maximum - minimum)", "_ARRAY_DIMENSIONS": ["profile", "glorys_depth"]}, "argo_temp_kelvin_uint8/.zarray": {"shape": [9451644, 50], "chunks": [50000, 50], "dtype": "|u1", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "argo_temp_valid/.zattrs": {"dtype": "bool", "_ARRAY_DIMENSIONS": ["profile", "glorys_depth"]}, "argo_temp_valid/.zarray": {"shape": [9451644, 50], "chunks": [50000, 50], "dtype": "|i1", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "glorys_depth/.zattrs": {"_ARRAY_DIMENSIONS": ["glorys_depth"]}, "glorys_depth/.zarray": {"shape": [50], "chunks": [50], "dtype": "<f4", "fill_value": "NaN", "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "grid_col/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "grid_col/.zarray": {"shape": [9451644], "chunks": [50000], "dtype": "<i4", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "grid_row/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "grid_row/.zarray": {"shape": [9451644], "chunks": [50000], "dtype": "<i4", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "latitude/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "latitude/.zarray": {"shape": [9451644], "chunks": [50000], "dtype": "<f4", "fill_value": "NaN", "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "longitude/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "longitude/.zarray": {"shape": [9451644], "chunks": [50000], "dtype": "<f4", "fill_value": "NaN", "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "profile/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "profile/.zarray": {"shape": [9451644], "chunks": [147682], "dtype": "<i8", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "profile_date/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "profile_date/.zarray": {"shape": [9451644], "chunks": [50000], "dtype": "<i4", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "profile_source_file/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "profile_source_file/.zarray": {"shape": [9451644], "chunks": [50000], "dtype": "<U33", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "source_profile_idx/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "source_profile_idx/.zarray": {"shape": [9451644], "chunks": [50000], "dtype": "<i4", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}, "target_date/.zattrs": {"_ARRAY_DIMENSIONS": ["profile"]}, "target_date/.zarray": {"shape": [9451644], "chunks": [50000], "dtype": "<i4", "fill_value": null, "order": "C", "filters": null, "dimension_separator": ".", "compressor": {"id": "blosc", "cname": "lz4", "clevel": 5, "shuffle": 1, "blocksize": 0}, "zarr_format": 2}}, "zarr_consolidated_format": 1}
argo/argo_profiles_on_grid.zarr/source_profile_idx/1 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/1 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/1 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/101 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/101 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/101 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/108 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/108 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/108 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/110 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/110 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/110 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/12 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/12 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/12 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/129 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/129 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/129 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/158 ADDED
Binary file (11.9 kB). View file
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/162 ADDED
Binary file (13.6 kB). View file
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/167 ADDED
Binary file (13.9 kB). View file
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/177 ADDED
Binary file (23.9 kB). View file
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/18 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/18 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/18 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/186 ADDED
Binary file (24.3 kB). View file
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/189 ADDED
Binary file (1.45 kB). View file
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/2 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/2 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/2 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/23 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/23 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/23 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/30 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/30 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/30 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/31 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/31 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/31 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/37 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/37 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/37 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/42 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/42 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/42 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/5 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/5 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/5 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/50 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/50 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/50 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/51 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/51 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/51 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/62 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/62 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/62 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/64 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/64 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/64 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/7 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/7 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/7 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/71 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/71 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/71 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/77 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/77 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/77 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/84 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/84 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/84 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/91 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/91 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/91 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/92 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/92 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/92 differ
 
argo/argo_profiles_on_grid.zarr/source_profile_idx/93 CHANGED
Binary files a/argo/argo_profiles_on_grid.zarr/source_profile_idx/93 and b/argo/argo_profiles_on_grid.zarr/source_profile_idx/93 differ
 
depthdif_dataset/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PyTorch loaders for the DepthDif Hugging Face dataset."""
2
+
3
+ from .dataloaders import (
4
+ DepthTileDataModule,
5
+ build_dataloader,
6
+ build_train_val_dataloaders,
7
+ split_dataset,
8
+ )
9
+ from .dataset import (
10
+ ArgoGeoTIFFGriddedPatchDataset,
11
+ ArgoGeoTIFFProfileStore,
12
+ GeoTIFFPatchIndex,
13
+ GeoTIFFRasterStore,
14
+ )
15
+ from .normalizations import salinity_normalize, temperature_normalize
16
+
17
+ __all__ = [
18
+ "ArgoGeoTIFFGriddedPatchDataset",
19
+ "ArgoGeoTIFFProfileStore",
20
+ "DepthTileDataModule",
21
+ "GeoTIFFPatchIndex",
22
+ "GeoTIFFRasterStore",
23
+ "build_dataloader",
24
+ "build_train_val_dataloaders",
25
+ "salinity_normalize",
26
+ "split_dataset",
27
+ "temperature_normalize",
28
+ ]
depthdif_dataset/dataloaders.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import torch
6
+ from torch.utils.data import DataLoader, Dataset, Subset, random_split
7
+
8
+
9
+ def build_dataloader(
10
+ dataset: Dataset,
11
+ *,
12
+ batch_size: int = 16,
13
+ shuffle: bool = True,
14
+ num_workers: int = 0,
15
+ pin_memory: bool = True,
16
+ persistent_workers: bool = False,
17
+ prefetch_factor: int | None = 2,
18
+ ) -> DataLoader:
19
+ """Build a PyTorch DataLoader with the DepthDif training defaults."""
20
+ num_workers = int(num_workers)
21
+ kwargs: dict[str, Any] = dict(
22
+ dataset=dataset,
23
+ batch_size=int(batch_size),
24
+ shuffle=bool(shuffle),
25
+ num_workers=num_workers,
26
+ pin_memory=bool(pin_memory),
27
+ persistent_workers=bool(persistent_workers) and num_workers > 0,
28
+ )
29
+ # PyTorch only accepts prefetch_factor when worker processes are enabled.
30
+ if num_workers > 0 and prefetch_factor is not None:
31
+ kwargs["prefetch_factor"] = int(prefetch_factor)
32
+ return DataLoader(**kwargs)
33
+
34
+
35
+ def split_dataset(
36
+ dataset: Dataset,
37
+ *,
38
+ val_fraction: float = 0.2,
39
+ seed: int = 7,
40
+ ) -> tuple[Subset, Subset]:
41
+ """Create a deterministic train/validation split from one dataset."""
42
+ total_len = len(dataset)
43
+ if total_len == 0:
44
+ raise RuntimeError("Dataset is empty; cannot create train/val split.")
45
+
46
+ val_len = int(round(total_len * float(val_fraction)))
47
+ if total_len > 1:
48
+ val_len = min(max(val_len, 1 if val_fraction > 0.0 else 0), total_len - 1)
49
+ else:
50
+ val_len = 0
51
+ train_len = total_len - val_len
52
+ generator = torch.Generator().manual_seed(int(seed))
53
+ train_dataset, val_dataset = random_split(
54
+ dataset,
55
+ [train_len, val_len],
56
+ generator=generator,
57
+ )
58
+ return train_dataset, val_dataset
59
+
60
+
61
+ def build_train_val_dataloaders(
62
+ dataset: Dataset,
63
+ *,
64
+ val_dataset: Dataset | None = None,
65
+ dataloader_cfg: dict[str, Any] | None = None,
66
+ val_fraction: float = 0.2,
67
+ seed: int = 7,
68
+ ) -> tuple[DataLoader, DataLoader]:
69
+ """Build train and validation DataLoaders from one or two datasets."""
70
+ cfg = dict(dataloader_cfg or {})
71
+ if val_dataset is None:
72
+ train_dataset, val_dataset = split_dataset(
73
+ dataset,
74
+ val_fraction=val_fraction,
75
+ seed=seed,
76
+ )
77
+ else:
78
+ train_dataset = dataset
79
+
80
+ train_loader = build_dataloader(
81
+ train_dataset,
82
+ batch_size=int(cfg.get("batch_size", 16)),
83
+ shuffle=bool(cfg.get("shuffle", True)),
84
+ num_workers=int(cfg.get("num_workers", 4)),
85
+ pin_memory=bool(cfg.get("pin_memory", True)),
86
+ persistent_workers=bool(cfg.get("persistent_workers", False)),
87
+ prefetch_factor=cfg.get("prefetch_factor", 2),
88
+ )
89
+ val_loader = build_dataloader(
90
+ val_dataset,
91
+ batch_size=int(cfg.get("val_batch_size", cfg.get("batch_size", 16))),
92
+ # Keep the repository's intended behavior: validation is shuffled by default.
93
+ shuffle=bool(cfg.get("val_shuffle", True)),
94
+ num_workers=int(cfg.get("val_num_workers", 0)),
95
+ pin_memory=bool(cfg.get("pin_memory", True)),
96
+ persistent_workers=bool(cfg.get("val_persistent_workers", False)),
97
+ prefetch_factor=cfg.get("prefetch_factor", 2),
98
+ )
99
+ return train_loader, val_loader
100
+
101
+
102
+ class DepthTileDataModule:
103
+ """Small PyTorch-only DataModule-style wrapper for DepthDif tiles."""
104
+
105
+ def __init__(
106
+ self,
107
+ *,
108
+ dataset: Dataset,
109
+ val_dataset: Dataset | None = None,
110
+ dataloader_cfg: dict[str, Any] | None = None,
111
+ val_fraction: float = 0.2,
112
+ seed: int = 7,
113
+ ) -> None:
114
+ """Store dataset and loader settings without requiring Lightning."""
115
+ self.dataset = dataset
116
+ self.val_dataset = val_dataset
117
+ self.dataloader_cfg = dataloader_cfg or {}
118
+ self.val_fraction = float(val_fraction)
119
+ self.seed = int(seed)
120
+ self.train_dataset: Subset | Dataset | None = (
121
+ dataset if val_dataset is not None else None
122
+ )
123
+ self._train_val_split_done = val_dataset is not None
124
+
125
+ def setup(self, stage: str | None = None) -> None:
126
+ """Prepare deterministic train/validation datasets."""
127
+ _ = stage
128
+ if self._train_val_split_done:
129
+ return
130
+ self.train_dataset, self.val_dataset = split_dataset(
131
+ self.dataset,
132
+ val_fraction=self.val_fraction,
133
+ seed=self.seed,
134
+ )
135
+ self._train_val_split_done = True
136
+
137
+ def train_dataloader(self) -> DataLoader:
138
+ """Return the configured training DataLoader."""
139
+ if not self._train_val_split_done:
140
+ self.setup("fit")
141
+ return build_train_val_dataloaders(
142
+ self.train_dataset,
143
+ val_dataset=self.val_dataset,
144
+ dataloader_cfg=self.dataloader_cfg,
145
+ val_fraction=self.val_fraction,
146
+ seed=self.seed,
147
+ )[0]
148
+
149
+ def val_dataloader(self) -> DataLoader:
150
+ """Return the configured validation DataLoader."""
151
+ if not self._train_val_split_done:
152
+ self.setup("fit")
153
+ return build_train_val_dataloaders(
154
+ self.train_dataset,
155
+ val_dataset=self.val_dataset,
156
+ dataloader_cfg=self.dataloader_cfg,
157
+ val_fraction=self.val_fraction,
158
+ seed=self.seed,
159
+ )[1]
depthdif_dataset/dataset.py ADDED
@@ -0,0 +1,1781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import os
5
+ from collections import OrderedDict
6
+ from pathlib import Path
7
+ from typing import Any, Sequence
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ import rasterio
12
+ from rasterio.windows import Window
13
+ import torch
14
+ from torch.utils.data import Dataset
15
+ from tqdm import tqdm
16
+ import xarray as xr
17
+ import yaml
18
+ import zarr
19
+
20
+ from .grid_utils import (
21
+ MISSING_TEXT_VALUES,
22
+ _GridParams,
23
+ _build_land_mask_patch_table,
24
+ _center_lon_deg,
25
+ _deep_update_config,
26
+ _force_include_cache_hash,
27
+ _normalize_lon,
28
+ _parse_date_int,
29
+ _parse_force_include_regions,
30
+ _path_cache_hash,
31
+ _sanitize_cache_text,
32
+ _validate_grid_params,
33
+ )
34
+ from .normalizations import (
35
+ CELSIUS_TO_KELVIN_OFFSET,
36
+ salinity_normalize,
37
+ temperature_normalize,
38
+ )
39
+
40
+ VALID_CODE_MAX = 254.0
41
+ NODATA_CODE = 255
42
+
43
+
44
+ def _decode_stretched_uint8(values: np.ndarray, stretch: dict[str, Any]) -> np.ndarray:
45
+ """Decode uint8 GeoTIFF values into physical units from manifest metadata."""
46
+ arr = np.asarray(values, dtype=np.uint8)
47
+ nodata = int(stretch.get("nodata", NODATA_CODE))
48
+ valid_code_max = float(stretch.get("valid_code_max", VALID_CODE_MAX))
49
+ minimum = np.float32(stretch["minimum"])
50
+ maximum = np.float32(stretch["maximum"])
51
+ out = np.full(arr.shape, np.nan, dtype=np.float32)
52
+ valid = arr != nodata
53
+ out[valid] = minimum + (
54
+ arr[valid].astype(np.float32)
55
+ / np.float32(valid_code_max)
56
+ * np.float32(maximum - minimum)
57
+ )
58
+ return out
59
+
60
+
61
+ def _kelvin_to_celsius(values: np.ndarray) -> np.ndarray:
62
+ """Convert decoded Kelvin temperature values to Celsius for model normalization."""
63
+ return np.asarray(values, dtype=np.float32) - np.float32(CELSIUS_TO_KELVIN_OFFSET)
64
+
65
+
66
+ def _resolve_manifest_path(root_dir: Path, raw_path: str | Path) -> Path:
67
+ """Resolve a manifest path that may be absolute or export-root relative."""
68
+ path = Path(raw_path)
69
+ if path.is_absolute():
70
+ return path
71
+ return root_dir / path
72
+
73
+
74
+ def _resolve_land_mask_path(root_dir: Path, raw_path: str | Path) -> Path:
75
+ """Resolve a land-mask path inside the packaged GeoTIFF dataset root."""
76
+ export_path = _resolve_manifest_path(root_dir, raw_path)
77
+ if not export_path.exists():
78
+ raise FileNotFoundError(
79
+ "Land-mask GeoTIFF must be present in the packaged dataset layout: "
80
+ f"{export_path}"
81
+ )
82
+ return export_path
83
+
84
+
85
+ def _records_by_date(
86
+ entries: Sequence[dict[str, Any]], root_dir: Path
87
+ ) -> dict[int, Path]:
88
+ """Map manifest raster entries by date."""
89
+ records: dict[int, Path] = {}
90
+ for entry in entries:
91
+ records[int(entry["date"])] = _resolve_manifest_path(root_dir, entry["path"])
92
+ return records
93
+
94
+
95
+ def _date_signature(dates: Sequence[int]) -> str:
96
+ """Return a compact hashable date coverage signature."""
97
+ if not dates:
98
+ return "empty"
99
+ raw = (int(min(dates)), int(max(dates)), int(len(dates)))
100
+ return "-".join(str(value) for value in raw)
101
+
102
+
103
+ class RasterDatasetCache:
104
+ """Small LRU cache for rasterio datasets opened by one worker process."""
105
+
106
+ def __init__(self, max_open: int = 8) -> None:
107
+ """Initialize a bounded raster path cache."""
108
+ self.max_open = int(max_open)
109
+ self._pid = os.getpid()
110
+ self._items: OrderedDict[Path, rasterio.io.DatasetReader] = OrderedDict()
111
+
112
+ def _ensure_current_process(self) -> None:
113
+ """Drop inherited file handles after DataLoader worker forks."""
114
+ pid = os.getpid()
115
+ if pid == self._pid:
116
+ return
117
+ self.close()
118
+ self._pid = pid
119
+
120
+ def get(self, path: Path) -> rasterio.io.DatasetReader:
121
+ """Return an opened raster dataset for ``path``."""
122
+ self._ensure_current_process()
123
+ path = Path(path)
124
+ if path in self._items:
125
+ src = self._items.pop(path)
126
+ self._items[path] = src
127
+ return src
128
+ src = rasterio.open(path)
129
+ self._items[path] = src
130
+ while len(self._items) > self.max_open:
131
+ _, old = self._items.popitem(last=False)
132
+ old.close()
133
+ return src
134
+
135
+ def close(self) -> None:
136
+ """Close all cached raster datasets."""
137
+ for src in self._items.values():
138
+ src.close()
139
+ self._items.clear()
140
+
141
+
142
+ class GeoTIFFRasterStore:
143
+ """Date-indexed GeoTIFF raster source for one exported variable."""
144
+
145
+ def __init__(
146
+ self,
147
+ *,
148
+ paths_by_date: dict[int, Path],
149
+ stretch: dict[str, Any],
150
+ cache: RasterDatasetCache,
151
+ kelvin_temperature: bool,
152
+ ) -> None:
153
+ """Initialize a date-to-raster lookup."""
154
+ self.paths_by_date = dict(paths_by_date)
155
+ self.stretch = dict(stretch)
156
+ self.cache = cache
157
+ self.kelvin_temperature = bool(kelvin_temperature)
158
+
159
+ @property
160
+ def dates(self) -> set[int]:
161
+ """Return available YYYYMMDD dates."""
162
+ return set(int(value) for value in self.paths_by_date)
163
+
164
+ def read_patch(
165
+ self,
166
+ *,
167
+ target_date: int,
168
+ grid_y0: int,
169
+ grid_x0: int,
170
+ tile_size: int,
171
+ ) -> np.ndarray:
172
+ """Read and decode one patch for ``target_date``."""
173
+ path = self.paths_by_date[int(target_date)]
174
+ src = self.cache.get(path)
175
+ window = Window(
176
+ col_off=int(grid_x0),
177
+ row_off=int(grid_y0),
178
+ width=int(tile_size),
179
+ height=int(tile_size),
180
+ )
181
+ encoded = src.read(window=window)
182
+ decoded = _decode_stretched_uint8(encoded, self.stretch)
183
+ if self.kelvin_temperature:
184
+ decoded = _kelvin_to_celsius(decoded)
185
+ return decoded.astype(np.float32, copy=False)
186
+
187
+
188
+ class ArgoGeoTIFFProfileStore:
189
+ """Profile-indexed ARGO zarr source exported with the GeoTIFF dataset."""
190
+
191
+ def __init__(self, path: str | Path, *, include_salinity: bool = False) -> None:
192
+ """Open a compact ARGO profile zarr store."""
193
+ self.path = Path(path)
194
+ if not self.path.exists():
195
+ raise FileNotFoundError(f"ARGO profile zarr does not exist: {self.path}")
196
+ self.include_salinity = bool(include_salinity)
197
+ self._pid = os.getpid()
198
+ self.ds = self._open_dataset()
199
+ self._zarr_pid = os.getpid()
200
+ self._zarr_group = self._open_zarr_group()
201
+ required = {
202
+ "target_date",
203
+ "grid_row",
204
+ "grid_col",
205
+ "argo_temp_kelvin_uint8",
206
+ "argo_temp_valid",
207
+ }
208
+ if self.include_salinity:
209
+ required.update({"argo_psal_uint8", "argo_psal_valid"})
210
+ missing = sorted(name for name in required if name not in self.ds)
211
+ if missing:
212
+ raise RuntimeError(
213
+ f"ARGO profile zarr is missing required variables {missing}: {self.path}"
214
+ )
215
+ self.target_date = np.asarray(self.ds["target_date"].values, dtype=np.int32)
216
+ self.grid_row = np.asarray(self.ds["grid_row"].values, dtype=np.int32)
217
+ self.grid_col = np.asarray(self.ds["grid_col"].values, dtype=np.int32)
218
+ self.depth_axis_m = np.asarray(
219
+ self.ds["glorys_depth"].values, dtype=np.float32
220
+ ).reshape(-1)
221
+ temp_valid = np.asarray(self.ds["argo_temp_valid"].values, dtype=bool)
222
+ self._has_valid_temp = temp_valid.any(axis=1)
223
+ (
224
+ self._valid_profile_indices_by_date,
225
+ self._profile_index_bounds_by_date,
226
+ ) = self._build_valid_profile_index()
227
+ self.temperature_stretch = self._temperature_stretch()
228
+ self.salinity_stretch = (
229
+ self._salinity_stretch() if self.include_salinity else None
230
+ )
231
+
232
+ def _open_dataset(self) -> xr.Dataset:
233
+ """Open the zarr dataset in the current process."""
234
+ return xr.open_zarr(self.path, consolidated=None)
235
+
236
+ def _open_zarr_group(self) -> zarr.Group:
237
+ """Open the zarr group used for direct array reads."""
238
+ return zarr.open_group(self.path, mode="r")
239
+
240
+ def _ensure_current_process(self) -> xr.Dataset:
241
+ """Reopen zarr handles after DataLoader worker forks."""
242
+ pid = os.getpid()
243
+ if pid == self._pid:
244
+ return self.ds
245
+ # Do not close inherited xarray/zarr handles in a forked worker; closing
246
+ # those locks after fork can block before the worker reads its first batch.
247
+ self.ds = self._open_dataset()
248
+ self._pid = pid
249
+ return self.ds
250
+
251
+ def _ensure_zarr_group(self) -> zarr.Group:
252
+ """Return a direct zarr group opened in the current process."""
253
+ pid = os.getpid()
254
+ if pid != self._zarr_pid:
255
+ self._zarr_group = self._open_zarr_group()
256
+ self._zarr_pid = pid
257
+ return self._zarr_group
258
+
259
+ def _build_valid_profile_index(
260
+ self,
261
+ ) -> tuple[np.ndarray, dict[int, tuple[int, int]]]:
262
+ """Build date slices over valid-temperature profile indices."""
263
+ valid_indices = np.flatnonzero(self._has_valid_temp).astype(np.int64)
264
+ if valid_indices.size == 0:
265
+ return valid_indices, {}
266
+
267
+ # Querying per sample must not scan the full multi-million-profile store.
268
+ order = np.argsort(self.target_date[valid_indices], kind="stable")
269
+ sorted_indices = valid_indices[order]
270
+ sorted_dates = self.target_date[sorted_indices]
271
+ unique_dates, starts, counts = np.unique(
272
+ sorted_dates, return_index=True, return_counts=True
273
+ )
274
+ bounds = {
275
+ int(date): (int(start), int(start + count))
276
+ for date, start, count in zip(
277
+ unique_dates.tolist(),
278
+ starts.tolist(),
279
+ counts.tolist(),
280
+ strict=False,
281
+ )
282
+ }
283
+ return sorted_indices, bounds
284
+
285
+ def _temperature_stretch(self) -> dict[str, Any]:
286
+ """Read temperature stretch metadata from variable or dataset attributes."""
287
+ ds = self._ensure_current_process()
288
+ attrs = dict(ds["argo_temp_kelvin_uint8"].attrs)
289
+ if "minimum" in attrs and "maximum" in attrs:
290
+ return attrs
291
+ ds_attrs = dict(ds.attrs)
292
+ stretch = ds_attrs.get("temperature_stretch")
293
+ if isinstance(stretch, dict):
294
+ return stretch
295
+ raise RuntimeError(
296
+ f"ARGO profile zarr lacks temperature stretch metadata: {self.path}"
297
+ )
298
+
299
+ def _salinity_stretch(self) -> dict[str, Any]:
300
+ """Read salinity stretch metadata from variable or dataset attributes."""
301
+ ds = self._ensure_current_process()
302
+ attrs = dict(ds["argo_psal_uint8"].attrs)
303
+ if "minimum" in attrs and "maximum" in attrs:
304
+ return attrs
305
+ ds_attrs = dict(ds.attrs)
306
+ stretch = ds_attrs.get("salinity_stretch")
307
+ if isinstance(stretch, dict):
308
+ return stretch
309
+ raise RuntimeError(
310
+ f"ARGO profile zarr lacks salinity stretch metadata: {self.path}"
311
+ )
312
+
313
+ def query_indices(
314
+ self,
315
+ *,
316
+ target_date: int,
317
+ grid_y0: int,
318
+ grid_x0: int,
319
+ tile_size: int,
320
+ ) -> np.ndarray:
321
+ """Return profile indices assigned to one date and grid patch."""
322
+ y0 = int(grid_y0)
323
+ x0 = int(grid_x0)
324
+ tile = int(tile_size)
325
+ bounds = self._profile_index_bounds_by_date.get(int(target_date))
326
+ if bounds is None:
327
+ return np.zeros((0,), dtype=np.int64)
328
+ start, stop = bounds
329
+ candidates = self._valid_profile_indices_by_date[start:stop]
330
+ mask = (
331
+ (self.grid_row[candidates] >= y0)
332
+ & (self.grid_row[candidates] < y0 + tile)
333
+ & (self.grid_col[candidates] >= x0)
334
+ & (self.grid_col[candidates] < x0 + tile)
335
+ )
336
+ return candidates[mask].astype(np.int64, copy=False)
337
+
338
+ def load_temperature_profiles(self, indices: np.ndarray) -> np.ndarray:
339
+ """Load selected ARGO temperature profiles as Celsius arrays."""
340
+ indices = np.asarray(indices, dtype=np.int64).reshape(-1)
341
+ depth_size = int(self.depth_axis_m.size)
342
+ if indices.size == 0:
343
+ return np.zeros((0, depth_size), dtype=np.float32)
344
+ group = self._ensure_zarr_group()
345
+ encoded = np.asarray(
346
+ group["argo_temp_kelvin_uint8"].get_orthogonal_selection(
347
+ (indices, slice(None))
348
+ ),
349
+ dtype=np.uint8,
350
+ )
351
+ valid = np.asarray(
352
+ group["argo_temp_valid"].get_orthogonal_selection((indices, slice(None))),
353
+ dtype=bool,
354
+ )
355
+ kelvin = _decode_stretched_uint8(encoded, self.temperature_stretch)
356
+ kelvin[~valid] = np.nan
357
+ return _kelvin_to_celsius(kelvin).astype(np.float32, copy=False)
358
+
359
+ def load_salinity_profiles(self, indices: np.ndarray) -> np.ndarray:
360
+ """Load selected ARGO salinity profiles as raw PSU arrays."""
361
+ if self.salinity_stretch is None:
362
+ raise RuntimeError(
363
+ "ARGO salinity profiles were not enabled for this store."
364
+ )
365
+ indices = np.asarray(indices, dtype=np.int64).reshape(-1)
366
+ depth_size = int(self.depth_axis_m.size)
367
+ if indices.size == 0:
368
+ return np.zeros((0, depth_size), dtype=np.float32)
369
+ group = self._ensure_zarr_group()
370
+ encoded = np.asarray(
371
+ group["argo_psal_uint8"].get_orthogonal_selection((indices, slice(None))),
372
+ dtype=np.uint8,
373
+ )
374
+ valid = np.asarray(
375
+ group["argo_psal_valid"].get_orthogonal_selection((indices, slice(None))),
376
+ dtype=bool,
377
+ )
378
+ salinity = _decode_stretched_uint8(encoded, self.salinity_stretch)
379
+ salinity[~valid] = np.nan
380
+ return salinity.astype(np.float32, copy=False)
381
+
382
+ def close(self) -> None:
383
+ """Close the opened zarr dataset."""
384
+ self.ds.close()
385
+
386
+
387
+ class GeoTIFFPatchIndex:
388
+ """Build compact patch/date metadata rows for GeoTIFF training stores."""
389
+
390
+ CACHE_VERSION = 1
391
+
392
+ def __init__(
393
+ self,
394
+ *,
395
+ root_dir: Path,
396
+ dates: Sequence[int],
397
+ argo_store: ArgoGeoTIFFProfileStore | None,
398
+ cache_dir: str | Path | None,
399
+ grid_params: _GridParams,
400
+ ) -> None:
401
+ """Initialize index inputs."""
402
+ self.root_dir = Path(root_dir)
403
+ self.dates = sorted(int(value) for value in dates)
404
+ self.argo_store = argo_store
405
+ self.cache_dir = None if cache_dir is None else Path(cache_dir)
406
+ self.grid_params = grid_params
407
+ _validate_grid_params(self.grid_params)
408
+ if str(self.grid_params.patch_grid_source).strip().lower() != "land_mask":
409
+ raise ValueError(
410
+ "GeoTIFF datasets require grid.patch_grid_source='land_mask'."
411
+ )
412
+
413
+ def load_rows(self) -> list[dict[str, Any]]:
414
+ """Load cached rows or build a fresh patch/date registry."""
415
+ cache_path = self._cache_path()
416
+ if cache_path is not None and cache_path.exists():
417
+ return pd.read_csv(cache_path).to_dict(orient="records")
418
+
419
+ patch_df = _build_land_mask_patch_table(self.grid_params)
420
+ if self.grid_params.val_year is None:
421
+ patch_records = patch_df.to_dict(orient="records")
422
+ phases = self._split_phases(len(patch_records))
423
+ for rec, phase in zip(patch_records, phases, strict=False):
424
+ rec["split"] = phase
425
+ rec["phase"] = phase
426
+ patch_df = pd.DataFrame.from_records(patch_records)
427
+ support_counts = self._build_support_counts(patch_df)
428
+ rows: list[dict[str, Any]] = []
429
+ export_index = 0
430
+ for date_value in self.dates:
431
+ for patch in patch_df.to_dict(orient="records"):
432
+ patch_id = int(patch["patch_id"])
433
+ row = dict(patch)
434
+ row["date"] = int(date_value)
435
+ row["export_index"] = int(export_index)
436
+ if self.grid_params.val_year is not None:
437
+ phase = self._phase_for_date(int(date_value))
438
+ row["split"] = phase
439
+ row["phase"] = phase
440
+ else:
441
+ phase = str(patch.get("split", patch.get("phase", "train")))
442
+ row["split"] = phase
443
+ row["phase"] = phase
444
+ row["argo_profile_count"] = int(
445
+ support_counts.get((patch_id, int(date_value)), 0)
446
+ )
447
+ rows.append(row)
448
+ export_index += 1
449
+
450
+ if cache_path is not None:
451
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
452
+ pd.DataFrame.from_records(rows).to_csv(cache_path, index=False)
453
+ return rows
454
+
455
+ def _cache_path(self) -> Path | None:
456
+ """Return the metadata cache path for these index settings."""
457
+ if self.cache_dir is None:
458
+ return None
459
+ res_text = str(float(self.grid_params.resolution_deg)).replace(".", "p")
460
+ land_text = str(float(self.grid_params.max_land_fraction)).replace(".", "p")
461
+ grid_source = _sanitize_cache_text(self.grid_params.patch_grid_source)
462
+ mask_hash = _path_cache_hash(self.grid_params.land_mask_path)
463
+ force_hash = _force_include_cache_hash(self.grid_params.force_include_regions)
464
+ root_hash = hashlib.sha1(str(self.root_dir).encode("utf-8")).hexdigest()[:8]
465
+ split_text = (
466
+ f"valyear{int(self.grid_params.val_year)}"
467
+ if self.grid_params.val_year is not None
468
+ else "patchsplit"
469
+ )
470
+ name = (
471
+ f"argo_geotiff_gridded_v{self.CACHE_VERSION}_root{root_hash}_"
472
+ f"dates{_date_signature(self.dates)}_"
473
+ f"tile{int(self.grid_params.tile_size)}_res{res_text}_"
474
+ f"stride{int(self.grid_params.effective_patch_stride)}_"
475
+ f"grid{grid_source}_land{land_text}_mask{mask_hash}_"
476
+ f"force{force_hash}_{split_text}.csv"
477
+ )
478
+ return self.cache_dir / name
479
+
480
+ def _phase_for_date(self, date_value: int) -> str:
481
+ """Return the train/validation phase for one date."""
482
+ year = int(date_value) // 10000
483
+ return "val" if year == int(self.grid_params.val_year) else "train"
484
+
485
+ def _split_phases(self, n_patches: int) -> list[str]:
486
+ """Return deterministic spatial train/validation phases."""
487
+ phases = np.full((int(n_patches),), "train", dtype=object)
488
+ val_len = int(round(int(n_patches) * float(self.grid_params.val_fraction)))
489
+ if n_patches > 1:
490
+ val_len = min(
491
+ max(val_len, 1 if self.grid_params.val_fraction > 0.0 else 0),
492
+ int(n_patches) - 1,
493
+ )
494
+ else:
495
+ val_len = 0
496
+ if val_len > 0:
497
+ rng = np.random.default_rng(int(self.grid_params.split_seed))
498
+ val_indices = rng.permutation(np.arange(int(n_patches)))[:val_len]
499
+ phases[val_indices] = "val"
500
+ return [str(value) for value in phases.tolist()]
501
+
502
+ def _build_support_counts(
503
+ self,
504
+ patch_df: pd.DataFrame,
505
+ ) -> dict[tuple[int, int], int]:
506
+ """Count ARGO profiles per overlapping patch/date row."""
507
+ support_counts: dict[tuple[int, int], int] = {}
508
+ if self.argo_store is None or patch_df.empty or not self.dates:
509
+ return support_counts
510
+
511
+ date_set = set(int(value) for value in self.dates)
512
+ tile = int(self.grid_params.tile_size)
513
+ patch_by_start = {
514
+ (int(row["grid_y0"]), int(row["grid_x0"])): int(row["patch_id"])
515
+ for row in patch_df.to_dict(orient="records")
516
+ }
517
+ y_starts = np.asarray(
518
+ sorted({key[0] for key in patch_by_start}), dtype=np.int64
519
+ )
520
+ x_starts = np.asarray(
521
+ sorted({key[1] for key in patch_by_start}), dtype=np.int64
522
+ )
523
+ selected_profile_indices: list[np.ndarray] = []
524
+ for date_value in sorted(date_set):
525
+ bounds = self.argo_store._profile_index_bounds_by_date.get(int(date_value))
526
+ if bounds is None:
527
+ continue
528
+ start, stop = bounds
529
+ selected_profile_indices.append(
530
+ self.argo_store._valid_profile_indices_by_date[start:stop]
531
+ )
532
+ if not selected_profile_indices:
533
+ return support_counts
534
+ profile_indices = np.concatenate(selected_profile_indices).astype(
535
+ np.int64,
536
+ copy=False,
537
+ )
538
+
539
+ for profile_idx in tqdm(
540
+ profile_indices.tolist(),
541
+ total=int(profile_indices.size),
542
+ desc="Counting ARGO overlap support",
543
+ unit="profile",
544
+ dynamic_ncols=True,
545
+ ):
546
+ date_value = int(self.argo_store.target_date[profile_idx])
547
+ row_idx = int(self.argo_store.grid_row[profile_idx])
548
+ col_idx = int(self.argo_store.grid_col[profile_idx])
549
+ y_candidates = y_starts[(y_starts <= row_idx) & (row_idx < y_starts + tile)]
550
+ x_candidates = x_starts[(x_starts <= col_idx) & (col_idx < x_starts + tile)]
551
+ for y0 in y_candidates.tolist():
552
+ for x0 in x_candidates.tolist():
553
+ patch_id = patch_by_start.get((int(y0), int(x0)))
554
+ if patch_id is None:
555
+ continue
556
+ key = (int(patch_id), int(date_value))
557
+ support_counts[key] = support_counts.get(key, 0) + 1
558
+ return support_counts
559
+
560
+
561
+ DEFAULT_DATASET_ROOT_DIR = Path(__file__).resolve().parents[1]
562
+ DEFAULT_GEOTIFF_ROOT_DIR = DEFAULT_DATASET_ROOT_DIR.as_posix()
563
+ DEFAULT_METADATA_CACHE_DIR = (DEFAULT_DATASET_ROOT_DIR / "depthdif_cache").as_posix()
564
+ DEFAULT_CONFIG_PATH = (
565
+ Path(__file__).resolve().parent / "configs/default_dataset.yaml"
566
+ ).as_posix()
567
+ DEFAULT_LAND_MASK_RELATIVE_PATH = "masks/world_land_mask_glorys_0p1.tif"
568
+ EO_SOURCE_DEFAULTS = {"ostia": "analysed_sst", "sss": "sos"}
569
+ EO_STRETCH_BY_SOURCE_VAR = {
570
+ ("ostia", "analysed_sst"): ("temperature_kelvin", "temperature"),
571
+ ("sss", "sos"): ("salinity", "salinity"),
572
+ }
573
+
574
+
575
+ class ArgoGeoTIFFGriddedPatchDataset(Dataset):
576
+ """Dataset that lazily reads training patches from exported GeoTIFF stores."""
577
+
578
+ DEFAULT_CONFIG_PATH = DEFAULT_CONFIG_PATH
579
+ DEFAULT_GEOTIFF_ROOT_DIR = DEFAULT_DATASET_ROOT_DIR.as_posix()
580
+ DEFAULT_METADATA_CACHE_DIR = (
581
+ DEFAULT_DATASET_ROOT_DIR / "depthdif_cache"
582
+ ).as_posix()
583
+
584
+ def __init__(
585
+ self,
586
+ *,
587
+ geotiff_root_dir: str | Path = DEFAULT_GEOTIFF_ROOT_DIR,
588
+ metadata_cache_dir: str | Path | None = DEFAULT_METADATA_CACHE_DIR,
589
+ split: str = "all",
590
+ tile_size: int = 128,
591
+ resolution_deg: float = 0.1,
592
+ patch_grid_source: str = "land_mask",
593
+ land_mask_path: str | Path | None = None,
594
+ patch_stride: int | None = None,
595
+ max_land_fraction: float = 0.30,
596
+ force_include_regions: Sequence[dict[str, Any]] | None = None,
597
+ finetune_sampling: dict[str, Any] | None = None,
598
+ temporal_window_days: int = 7,
599
+ glorys_var_name: str = "thetao",
600
+ ostia_var_name: str = "analysed_sst",
601
+ eo_source: str = "ostia",
602
+ eo_var_name: str | None = None,
603
+ require_argo_for_train: bool = True,
604
+ require_argo_for_val: bool = True,
605
+ require_argo_for_all: bool = False,
606
+ synthetic_mode: bool = False,
607
+ synthetic_pixel_count: int = 250,
608
+ return_info: bool = True,
609
+ return_coords: bool = True,
610
+ include_salinity: bool = False,
611
+ output_fields: Sequence[str] | str | None = None,
612
+ date_start: int | str | None = None,
613
+ date_end: int | str | None = None,
614
+ max_dates: int | None = None,
615
+ count_argo_support: bool | None = None,
616
+ random_seed: int = 7,
617
+ cache_size: int = 8,
618
+ val_fraction: float = 0.2,
619
+ val_year: int | None = None,
620
+ ) -> None:
621
+ """Initialize the GeoTIFF-backed patch dataset."""
622
+ self.split = str(split).strip().lower()
623
+ if self.split not in {"all", "train", "val"}:
624
+ raise ValueError("split must be one of: 'all', 'train', 'val'")
625
+ self.root_dir = Path(geotiff_root_dir)
626
+ self.manifest_path = self.root_dir / "manifest.yaml"
627
+ if not self.manifest_path.exists():
628
+ raise FileNotFoundError(
629
+ f"GeoTIFF manifest does not exist: {self.manifest_path}"
630
+ )
631
+ with self.manifest_path.open("r", encoding="utf-8") as f:
632
+ self.manifest = yaml.safe_load(f)
633
+
634
+ self.tile_size = int(tile_size)
635
+ self.resolution_deg = float(resolution_deg)
636
+ self.patch_grid_source = str(patch_grid_source)
637
+ manifest_grid = self.manifest.get("grid", {})
638
+ configured_land_mask = (
639
+ land_mask_path
640
+ or manifest_grid.get("source")
641
+ or DEFAULT_LAND_MASK_RELATIVE_PATH
642
+ )
643
+ self.land_mask_path = _resolve_land_mask_path(
644
+ self.root_dir,
645
+ configured_land_mask,
646
+ )
647
+ self.patch_stride = None if patch_stride is None else int(patch_stride)
648
+ self.max_land_fraction = float(max_land_fraction)
649
+ self.force_include_regions = _parse_force_include_regions(force_include_regions)
650
+ self.finetune_sampling = self._normalize_finetune_sampling(finetune_sampling)
651
+ self.finetune_sampling_summary: dict[str, Any] = {
652
+ "enabled": bool(self.finetune_sampling["enabled"]),
653
+ "applied": False,
654
+ "split": self.split,
655
+ }
656
+ self.temporal_window_days = int(temporal_window_days)
657
+ self.glorys_var_name = str(glorys_var_name)
658
+ self.ostia_var_name = str(ostia_var_name)
659
+ self.eo_source, self.eo_var_name = self._normalize_eo_selection(
660
+ eo_source=eo_source,
661
+ eo_var_name=eo_var_name,
662
+ ostia_var_name=self.ostia_var_name,
663
+ )
664
+ self.eo_stretch_name, self.eo_normalization = self._resolve_eo_metadata(
665
+ self.eo_source, self.eo_var_name
666
+ )
667
+ self.return_info = bool(return_info)
668
+ self.return_coords = bool(return_coords)
669
+ self.output_fields = self._normalize_output_fields(
670
+ output_fields, include_salinity=bool(include_salinity)
671
+ )
672
+ self.include_salinity = "salinity" in self.output_fields
673
+ self._loads_temperature = "temperature" in self.output_fields
674
+ self.random_seed = int(random_seed)
675
+ self.require_argo_for_train = bool(require_argo_for_train)
676
+ self.require_argo_for_val = bool(require_argo_for_val)
677
+ self.require_argo_for_all = bool(require_argo_for_all)
678
+ self.synthetic_mode = bool(synthetic_mode)
679
+ self.synthetic_pixel_count = int(synthetic_pixel_count)
680
+ self.date_start = self._optional_int(date_start)
681
+ self.date_end = self._optional_int(date_end)
682
+ self.max_dates = None if max_dates is None else int(max_dates)
683
+ if self.temporal_window_days < 1:
684
+ raise ValueError("sampling.temporal_window_days must be >= 1.")
685
+ if self.synthetic_pixel_count < 0:
686
+ raise ValueError("synthetic.pixel_count must be >= 0.")
687
+ if self.max_dates is not None and self.max_dates < 1:
688
+ raise ValueError("max_dates must be >= 1 when provided.")
689
+ if (
690
+ self.date_start is not None
691
+ and self.date_end is not None
692
+ and int(self.date_start) > int(self.date_end)
693
+ ):
694
+ raise ValueError("date_start must be <= date_end.")
695
+
696
+ self.raster_cache = RasterDatasetCache(max_open=cache_size)
697
+ self._depth_axis_m = np.asarray(
698
+ self.manifest.get("depth_axis_m", ()), dtype=np.float32
699
+ ).reshape(-1)
700
+ if self._depth_axis_m.size == 0:
701
+ raise RuntimeError("GeoTIFF manifest is missing depth_axis_m.")
702
+
703
+ self.argo_store = self._open_argo_store()
704
+ if self.argo_store is not None and int(
705
+ self.argo_store.depth_axis_m.size
706
+ ) != int(self._depth_axis_m.size):
707
+ raise RuntimeError(
708
+ "ARGO profile zarr depth axis does not match GeoTIFF manifest depth_axis_m."
709
+ )
710
+
711
+ self.glorys_store, self.salinity_store, self.eo_store = (
712
+ self._build_raster_stores()
713
+ )
714
+ # Backward-compatible alias for callers that still inspect the old name.
715
+ self.ostia_store = self.eo_store
716
+ self.available_dates = self._filter_available_dates(
717
+ sorted(self.glorys_store.dates & self.eo_store.dates)
718
+ )
719
+ if not self.available_dates:
720
+ raise RuntimeError("No overlapping GeoTIFF raster dates were found.")
721
+ self.count_argo_support = self._resolve_count_argo_support(count_argo_support)
722
+ if self._require_argo_for_current_split() and not self.count_argo_support:
723
+ raise ValueError(
724
+ "count_argo_support=False is incompatible with requiring ARGO "
725
+ "profiles for the current split."
726
+ )
727
+ if self.include_salinity:
728
+ if self.salinity_store is None:
729
+ raise RuntimeError("GeoTIFF salinity store was not initialized.")
730
+ missing_salinity_dates = sorted(
731
+ set(self.available_dates) - self.salinity_store.dates
732
+ )
733
+ if missing_salinity_dates:
734
+ raise RuntimeError(
735
+ "GeoTIFF manifest is missing GLORYS salinity 'so' rasters "
736
+ f"for dates: {missing_salinity_dates[:5]}"
737
+ )
738
+
739
+ grid_params = _GridParams(
740
+ tile_size=self.tile_size,
741
+ resolution_deg=self.resolution_deg,
742
+ invalid_threshold=0.5,
743
+ invalid_mask_flags=("land",),
744
+ val_fraction=float(val_fraction),
745
+ val_year=None if val_year is None else int(val_year),
746
+ split_seed=self.random_seed,
747
+ patch_grid_source=self.patch_grid_source,
748
+ land_mask_path=self.land_mask_path,
749
+ patch_stride=self.patch_stride,
750
+ max_land_fraction=self.max_land_fraction,
751
+ force_include_regions=self._effective_force_include_regions(),
752
+ )
753
+ index = GeoTIFFPatchIndex(
754
+ root_dir=self.root_dir,
755
+ dates=self.available_dates,
756
+ argo_store=self.argo_store if self.count_argo_support else None,
757
+ cache_dir=metadata_cache_dir,
758
+ grid_params=grid_params,
759
+ )
760
+ rows = index.load_rows()
761
+ rows = self._filter_rows(rows)
762
+ rows = self._apply_finetune_sampling(rows)
763
+ if not rows:
764
+ raise RuntimeError("Dataset is empty after split/ARGO filtering.")
765
+ self._rows = rows
766
+
767
+ def _filter_available_dates(self, dates: Sequence[int]) -> list[int]:
768
+ """Apply optional date-window controls before row indexing."""
769
+ filtered = [
770
+ int(date)
771
+ for date in dates
772
+ if (self.date_start is None or int(date) >= int(self.date_start))
773
+ and (self.date_end is None or int(date) <= int(self.date_end))
774
+ ]
775
+ if self.max_dates is not None:
776
+ filtered = filtered[: int(self.max_dates)]
777
+ return filtered
778
+
779
+ def _resolve_count_argo_support(self, value: bool | None) -> bool:
780
+ """Decide whether to compute profile counts during index creation."""
781
+ if value is not None:
782
+ return bool(value)
783
+ # The profile-count pass scans the compact ARGO store. Keep first use of
784
+ # downloaded checkouts fast unless this split filters by ARGO support.
785
+ return bool(self._require_argo_for_current_split())
786
+
787
+ @staticmethod
788
+ def _normalize_eo_selection(
789
+ *,
790
+ eo_source: str,
791
+ eo_var_name: str | None,
792
+ ostia_var_name: str,
793
+ ) -> tuple[str, str]:
794
+ """Resolve the dense surface EO raster group and variable."""
795
+ source = str(eo_source or "ostia").strip().lower()
796
+ if not source:
797
+ source = "ostia"
798
+ var_name = eo_var_name
799
+ if var_name is None:
800
+ var_name = (
801
+ ostia_var_name if source == "ostia" else EO_SOURCE_DEFAULTS.get(source)
802
+ )
803
+ if var_name is None or not str(var_name).strip():
804
+ raise ValueError(f"No EO variable configured for source {source!r}.")
805
+ return source, str(var_name).strip()
806
+
807
+ @staticmethod
808
+ def _resolve_eo_metadata(eo_source: str, eo_var_name: str) -> tuple[str, str]:
809
+ """Return manifest stretch and normalization family for one EO raster."""
810
+ key = (str(eo_source).strip().lower(), str(eo_var_name).strip())
811
+ metadata = EO_STRETCH_BY_SOURCE_VAR.get(key)
812
+ if metadata is None:
813
+ supported = ", ".join(
814
+ f"{source}/{var}" for source, var in sorted(EO_STRETCH_BY_SOURCE_VAR)
815
+ )
816
+ raise ValueError(
817
+ "Unsupported EO raster selection "
818
+ f"{key[0]!r}/{key[1]!r}. Supported selections: {supported}."
819
+ )
820
+ return metadata
821
+
822
+ def _open_argo_store(self) -> ArgoGeoTIFFProfileStore | None:
823
+ """Open the optional compact ARGO zarr profile store."""
824
+ argo_info = self.manifest.get("argo", {})
825
+ raw_path = argo_info.get("path")
826
+ if raw_path is None or str(raw_path).strip().lower() in MISSING_TEXT_VALUES:
827
+ return None
828
+ return ArgoGeoTIFFProfileStore(
829
+ _resolve_manifest_path(self.root_dir, raw_path),
830
+ include_salinity=self.include_salinity,
831
+ )
832
+
833
+ def _build_raster_stores(
834
+ self,
835
+ ) -> tuple[GeoTIFFRasterStore, GeoTIFFRasterStore | None, GeoTIFFRasterStore]:
836
+ """Build date-indexed dense raster stores from manifest entries."""
837
+ rasters = self.manifest.get("rasters", {})
838
+ stretch = self.manifest.get("stretch", {})
839
+ temp_stretch = stretch.get("temperature_kelvin")
840
+ if not isinstance(temp_stretch, dict):
841
+ raise RuntimeError(
842
+ "GeoTIFF manifest is missing temperature_kelvin stretch."
843
+ )
844
+ eo_stretch = stretch.get(self.eo_stretch_name)
845
+ if not isinstance(eo_stretch, dict):
846
+ raise RuntimeError(
847
+ "GeoTIFF manifest is missing EO stretch "
848
+ f"{self.eo_stretch_name!r} for {self.eo_source}/{self.eo_var_name}."
849
+ )
850
+ glorys_rasters = rasters.get("glorys", {})
851
+ glorys_entries = (
852
+ glorys_rasters.get(self.glorys_var_name, [])
853
+ if isinstance(glorys_rasters, dict)
854
+ else []
855
+ )
856
+ eo_rasters = rasters.get(self.eo_source, {})
857
+ eo_entries = (
858
+ eo_rasters.get(self.eo_var_name, []) if isinstance(eo_rasters, dict) else []
859
+ )
860
+ if not glorys_entries or not eo_entries:
861
+ raise RuntimeError(
862
+ "GeoTIFF manifest is missing GLORYS/EO raster entries for "
863
+ f"{self.glorys_var_name!r}/{self.eo_source}/{self.eo_var_name}."
864
+ )
865
+ salinity_store = None
866
+ if self.include_salinity:
867
+ salinity_stretch = stretch.get("salinity")
868
+ if not isinstance(salinity_stretch, dict):
869
+ raise RuntimeError("GeoTIFF manifest is missing salinity stretch.")
870
+ salinity_entries = (
871
+ glorys_rasters.get("so", []) if isinstance(glorys_rasters, dict) else []
872
+ )
873
+ if not salinity_entries:
874
+ raise RuntimeError(
875
+ "GeoTIFF manifest is missing GLORYS salinity 'so' raster entries."
876
+ )
877
+ salinity_store = GeoTIFFRasterStore(
878
+ paths_by_date=_records_by_date(salinity_entries, self.root_dir),
879
+ stretch=salinity_stretch,
880
+ cache=self.raster_cache,
881
+ kelvin_temperature=False,
882
+ )
883
+ return (
884
+ GeoTIFFRasterStore(
885
+ paths_by_date=_records_by_date(glorys_entries, self.root_dir),
886
+ stretch=temp_stretch,
887
+ cache=self.raster_cache,
888
+ kelvin_temperature=True,
889
+ ),
890
+ salinity_store,
891
+ GeoTIFFRasterStore(
892
+ paths_by_date=_records_by_date(eo_entries, self.root_dir),
893
+ stretch=eo_stretch,
894
+ cache=self.raster_cache,
895
+ kelvin_temperature=self.eo_normalization == "temperature",
896
+ ),
897
+ )
898
+
899
+ @property
900
+ def rows(self) -> list[dict[str, Any]]:
901
+ """Return patch/date metadata rows."""
902
+ return self._rows
903
+
904
+ @property
905
+ def depth_axis_m(self) -> np.ndarray:
906
+ """Return the GLORYS depth axis in meters."""
907
+ return self._depth_axis_m.copy()
908
+
909
+ @classmethod
910
+ def from_config(
911
+ cls,
912
+ config_path: str | Path | None = None,
913
+ *,
914
+ split: str = "all",
915
+ dataset_overrides: dict[str, Any] | None = None,
916
+ ) -> "ArgoGeoTIFFGriddedPatchDataset":
917
+ """Build a GeoTIFF dataset from a YAML data config."""
918
+ if config_path is None:
919
+ config_path = cls.DEFAULT_CONFIG_PATH
920
+ config_path = Path(config_path).expanduser()
921
+ if not config_path.is_absolute():
922
+ config_path = (DEFAULT_DATASET_ROOT_DIR / config_path).resolve()
923
+ with config_path.open("r", encoding="utf-8") as f:
924
+ cfg = yaml.safe_load(f)
925
+
926
+ ds_cfg = cfg.get("data", cfg).get("dataset", {})
927
+ if dataset_overrides:
928
+ ds_cfg = _deep_update_config(ds_cfg, dataset_overrides)
929
+ return cls(
930
+ geotiff_root_dir=cls._cfg_get(
931
+ ds_cfg,
932
+ "core.geotiff_root_dir",
933
+ "geotiff_root_dir",
934
+ default=cls.DEFAULT_GEOTIFF_ROOT_DIR,
935
+ ),
936
+ metadata_cache_dir=cls._cfg_get(
937
+ ds_cfg,
938
+ "core.metadata_cache_dir",
939
+ "metadata_cache_dir",
940
+ default=cls.DEFAULT_METADATA_CACHE_DIR,
941
+ ),
942
+ split=split,
943
+ tile_size=int(
944
+ cls._cfg_get(ds_cfg, "grid.tile_size", "tile_size", default=128)
945
+ ),
946
+ resolution_deg=float(
947
+ cls._cfg_get(
948
+ ds_cfg, "grid.resolution_deg", "resolution_deg", default=0.1
949
+ )
950
+ ),
951
+ patch_grid_source=str(
952
+ cls._cfg_get(
953
+ ds_cfg,
954
+ "grid.patch_grid_source",
955
+ "patch_grid_source",
956
+ default="land_mask",
957
+ )
958
+ ),
959
+ land_mask_path=cls._cfg_get(
960
+ ds_cfg,
961
+ "grid.land_mask_path",
962
+ "land_mask_path",
963
+ default=None,
964
+ ),
965
+ patch_stride=cls._optional_int(
966
+ cls._cfg_get(
967
+ ds_cfg,
968
+ "grid.patch_stride",
969
+ "patch_stride",
970
+ default=None,
971
+ )
972
+ ),
973
+ max_land_fraction=float(
974
+ cls._cfg_get(
975
+ ds_cfg,
976
+ "grid.max_land_fraction",
977
+ "max_land_fraction",
978
+ default=0.30,
979
+ )
980
+ ),
981
+ force_include_regions=cls._cfg_get(
982
+ ds_cfg,
983
+ "grid.force_include_regions",
984
+ "force_include_regions",
985
+ default=None,
986
+ ),
987
+ finetune_sampling=cls._cfg_get(
988
+ ds_cfg,
989
+ "finetune_sampling",
990
+ "finetune_sampling",
991
+ default=None,
992
+ ),
993
+ temporal_window_days=int(
994
+ cls._cfg_get(
995
+ ds_cfg,
996
+ "sampling.temporal_window_days",
997
+ "temporal_window_days",
998
+ default=7,
999
+ )
1000
+ ),
1001
+ glorys_var_name=str(
1002
+ cls._cfg_get(
1003
+ ds_cfg,
1004
+ "sampling.glorys_var_name",
1005
+ "glorys_var_name",
1006
+ default="thetao",
1007
+ )
1008
+ ),
1009
+ ostia_var_name=str(
1010
+ cls._cfg_get(
1011
+ ds_cfg,
1012
+ "sampling.ostia_var_name",
1013
+ "ostia_var_name",
1014
+ default="analysed_sst",
1015
+ )
1016
+ ),
1017
+ eo_source=str(
1018
+ cls._cfg_get(
1019
+ ds_cfg,
1020
+ "sampling.eo_source",
1021
+ "eo_source",
1022
+ default="ostia",
1023
+ )
1024
+ ),
1025
+ eo_var_name=cls._cfg_get(
1026
+ ds_cfg,
1027
+ "sampling.eo_var_name",
1028
+ "eo_var_name",
1029
+ default=None,
1030
+ ),
1031
+ val_fraction=float(cfg.get("split", {}).get("val_fraction", 0.2)),
1032
+ val_year=cls._optional_int(cfg.get("split", {}).get("val_year", None)),
1033
+ date_start=cls._cfg_get(
1034
+ ds_cfg, "sampling.date_start", "date_start", default=None
1035
+ ),
1036
+ date_end=cls._cfg_get(
1037
+ ds_cfg, "sampling.date_end", "date_end", default=None
1038
+ ),
1039
+ max_dates=cls._optional_int(
1040
+ cls._cfg_get(ds_cfg, "sampling.max_dates", "max_dates", default=None)
1041
+ ),
1042
+ count_argo_support=cls._optional_bool(
1043
+ cls._cfg_get(
1044
+ ds_cfg,
1045
+ "selection.count_argo_support",
1046
+ "count_argo_support",
1047
+ default=None,
1048
+ )
1049
+ ),
1050
+ require_argo_for_train=bool(
1051
+ cls._cfg_get(
1052
+ ds_cfg,
1053
+ "selection.require_argo_for_train",
1054
+ "require_argo_for_train",
1055
+ default=True,
1056
+ )
1057
+ ),
1058
+ require_argo_for_val=bool(
1059
+ cls._cfg_get(
1060
+ ds_cfg,
1061
+ "selection.require_argo_for_val",
1062
+ "require_argo_for_val",
1063
+ default=True,
1064
+ )
1065
+ ),
1066
+ require_argo_for_all=bool(
1067
+ cls._cfg_get(
1068
+ ds_cfg,
1069
+ "selection.require_argo_for_all",
1070
+ "require_argo_for_all",
1071
+ default=False,
1072
+ )
1073
+ ),
1074
+ synthetic_mode=bool(
1075
+ cls._cfg_get(
1076
+ ds_cfg, "synthetic.enabled", "synthetic_enabled", default=False
1077
+ )
1078
+ ),
1079
+ synthetic_pixel_count=int(
1080
+ cls._cfg_get(
1081
+ ds_cfg,
1082
+ "synthetic.pixel_count",
1083
+ "synthetic_pixel_count",
1084
+ default=250,
1085
+ )
1086
+ ),
1087
+ return_info=bool(
1088
+ cls._cfg_get(ds_cfg, "output.return_info", "return_info", default=True)
1089
+ ),
1090
+ return_coords=bool(
1091
+ cls._cfg_get(
1092
+ ds_cfg, "output.return_coords", "return_coords", default=True
1093
+ )
1094
+ ),
1095
+ include_salinity=bool(
1096
+ cls._cfg_get(
1097
+ ds_cfg,
1098
+ "output.include_salinity",
1099
+ "include_salinity",
1100
+ default=False,
1101
+ )
1102
+ ),
1103
+ output_fields=cls._cfg_get(
1104
+ ds_cfg, "output.fields", "output_fields", default=None
1105
+ ),
1106
+ random_seed=int(
1107
+ cls._cfg_get(ds_cfg, "runtime.random_seed", "random_seed", default=7)
1108
+ ),
1109
+ cache_size=int(
1110
+ cls._cfg_get(ds_cfg, "runtime.cache_size", "cache_size", default=8)
1111
+ ),
1112
+ )
1113
+
1114
+ @staticmethod
1115
+ def _cfg_get(
1116
+ cfg: dict[str, Any],
1117
+ nested_key: str,
1118
+ flat_key: str,
1119
+ *,
1120
+ default: Any,
1121
+ ) -> Any:
1122
+ """Read nested config values while keeping flat-key compatibility."""
1123
+ node: Any = cfg
1124
+ for part in nested_key.split("."):
1125
+ if not isinstance(node, dict) or part not in node:
1126
+ node = None
1127
+ break
1128
+ node = node[part]
1129
+ if node is not None:
1130
+ return node
1131
+ _ = flat_key
1132
+ return default
1133
+
1134
+ @staticmethod
1135
+ def _normalize_output_fields(
1136
+ output_fields: Sequence[str] | str | None,
1137
+ *,
1138
+ include_salinity: bool,
1139
+ ) -> tuple[str, ...]:
1140
+ """Resolve physical fields loaded for each dataset sample."""
1141
+ if output_fields is None:
1142
+ return ("temperature", "salinity") if include_salinity else ("temperature",)
1143
+ if isinstance(output_fields, str):
1144
+ fields = (output_fields,)
1145
+ else:
1146
+ fields = tuple(str(field) for field in output_fields)
1147
+ normalized = tuple(field.strip().lower() for field in fields if field.strip())
1148
+ if not normalized:
1149
+ raise ValueError("dataset.output.fields must contain at least one field.")
1150
+ unsupported = sorted(set(normalized) - {"temperature", "salinity"})
1151
+ if unsupported:
1152
+ raise ValueError(
1153
+ "dataset.output.fields contains unsupported fields: "
1154
+ f"{unsupported}. Supported fields are: temperature, salinity."
1155
+ )
1156
+ if len(set(normalized)) != len(normalized):
1157
+ raise ValueError("dataset.output.fields cannot contain duplicates.")
1158
+ return normalized
1159
+
1160
+ @staticmethod
1161
+ def _optional_bool(value: Any) -> bool | None:
1162
+ """Parse nullable boolean config values."""
1163
+ if value is None:
1164
+ return None
1165
+ if isinstance(value, str):
1166
+ normalized = value.strip().lower()
1167
+ if normalized in MISSING_TEXT_VALUES:
1168
+ return None
1169
+ if normalized in {"true", "yes", "on", "1"}:
1170
+ return True
1171
+ if normalized in {"false", "no", "off", "0"}:
1172
+ return False
1173
+ if isinstance(value, bool):
1174
+ return value
1175
+ raise ValueError(f"Expected a nullable boolean value, got {value!r}.")
1176
+
1177
+ @staticmethod
1178
+ def _optional_int(value: Any) -> int | None:
1179
+ """Parse nullable integer config values."""
1180
+ if value is None:
1181
+ return None
1182
+ if isinstance(value, str) and value.strip().lower() in MISSING_TEXT_VALUES:
1183
+ return None
1184
+ return int(value)
1185
+
1186
+ @staticmethod
1187
+ def _normalize_finetune_sampling(raw_cfg: dict[str, Any] | None) -> dict[str, Any]:
1188
+ """Normalize optional hard-area finetuning row-sampling settings."""
1189
+ cfg = dict(raw_cfg or {})
1190
+ hard_fraction = float(cfg.get("hard_fraction", 0.75))
1191
+ if not (0.0 < hard_fraction <= 1.0):
1192
+ raise ValueError("finetune_sampling.hard_fraction must be in (0, 1].")
1193
+ default_max_land_fraction = float(cfg.get("default_max_land_fraction", 0.85))
1194
+ if not (0.0 <= default_max_land_fraction <= 1.0):
1195
+ raise ValueError(
1196
+ "finetune_sampling.default_max_land_fraction must be in [0, 1]."
1197
+ )
1198
+
1199
+ raw_splits = cfg.get("apply_to_splits", ("train",))
1200
+ if isinstance(raw_splits, str):
1201
+ apply_to_splits = (raw_splits.strip().lower(),)
1202
+ else:
1203
+ apply_to_splits = tuple(str(value).strip().lower() for value in raw_splits)
1204
+ if not apply_to_splits or any(
1205
+ value not in {"all", "train", "val"} for value in apply_to_splits
1206
+ ):
1207
+ raise ValueError(
1208
+ "finetune_sampling.apply_to_splits must contain split names from "
1209
+ "{'all', 'train', 'val'}."
1210
+ )
1211
+
1212
+ hard_regions: list[dict[str, Any]] = []
1213
+ for idx, raw_region in enumerate(cfg.get("hard_regions", ()) or ()):
1214
+ if not isinstance(raw_region, dict):
1215
+ raise ValueError(
1216
+ "Each finetune_sampling.hard_regions item must be a mapping."
1217
+ )
1218
+ region = dict(raw_region)
1219
+ region["name"] = str(region.get("name", f"hard_region_{idx}"))
1220
+ region["lon_min"] = float(region["lon_min"])
1221
+ region["lon_max"] = float(region["lon_max"])
1222
+ region["lat_min"] = float(region["lat_min"])
1223
+ region["lat_max"] = float(region["lat_max"])
1224
+ region["max_land_fraction"] = float(
1225
+ region.get("max_land_fraction", default_max_land_fraction)
1226
+ )
1227
+ if not (0.0 <= region["max_land_fraction"] <= 1.0):
1228
+ raise ValueError(
1229
+ "finetune_sampling.hard_regions[].max_land_fraction must be "
1230
+ "in [0, 1]."
1231
+ )
1232
+ hard_regions.append(region)
1233
+
1234
+ return {
1235
+ "enabled": bool(cfg.get("enabled", False)),
1236
+ "hard_fraction": hard_fraction,
1237
+ "apply_to_splits": apply_to_splits,
1238
+ "relax_land_filter": bool(cfg.get("relax_land_filter", True)),
1239
+ "default_max_land_fraction": default_max_land_fraction,
1240
+ "hard_regions": tuple(hard_regions),
1241
+ }
1242
+
1243
+ def _finetune_applies_to_current_split(self) -> bool:
1244
+ """Return whether hard-area finetuning should filter this split."""
1245
+ if not bool(self.finetune_sampling["enabled"]):
1246
+ return False
1247
+ apply_to_splits = set(self.finetune_sampling["apply_to_splits"])
1248
+ return "all" in apply_to_splits or self.split in apply_to_splits
1249
+
1250
+ def _effective_force_include_regions(self) -> tuple[Any, ...]:
1251
+ """Return force-include regions, extended by finetune boxes when needed."""
1252
+ if not (
1253
+ self._finetune_applies_to_current_split()
1254
+ and bool(self.finetune_sampling["relax_land_filter"])
1255
+ ):
1256
+ return self.force_include_regions
1257
+
1258
+ merged = {region.name: region for region in self.force_include_regions}
1259
+ for raw_region in self.finetune_sampling["hard_regions"]:
1260
+ parsed_region = _parse_force_include_regions([raw_region])[0]
1261
+ existing = merged.get(parsed_region.name)
1262
+ if existing is not None:
1263
+ # Duplicate named boxes keep the most permissive finetune land cap.
1264
+ parsed_region = parsed_region.__class__(
1265
+ name=parsed_region.name,
1266
+ lon_min=parsed_region.lon_min,
1267
+ lon_max=parsed_region.lon_max,
1268
+ lat_min=parsed_region.lat_min,
1269
+ lat_max=parsed_region.lat_max,
1270
+ max_land_fraction=max(
1271
+ float(existing.max_land_fraction),
1272
+ float(parsed_region.max_land_fraction),
1273
+ ),
1274
+ )
1275
+ merged[parsed_region.name] = parsed_region
1276
+ return tuple(merged.values())
1277
+
1278
+ @staticmethod
1279
+ def _row_in_hard_region(
1280
+ row: dict[str, Any], regions: Sequence[dict[str, Any]]
1281
+ ) -> bool:
1282
+ """Return whether a patch center falls inside any hard finetune box."""
1283
+ lat_center = float(row.get("lat_center", np.nan))
1284
+ lon_center = _normalize_lon(float(row.get("lon_center", np.nan)))
1285
+ if not (np.isfinite(lat_center) and np.isfinite(lon_center)):
1286
+ return False
1287
+ for region in regions:
1288
+ lat_min = min(float(region["lat_min"]), float(region["lat_max"]))
1289
+ lat_max = max(float(region["lat_min"]), float(region["lat_max"]))
1290
+ lon_min = min(float(region["lon_min"]), float(region["lon_max"]))
1291
+ lon_max = max(float(region["lon_min"]), float(region["lon_max"]))
1292
+ if lat_min <= lat_center <= lat_max and lon_min <= lon_center <= lon_max:
1293
+ return True
1294
+ return False
1295
+
1296
+ def _apply_finetune_sampling(
1297
+ self, rows: list[dict[str, Any]]
1298
+ ) -> list[dict[str, Any]]:
1299
+ """Apply deterministic hard/easy row filtering for finetuning runs."""
1300
+ if not self._finetune_applies_to_current_split():
1301
+ self.finetune_sampling_summary = {
1302
+ "enabled": bool(self.finetune_sampling["enabled"]),
1303
+ "applied": False,
1304
+ "split": self.split,
1305
+ "total_rows": len(rows),
1306
+ }
1307
+ return rows
1308
+
1309
+ regions = self.finetune_sampling["hard_regions"]
1310
+ hard_indices = [
1311
+ idx
1312
+ for idx, row in enumerate(rows)
1313
+ if self._row_in_hard_region(row, regions)
1314
+ ]
1315
+ if not hard_indices:
1316
+ raise RuntimeError(
1317
+ "Finetune hard-area sampling matched no rows for split "
1318
+ f"{self.split!r}. Check data.dataset.finetune_sampling.hard_regions."
1319
+ )
1320
+
1321
+ hard_fraction = float(self.finetune_sampling["hard_fraction"])
1322
+ hard_index_set = set(hard_indices)
1323
+ easy_indices = [idx for idx in range(len(rows)) if idx not in hard_index_set]
1324
+ requested_easy = int(
1325
+ round(len(hard_indices) * (1.0 - hard_fraction) / hard_fraction)
1326
+ )
1327
+ selected_easy: list[int] = []
1328
+ if requested_easy > 0 and easy_indices:
1329
+ sample_count = min(int(requested_easy), len(easy_indices))
1330
+ rng = np.random.default_rng(int(self.random_seed))
1331
+ selected_easy = sorted(
1332
+ int(value)
1333
+ for value in rng.choice(easy_indices, size=sample_count, replace=False)
1334
+ )
1335
+
1336
+ selected_indices = sorted(hard_indices + selected_easy)
1337
+ filtered_rows = [rows[idx] for idx in selected_indices]
1338
+ actual_hard_fraction = len(hard_indices) / float(len(filtered_rows))
1339
+ self.finetune_sampling_summary = {
1340
+ "enabled": True,
1341
+ "applied": True,
1342
+ "split": self.split,
1343
+ "target_hard_fraction": hard_fraction,
1344
+ "actual_hard_fraction": actual_hard_fraction,
1345
+ "hard_rows": len(hard_indices),
1346
+ "easy_rows": len(selected_easy),
1347
+ "total_rows": len(filtered_rows),
1348
+ "available_easy_rows": len(easy_indices),
1349
+ "region_names": [str(region["name"]) for region in regions],
1350
+ }
1351
+ return filtered_rows
1352
+
1353
+ def _filter_rows(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
1354
+ """Apply split and ARGO-support filters."""
1355
+ if self.split in {"train", "val"}:
1356
+ rows = [
1357
+ row
1358
+ for row in rows
1359
+ if str(row.get("split", row.get("phase", ""))).strip().lower()
1360
+ == self.split
1361
+ ]
1362
+ require_argo = self._require_argo_for_current_split()
1363
+ if require_argo:
1364
+ rows = [row for row in rows if int(row.get("argo_profile_count", 0)) > 0]
1365
+ return rows
1366
+
1367
+ def _require_argo_for_current_split(self) -> bool:
1368
+ """Return whether the current split requires sparse ARGO support."""
1369
+ if self.synthetic_mode:
1370
+ return False
1371
+ if self.split == "train":
1372
+ return self.require_argo_for_train
1373
+ if self.split == "val":
1374
+ return self.require_argo_for_val
1375
+ return self.require_argo_for_all
1376
+
1377
+ def __len__(self) -> int:
1378
+ """Return dataset row count."""
1379
+ return len(self._rows)
1380
+
1381
+ def _load_y_patch(self, row: dict[str, Any]) -> np.ndarray:
1382
+ """Load the dense GLORYS target patch."""
1383
+ y_np = self.glorys_store.read_patch(
1384
+ target_date=int(row["date"]),
1385
+ grid_y0=int(row["grid_y0"]),
1386
+ grid_x0=int(row["grid_x0"]),
1387
+ tile_size=self.tile_size,
1388
+ )
1389
+ if y_np.ndim != 3:
1390
+ raise RuntimeError(
1391
+ f"Expected GLORYS patch shape (D,H,W), got {tuple(y_np.shape)}"
1392
+ )
1393
+ if int(y_np.shape[0]) != int(self._depth_axis_m.size):
1394
+ raise RuntimeError(
1395
+ "GLORYS raster band count does not match manifest depth_axis_m: "
1396
+ f"{int(y_np.shape[0])} != {int(self._depth_axis_m.size)}"
1397
+ )
1398
+ return y_np.astype(np.float32, copy=False)
1399
+
1400
+ def _load_y_salinity_patch(self, row: dict[str, Any]) -> np.ndarray:
1401
+ """Load the dense GLORYS salinity target patch as raw PSU."""
1402
+ if self.salinity_store is None:
1403
+ raise RuntimeError("GeoTIFF salinity output is not enabled.")
1404
+ salinity_np = self.salinity_store.read_patch(
1405
+ target_date=int(row["date"]),
1406
+ grid_y0=int(row["grid_y0"]),
1407
+ grid_x0=int(row["grid_x0"]),
1408
+ tile_size=self.tile_size,
1409
+ )
1410
+ if salinity_np.ndim != 3:
1411
+ raise RuntimeError(
1412
+ "Expected GLORYS salinity patch shape (D,H,W), "
1413
+ f"got {tuple(salinity_np.shape)}"
1414
+ )
1415
+ if int(salinity_np.shape[0]) != int(self._depth_axis_m.size):
1416
+ raise RuntimeError(
1417
+ "GLORYS salinity raster band count does not match manifest "
1418
+ f"depth_axis_m: {int(salinity_np.shape[0])} != "
1419
+ f"{int(self._depth_axis_m.size)}"
1420
+ )
1421
+ return salinity_np.astype(np.float32, copy=False)
1422
+
1423
+ def _load_land_mask_patch(self, row: dict[str, Any]) -> np.ndarray:
1424
+ """Load the configured on-disk world-mask patch as an ocean mask."""
1425
+ src = self.raster_cache.get(self.land_mask_path)
1426
+ window = Window(
1427
+ col_off=int(row["grid_x0"]),
1428
+ row_off=int(row["grid_y0"]),
1429
+ width=int(self.tile_size),
1430
+ height=int(self.tile_size),
1431
+ )
1432
+ land_np = src.read(1, window=window)
1433
+ expected_shape = (int(self.tile_size), int(self.tile_size))
1434
+ if land_np.shape != expected_shape:
1435
+ raise RuntimeError(
1436
+ "Land-mask patch shape does not match dataset tile_size: "
1437
+ f"{tuple(land_np.shape)} != {expected_shape}"
1438
+ )
1439
+ # The world raster stores 1 for land, while model masks use 1 for ocean.
1440
+ return (np.asarray(land_np, dtype=np.float32) <= 0.5).astype(
1441
+ np.float32,
1442
+ copy=False,
1443
+ )[None, ...]
1444
+
1445
+ def _load_eo_patch(self, row: dict[str, Any]) -> np.ndarray:
1446
+ """Load the configured dense surface-context patch."""
1447
+ eo_np = self.eo_store.read_patch(
1448
+ target_date=int(row["date"]),
1449
+ grid_y0=int(row["grid_y0"]),
1450
+ grid_x0=int(row["grid_x0"]),
1451
+ tile_size=self.tile_size,
1452
+ )
1453
+ if eo_np.ndim == 3 and int(eo_np.shape[0]) == 1:
1454
+ eo_np = eo_np[0]
1455
+ if eo_np.ndim != 2:
1456
+ raise RuntimeError(
1457
+ f"Expected EO patch shape (H,W), got {tuple(eo_np.shape)}"
1458
+ )
1459
+ return eo_np.astype(np.float32, copy=False)[None, ...]
1460
+
1461
+ def _normalize_eo_tensor(self, tensor: torch.Tensor) -> torch.Tensor:
1462
+ """Normalize the EO channel according to its physical variable family."""
1463
+ if self.eo_normalization == "temperature":
1464
+ return temperature_normalize(mode="norm", tensor=tensor)
1465
+ if self.eo_normalization == "salinity":
1466
+ return salinity_normalize(mode="norm", tensor=tensor)
1467
+ raise RuntimeError(f"Unsupported EO normalization: {self.eo_normalization}")
1468
+
1469
+ def _spatial_support_from_valid_mask(
1470
+ self,
1471
+ valid_mask_np: np.ndarray,
1472
+ *,
1473
+ source_name: str,
1474
+ ) -> np.ndarray:
1475
+ """Collapse a per-band validity mask into one spatial ocean-support mask."""
1476
+ valid_np = np.asarray(valid_mask_np, dtype=bool)
1477
+ if valid_np.ndim == 3:
1478
+ spatial_mask = valid_np.any(axis=0, keepdims=True)
1479
+ elif valid_np.ndim == 2:
1480
+ spatial_mask = valid_np[None, ...]
1481
+ else:
1482
+ raise RuntimeError(
1483
+ f"{source_name} support must be shaped as (C,H,W) or (H,W), "
1484
+ f"got {tuple(valid_np.shape)}."
1485
+ )
1486
+ expected_shape = (1, int(self.tile_size), int(self.tile_size))
1487
+ if tuple(spatial_mask.shape) != expected_shape:
1488
+ raise RuntimeError(
1489
+ f"{source_name} support shape does not match dataset tile_size: "
1490
+ f"{tuple(spatial_mask.shape)} != {expected_shape}."
1491
+ )
1492
+ return spatial_mask.astype(np.float32, copy=False)
1493
+
1494
+ def _build_land_mask_patch(
1495
+ self,
1496
+ row: dict[str, Any],
1497
+ *,
1498
+ y_valid_mask_np: np.ndarray | None,
1499
+ eo_np: np.ndarray | None,
1500
+ ) -> np.ndarray:
1501
+ """Build one spatial ocean mask from GLORYS, EO, or the on-disk mask."""
1502
+ if y_valid_mask_np is not None:
1503
+ return self._spatial_support_from_valid_mask(
1504
+ y_valid_mask_np,
1505
+ source_name="GLORYS target",
1506
+ )
1507
+ if eo_np is not None:
1508
+ return self._spatial_support_from_valid_mask(
1509
+ np.isfinite(eo_np),
1510
+ source_name="EO surface context",
1511
+ )
1512
+ if self.land_mask_path.exists():
1513
+ return self._load_land_mask_patch(row)
1514
+ raise RuntimeError(
1515
+ "Could not build land_mask: GLORYS target support was unavailable, "
1516
+ "EO support was unavailable, and the configured on-disk land mask "
1517
+ f"does not exist: {self.land_mask_path}"
1518
+ )
1519
+
1520
+ def _empty_sparse_patch(self) -> tuple[np.ndarray, np.ndarray]:
1521
+ """Return an empty sparse profile patch and validity mask."""
1522
+ depth_size = int(self._depth_axis_m.size)
1523
+ shape = (depth_size, self.tile_size, self.tile_size)
1524
+ return np.full(shape, np.nan, dtype=np.float32), np.zeros(shape, dtype=bool)
1525
+
1526
+ def _rasterize_profile_values(
1527
+ self,
1528
+ row: dict[str, Any],
1529
+ indices: np.ndarray,
1530
+ values: np.ndarray,
1531
+ ) -> tuple[np.ndarray, np.ndarray]:
1532
+ """Rasterize selected profile values into one sparse patch."""
1533
+ depth_size = int(self._depth_axis_m.size)
1534
+ if indices.size == 0:
1535
+ return self._empty_sparse_patch()
1536
+ if values.ndim != 2 or int(values.shape[1]) != depth_size:
1537
+ raise RuntimeError(
1538
+ "ARGO profile values do not match manifest depth_axis_m: "
1539
+ f"{tuple(values.shape)}"
1540
+ )
1541
+
1542
+ value_sum = np.zeros(
1543
+ (depth_size, self.tile_size, self.tile_size), dtype=np.float64
1544
+ )
1545
+ value_count = np.zeros(
1546
+ (depth_size, self.tile_size, self.tile_size), dtype=np.uint16
1547
+ )
1548
+ y0 = int(row["grid_y0"])
1549
+ x0 = int(row["grid_x0"])
1550
+ for local_idx, profile_idx in enumerate(indices.tolist()):
1551
+ row_idx = int(self.argo_store.grid_row[int(profile_idx)]) - y0
1552
+ col_idx = int(self.argo_store.grid_col[int(profile_idx)]) - x0
1553
+ if (
1554
+ row_idx < 0
1555
+ or row_idx >= self.tile_size
1556
+ or col_idx < 0
1557
+ or col_idx >= self.tile_size
1558
+ ):
1559
+ continue
1560
+ profile = values[int(local_idx)]
1561
+ valid = np.isfinite(profile)
1562
+ if not np.any(valid):
1563
+ continue
1564
+ # Multiple ARGO profiles can land on the same grid cell and depth.
1565
+ value_sum[valid, row_idx, col_idx] += profile[valid].astype(np.float64)
1566
+ value_count[valid, row_idx, col_idx] += 1
1567
+
1568
+ value_np = np.full(value_sum.shape, np.nan, dtype=np.float32)
1569
+ value_valid = value_count > 0
1570
+ value_np[value_valid] = (
1571
+ value_sum[value_valid] / value_count[value_valid].astype(np.float64)
1572
+ ).astype(
1573
+ np.float32,
1574
+ copy=False,
1575
+ )
1576
+ return value_np, value_valid
1577
+
1578
+ def _query_temperature_valid_argo_indices(self, row: dict[str, Any]) -> np.ndarray:
1579
+ """Return temperature-valid ARGO indices for the current patch."""
1580
+ if self.argo_store is None:
1581
+ return np.zeros((0,), dtype=np.int64)
1582
+ return self.argo_store.query_indices(
1583
+ target_date=int(row["date"]),
1584
+ grid_y0=int(row["grid_y0"]),
1585
+ grid_x0=int(row["grid_x0"]),
1586
+ tile_size=self.tile_size,
1587
+ )
1588
+
1589
+ def _rasterize_argo_patch(
1590
+ self, row: dict[str, Any]
1591
+ ) -> tuple[np.ndarray, np.ndarray]:
1592
+ """Rasterize compact ARGO temperature observations into one patch."""
1593
+ indices = self._query_temperature_valid_argo_indices(row)
1594
+ if indices.size == 0 or self.argo_store is None:
1595
+ return self._empty_sparse_patch()
1596
+ values = self.argo_store.load_temperature_profiles(indices)
1597
+ return self._rasterize_profile_values(row, indices, values)
1598
+
1599
+ def _rasterize_argo_salinity_patch(
1600
+ self, row: dict[str, Any]
1601
+ ) -> tuple[np.ndarray, np.ndarray]:
1602
+ """Rasterize compact ARGO salinity observations into one patch."""
1603
+ if not self.include_salinity:
1604
+ raise RuntimeError("ARGO salinity output is not enabled.")
1605
+ indices = self._query_temperature_valid_argo_indices(row)
1606
+ if indices.size == 0 or self.argo_store is None:
1607
+ return self._empty_sparse_patch()
1608
+ # Keep salinity on the same temperature-valid support used for filtering.
1609
+ values = self.argo_store.load_salinity_profiles(indices)
1610
+ return self._rasterize_profile_values(row, indices, values)
1611
+
1612
+ def _synthetic_rng_for_row(
1613
+ self,
1614
+ row: dict[str, Any],
1615
+ *,
1616
+ idx: int,
1617
+ ) -> np.random.Generator:
1618
+ """Build a deterministic synthetic-sampling RNG for one row."""
1619
+ seed = np.random.SeedSequence(
1620
+ [
1621
+ int(self.random_seed),
1622
+ int(row.get("patch_id", 0)),
1623
+ int(row.get("date", 0)),
1624
+ int(idx),
1625
+ ]
1626
+ )
1627
+ return np.random.default_rng(seed)
1628
+
1629
+ def _build_synthetic_x_from_glorys(
1630
+ self,
1631
+ y_np: np.ndarray,
1632
+ y_valid_mask_np: np.ndarray,
1633
+ row: dict[str, Any],
1634
+ *,
1635
+ idx: int,
1636
+ ) -> tuple[np.ndarray, np.ndarray]:
1637
+ """Build sparse synthetic observations by sampling the dense target."""
1638
+ x_np = np.full(y_np.shape, np.nan, dtype=np.float32)
1639
+ x_valid = np.zeros(y_valid_mask_np.shape, dtype=bool)
1640
+ if self.synthetic_pixel_count == 0:
1641
+ return x_np, x_valid
1642
+
1643
+ valid_columns = np.asarray(y_valid_mask_np, dtype=bool).any(axis=0)
1644
+ flat_valid_columns = np.flatnonzero(valid_columns.reshape(-1))
1645
+ if flat_valid_columns.size == 0:
1646
+ return x_np, x_valid
1647
+
1648
+ sample_count = min(
1649
+ int(self.synthetic_pixel_count), int(flat_valid_columns.size)
1650
+ )
1651
+ rng = self._synthetic_rng_for_row(row, idx=idx)
1652
+ selected = rng.choice(flat_valid_columns, size=sample_count, replace=False)
1653
+ row_indices, col_indices = np.unravel_index(selected, valid_columns.shape)
1654
+ for row_idx, col_idx in zip(row_indices.tolist(), col_indices.tolist()):
1655
+ depth_valid = y_valid_mask_np[:, int(row_idx), int(col_idx)]
1656
+ if not np.any(depth_valid):
1657
+ continue
1658
+ # Synthetic mode uses decoded dense target values as sparse input.
1659
+ x_np[depth_valid, int(row_idx), int(col_idx)] = y_np[
1660
+ depth_valid,
1661
+ int(row_idx),
1662
+ int(col_idx),
1663
+ ]
1664
+ x_valid[depth_valid, int(row_idx), int(col_idx)] = True
1665
+ return x_np, x_valid
1666
+
1667
+ def __getitem__(self, idx: int) -> dict[str, Any]:
1668
+ """Return one model-ready training sample."""
1669
+ row = self._rows[int(idx)]
1670
+ eo_np = self._load_eo_patch(row)
1671
+ temperature_payload: dict[str, torch.Tensor] | None = None
1672
+ salinity_payload: dict[str, torch.Tensor] | None = None
1673
+ land_support_np: np.ndarray | None = None
1674
+
1675
+ if self._loads_temperature:
1676
+ y_np = self._load_y_patch(row)
1677
+ y_valid_mask_np = np.isfinite(y_np)
1678
+ if self.synthetic_mode:
1679
+ x_np, x_valid_mask_np = self._build_synthetic_x_from_glorys(
1680
+ y_np,
1681
+ y_valid_mask_np,
1682
+ row,
1683
+ idx=int(idx),
1684
+ )
1685
+ else:
1686
+ x_np, x_valid_mask_np = self._rasterize_argo_patch(row)
1687
+
1688
+ x = temperature_normalize(mode="norm", tensor=torch.from_numpy(x_np))
1689
+ y = temperature_normalize(mode="norm", tensor=torch.from_numpy(y_np))
1690
+ x = torch.nan_to_num(x, nan=0.0, posinf=0.0, neginf=0.0)
1691
+ y = torch.nan_to_num(y, nan=0.0, posinf=0.0, neginf=0.0)
1692
+ x_valid_mask = torch.from_numpy(
1693
+ x_valid_mask_np.astype(np.bool_, copy=False)
1694
+ )
1695
+ y_valid_mask = torch.from_numpy(
1696
+ y_valid_mask_np.astype(np.bool_, copy=False)
1697
+ )
1698
+ temperature_payload = {
1699
+ "x": x,
1700
+ "y": y,
1701
+ "x_valid_mask": x_valid_mask,
1702
+ "y_valid_mask": y_valid_mask,
1703
+ "x_valid_mask_1d": x_valid_mask.any(dim=0, keepdim=True),
1704
+ }
1705
+ land_support_np = y_valid_mask_np
1706
+
1707
+ if self.include_salinity:
1708
+ y_salinity_np = self._load_y_salinity_patch(row)
1709
+ y_salinity_valid_mask_np = np.isfinite(y_salinity_np)
1710
+ if self.synthetic_mode:
1711
+ x_salinity_np, x_salinity_valid_mask_np = (
1712
+ self._build_synthetic_x_from_glorys(
1713
+ y_salinity_np,
1714
+ y_salinity_valid_mask_np,
1715
+ row,
1716
+ idx=int(idx),
1717
+ )
1718
+ )
1719
+ else:
1720
+ x_salinity_np, x_salinity_valid_mask_np = (
1721
+ self._rasterize_argo_salinity_patch(row)
1722
+ )
1723
+ x_salinity = salinity_normalize(
1724
+ mode="norm", tensor=torch.from_numpy(x_salinity_np)
1725
+ )
1726
+ y_salinity = salinity_normalize(
1727
+ mode="norm", tensor=torch.from_numpy(y_salinity_np)
1728
+ )
1729
+ x_salinity = torch.nan_to_num(x_salinity, nan=0.0, posinf=0.0, neginf=0.0)
1730
+ y_salinity = torch.nan_to_num(y_salinity, nan=0.0, posinf=0.0, neginf=0.0)
1731
+ x_salinity_valid_mask = torch.from_numpy(
1732
+ x_salinity_valid_mask_np.astype(np.bool_, copy=False)
1733
+ )
1734
+ y_salinity_valid_mask = torch.from_numpy(
1735
+ y_salinity_valid_mask_np.astype(np.bool_, copy=False)
1736
+ )
1737
+ salinity_payload = {
1738
+ "x_salinity": x_salinity,
1739
+ "y_salinity": y_salinity,
1740
+ "x_salinity_valid_mask": x_salinity_valid_mask,
1741
+ "y_salinity_valid_mask": y_salinity_valid_mask,
1742
+ "x_salinity_valid_mask_1d": x_salinity_valid_mask.any(
1743
+ dim=0, keepdim=True
1744
+ ),
1745
+ }
1746
+ if land_support_np is None:
1747
+ # Salinity-only runs should derive the spatial mask from salinity support.
1748
+ land_support_np = y_salinity_valid_mask_np
1749
+
1750
+ land_mask_np = self._build_land_mask_patch(
1751
+ row,
1752
+ y_valid_mask_np=land_support_np,
1753
+ eo_np=eo_np,
1754
+ )
1755
+ eo = self._normalize_eo_tensor(torch.from_numpy(eo_np))
1756
+ eo = torch.nan_to_num(eo, nan=0.0, posinf=0.0, neginf=0.0)
1757
+ sample: dict[str, Any] = {
1758
+ "eo": eo,
1759
+ "land_mask": torch.from_numpy(land_mask_np),
1760
+ "date": _parse_date_int(row.get("date", 19700115)),
1761
+ }
1762
+ if temperature_payload is not None:
1763
+ sample.update(temperature_payload)
1764
+ if salinity_payload is not None:
1765
+ sample.update(salinity_payload)
1766
+ if self.return_coords:
1767
+ sample["coords"] = torch.tensor(
1768
+ [
1769
+ 0.5 * (float(row["lat0"]) + float(row["lat1"])),
1770
+ _center_lon_deg(float(row["lon0"]), float(row["lon1"])),
1771
+ ],
1772
+ dtype=torch.float32,
1773
+ )
1774
+ if self.return_info:
1775
+ info = dict(row)
1776
+ info["x_source"] = "glorys_synthetic" if self.synthetic_mode else "argo"
1777
+ info["synthetic_pixel_count"] = (
1778
+ int(self.synthetic_pixel_count) if self.synthetic_mode else 0
1779
+ )
1780
+ sample["info"] = info
1781
+ return sample
depthdif_dataset/grid_utils.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Any, Sequence
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ import rasterio
11
+ from tqdm import tqdm
12
+
13
+ MISSING_TEXT_VALUES = frozenset({"", "__missing__", "nan", "none", "null"})
14
+ DEFAULT_DATASET_ROOT_DIR = Path(__file__).resolve().parents[1]
15
+ DEFAULT_LAND_MASK_PATH = str(
16
+ DEFAULT_DATASET_ROOT_DIR / "masks/world_land_mask_glorys_0p1.tif"
17
+ )
18
+
19
+
20
+ def resolve_package_path(path: str | Path) -> Path:
21
+ """Resolve paths relative to this Hugging Face dataset checkout."""
22
+ candidate = Path(path).expanduser()
23
+ if candidate.is_absolute():
24
+ return candidate
25
+ repo_relative = DEFAULT_DATASET_ROOT_DIR / candidate
26
+ if repo_relative.exists():
27
+ return repo_relative
28
+ return candidate
29
+
30
+
31
+ def _parse_date_int(value: Any) -> int:
32
+ """Parse a model date integer while avoiding leap-day calendar issues."""
33
+ raw = str(value).strip()
34
+ if raw.isdigit():
35
+ date_int = int(raw)
36
+ month = (date_int // 100) % 100
37
+ day = date_int % 100
38
+ # Keep dataset dates compatible with the model's fixed non-leap calendar.
39
+ if month == 2 and day == 29:
40
+ return date_int - 1
41
+ return date_int
42
+ return 20100101
43
+
44
+
45
+ def _normalize_lon(lon: float) -> float:
46
+ """Normalize longitude to the -180..180 degree range."""
47
+ return float(((float(lon) + 180.0) % 360.0) - 180.0)
48
+
49
+
50
+ def _center_lon_deg(lon0: float, lon1: float) -> float:
51
+ """Return the circular midpoint longitude in degrees."""
52
+ lon0_rad = np.deg2rad(lon0)
53
+ lon1_rad = np.deg2rad(lon1)
54
+ sin_sum = np.sin(lon0_rad) + np.sin(lon1_rad)
55
+ cos_sum = np.cos(lon0_rad) + np.cos(lon1_rad)
56
+ return float(np.rad2deg(np.arctan2(sin_sum, cos_sum)))
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class _ForceIncludeRegion:
61
+ """Named region that relaxes land-fraction filtering for patch centers."""
62
+
63
+ name: str
64
+ lon_min: float
65
+ lon_max: float
66
+ lat_min: float
67
+ lat_max: float
68
+ max_land_fraction: float
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class _GridParams:
73
+ """Patch-grid construction parameters shared by dataset backends."""
74
+
75
+ tile_size: int
76
+ resolution_deg: float
77
+ invalid_threshold: float
78
+ invalid_mask_flags: tuple[str, ...]
79
+ val_fraction: float
80
+ val_year: int | None
81
+ split_seed: int
82
+ patch_grid_source: str = "land_mask"
83
+ land_mask_path: str | Path | None = DEFAULT_LAND_MASK_PATH
84
+ patch_stride: int | None = None
85
+ max_land_fraction: float = 0.30
86
+ force_include_regions: tuple[_ForceIncludeRegion, ...] = ()
87
+
88
+ @property
89
+ def effective_patch_stride(self) -> int:
90
+ """Return the configured stride, defaulting to non-overlapping tiles."""
91
+ return int(self.tile_size if self.patch_stride is None else self.patch_stride)
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class _PatchGridLookup:
96
+ """Compact lookup from global pixel coordinates to retained patch ids."""
97
+
98
+ patch_by_start: dict[tuple[int, int], int]
99
+ y_starts: np.ndarray
100
+ x_starts: np.ndarray
101
+ grid_top: float
102
+ grid_left: float
103
+ tile_size: int
104
+ resolution_deg: float
105
+
106
+
107
+ def _sanitize_cache_text(value: Any) -> str:
108
+ """Sanitize arbitrary config text for use in cache filenames."""
109
+ text = str(value).strip().lower().replace("\\", "/")
110
+ for old, new in (("/", "-"), (".", "p"), (" ", ""), (":", "-")):
111
+ text = text.replace(old, new)
112
+ return text
113
+
114
+
115
+ def _path_cache_hash(path: str | Path | None) -> str:
116
+ """Return a short stable hash for a path-like cache key."""
117
+ if path is None:
118
+ return "none"
119
+ raw = str(Path(path)).encode("utf-8")
120
+ return hashlib.sha1(raw).hexdigest()[:8]
121
+
122
+
123
+ def _deep_update_config(
124
+ base: dict[str, Any], overrides: dict[str, Any]
125
+ ) -> dict[str, Any]:
126
+ """Return a copy of a config mapping with nested override values applied."""
127
+ out = dict(base)
128
+ for key, value in overrides.items():
129
+ if isinstance(value, dict) and isinstance(out.get(key), dict):
130
+ out[key] = _deep_update_config(out[key], value)
131
+ else:
132
+ out[key] = value
133
+ return out
134
+
135
+
136
+ def _force_include_cache_hash(regions: Sequence[_ForceIncludeRegion]) -> str:
137
+ """Return a short stable hash for force-include region settings."""
138
+ if not regions:
139
+ return "none"
140
+ parts = [
141
+ (
142
+ region.name,
143
+ f"{region.lon_min:.6f}",
144
+ f"{region.lon_max:.6f}",
145
+ f"{region.lat_min:.6f}",
146
+ f"{region.lat_max:.6f}",
147
+ f"{region.max_land_fraction:.6f}",
148
+ )
149
+ for region in regions
150
+ ]
151
+ raw = repr(parts).encode("utf-8")
152
+ return hashlib.sha1(raw).hexdigest()[:8]
153
+
154
+
155
+ def _parse_force_include_regions(value: Any) -> tuple[_ForceIncludeRegion, ...]:
156
+ """Parse optional force-include region mappings from dataset config."""
157
+ if value is None:
158
+ return ()
159
+ if isinstance(value, str) and value.strip().lower() in MISSING_TEXT_VALUES:
160
+ return ()
161
+ if not isinstance(value, (list, tuple)):
162
+ raise ValueError("grid.force_include_regions must be a list of mappings.")
163
+
164
+ regions: list[_ForceIncludeRegion] = []
165
+ for idx, raw_region in enumerate(value):
166
+ if not isinstance(raw_region, dict):
167
+ raise ValueError("Each grid.force_include_regions item must be a mapping.")
168
+ name = str(raw_region.get("name", f"region_{idx}"))
169
+ lon_min = float(raw_region["lon_min"])
170
+ lon_max = float(raw_region["lon_max"])
171
+ lat_min = float(raw_region["lat_min"])
172
+ lat_max = float(raw_region["lat_max"])
173
+ max_land_fraction = float(raw_region.get("max_land_fraction", 1.0))
174
+ regions.append(
175
+ _ForceIncludeRegion(
176
+ name=name,
177
+ lon_min=min(lon_min, lon_max),
178
+ lon_max=max(lon_min, lon_max),
179
+ lat_min=min(lat_min, lat_max),
180
+ lat_max=max(lat_min, lat_max),
181
+ max_land_fraction=max_land_fraction,
182
+ )
183
+ )
184
+ return tuple(regions)
185
+
186
+
187
+ def _grid_starts(size: int, tile: int, stride: int) -> list[int]:
188
+ """Return grid start indices that always include the final valid tile."""
189
+ if tile < 1:
190
+ raise ValueError("grid.tile_size must be >= 1.")
191
+ if stride < 1:
192
+ raise ValueError("grid.patch_stride must be >= 1.")
193
+ if int(size) < int(tile):
194
+ raise RuntimeError("Source grid is smaller than the requested tile size.")
195
+
196
+ last_start = int(size) - int(tile)
197
+ starts = list(range(0, last_start + 1, int(stride)))
198
+ if not starts or starts[-1] != last_start:
199
+ starts.append(last_start)
200
+ return starts
201
+
202
+
203
+ def _summed_area_table(mask: np.ndarray) -> np.ndarray:
204
+ """Build a summed-area table for fast rectangular mask sums."""
205
+ values = np.asarray(mask, dtype=np.float64)
206
+ table = np.zeros((values.shape[0] + 1, values.shape[1] + 1), dtype=np.float64)
207
+ table[1:, 1:] = values.cumsum(axis=0).cumsum(axis=1)
208
+ return table
209
+
210
+
211
+ def _window_sum(table: np.ndarray, *, y0: int, x0: int, tile: int) -> float:
212
+ """Return a square-window sum from a summed-area table."""
213
+ y1 = int(y0) + int(tile)
214
+ x1 = int(x0) + int(tile)
215
+ return float(
216
+ table[y1, x1]
217
+ - table[int(y0), x1]
218
+ - table[y1, int(x0)]
219
+ + table[int(y0), int(x0)]
220
+ )
221
+
222
+
223
+ def _validate_grid_params(grid_params: _GridParams) -> None:
224
+ """Validate patch-grid settings before building a registry."""
225
+ tile = int(grid_params.tile_size)
226
+ stride = int(grid_params.effective_patch_stride)
227
+ if tile < 1:
228
+ raise ValueError("grid.tile_size must be >= 1.")
229
+ if stride < 1:
230
+ raise ValueError("grid.patch_stride must be >= 1.")
231
+ if stride < tile and grid_params.val_year is None:
232
+ raise ValueError(
233
+ "Overlapping patch grids require split.val_year to avoid spatial "
234
+ "train/val leakage. Set split.val_year or use patch_stride >= tile_size."
235
+ )
236
+ if not (0.0 <= float(grid_params.max_land_fraction) <= 1.0):
237
+ raise ValueError("grid.max_land_fraction must be in [0, 1].")
238
+ for region in grid_params.force_include_regions:
239
+ if not (0.0 <= float(region.max_land_fraction) <= 1.0):
240
+ raise ValueError(
241
+ "grid.force_include_regions[].max_land_fraction must be in [0, 1]."
242
+ )
243
+ source = str(grid_params.patch_grid_source).strip().lower()
244
+ if source not in {"land_mask", "ostia_mask"}:
245
+ raise ValueError("grid.patch_grid_source must be 'land_mask' or 'ostia_mask'.")
246
+
247
+
248
+ def _force_include_region_for_patch(
249
+ *,
250
+ lat_center: float,
251
+ lon_center: float,
252
+ land_fraction: float,
253
+ regions: Sequence[_ForceIncludeRegion],
254
+ ) -> _ForceIncludeRegion | None:
255
+ """Return the matching force-include region for a patch, if any."""
256
+ for region in regions:
257
+ lon_value = _normalize_lon(float(lon_center))
258
+ if (
259
+ region.lat_min <= float(lat_center) <= region.lat_max
260
+ and region.lon_min <= lon_value <= region.lon_max
261
+ and float(land_fraction) <= float(region.max_land_fraction)
262
+ ):
263
+ return region
264
+ return None
265
+
266
+
267
+ def _build_patch_lookup(
268
+ patch_df: pd.DataFrame, grid_params: _GridParams
269
+ ) -> _PatchGridLookup:
270
+ """Build a compact lookup from retained patch starts to patch ids."""
271
+ if patch_df.empty:
272
+ raise RuntimeError("Cannot build patch lookup from an empty patch table.")
273
+
274
+ records = patch_df.to_dict(orient="records")
275
+ first = records[0]
276
+ resolution = float(grid_params.resolution_deg)
277
+ grid_top = max(float(first["lat0"]), float(first["lat1"])) + (
278
+ int(first["grid_y0"]) * resolution
279
+ )
280
+ grid_left = min(float(first["lon0"]), float(first["lon1"])) - (
281
+ int(first["grid_x0"]) * resolution
282
+ )
283
+ patch_by_start = {
284
+ (int(row["grid_y0"]), int(row["grid_x0"])): int(row["patch_id"])
285
+ for row in records
286
+ }
287
+ y_starts = np.asarray(
288
+ sorted({int(row["grid_y0"]) for row in records}), dtype=np.int64
289
+ )
290
+ x_starts = np.asarray(
291
+ sorted({int(row["grid_x0"]) for row in records}), dtype=np.int64
292
+ )
293
+ return _PatchGridLookup(
294
+ patch_by_start=patch_by_start,
295
+ y_starts=y_starts,
296
+ x_starts=x_starts,
297
+ grid_top=float(grid_top),
298
+ grid_left=float(grid_left),
299
+ tile_size=int(grid_params.tile_size),
300
+ resolution_deg=resolution,
301
+ )
302
+
303
+
304
+ def _candidate_starts_for_pixel(
305
+ starts: np.ndarray, pixel_idx: int, tile: int
306
+ ) -> np.ndarray:
307
+ """Return patch start indices whose tile contains one pixel index."""
308
+ starts = np.asarray(starts, dtype=np.int64)
309
+ if starts.size == 0:
310
+ return starts
311
+ mask = (starts <= int(pixel_idx)) & (int(pixel_idx) < (starts + int(tile)))
312
+ return starts[mask]
313
+
314
+
315
+ def _patch_ids_for_profile(
316
+ lookup: _PatchGridLookup,
317
+ *,
318
+ lat: float,
319
+ lon: float,
320
+ ) -> list[int]:
321
+ """Return all retained patch ids containing one profile location."""
322
+ if not np.isfinite(lat) or not np.isfinite(lon):
323
+ return []
324
+
325
+ row_idx = int(
326
+ np.floor((float(lookup.grid_top) - float(lat)) / lookup.resolution_deg)
327
+ )
328
+ lon_value = _normalize_lon(float(lon))
329
+ if float(lookup.grid_left) >= 0.0 and lon_value < float(lookup.grid_left):
330
+ # Some legacy OSTIA grids use 0..360 longitude coordinates while ARGO
331
+ # profile longitudes are normalized to -180..180.
332
+ lon_value += 360.0
333
+ col_idx = int(
334
+ np.floor((lon_value - float(lookup.grid_left)) / lookup.resolution_deg)
335
+ )
336
+ y_candidates = _candidate_starts_for_pixel(
337
+ lookup.y_starts,
338
+ row_idx,
339
+ lookup.tile_size,
340
+ )
341
+ x_candidates = _candidate_starts_for_pixel(
342
+ lookup.x_starts,
343
+ col_idx,
344
+ lookup.tile_size,
345
+ )
346
+ patch_ids: list[int] = []
347
+ for y0 in y_candidates.tolist():
348
+ for x0 in x_candidates.tolist():
349
+ patch_id = lookup.patch_by_start.get((int(y0), int(x0)))
350
+ if patch_id is not None:
351
+ patch_ids.append(int(patch_id))
352
+ return patch_ids
353
+
354
+
355
+ def _build_land_mask_patch_table(grid_params: _GridParams) -> pd.DataFrame:
356
+ """Build retained patch metadata from the authoritative land-mask GeoTIFF."""
357
+ land_mask_path = resolve_package_path(
358
+ DEFAULT_LAND_MASK_PATH
359
+ if grid_params.land_mask_path is None
360
+ else grid_params.land_mask_path
361
+ )
362
+ if not land_mask_path.exists():
363
+ raise FileNotFoundError(f"Land-mask GeoTIFF does not exist: {land_mask_path}")
364
+
365
+ with rasterio.open(land_mask_path) as src:
366
+ land_mask = src.read(1)
367
+ transform = src.transform
368
+ width = int(src.width)
369
+ height = int(src.height)
370
+
371
+ tile = int(grid_params.tile_size)
372
+ stride = int(grid_params.effective_patch_stride)
373
+ resolution = float(grid_params.resolution_deg)
374
+ if not np.isclose(
375
+ float(transform.a), resolution, rtol=0.0, atol=1.0e-8
376
+ ) or not np.isclose(
377
+ abs(float(transform.e)),
378
+ resolution,
379
+ rtol=0.0,
380
+ atol=1.0e-8,
381
+ ):
382
+ raise RuntimeError(
383
+ "Land-mask GeoTIFF resolution does not match dataset.grid.resolution_deg: "
384
+ f"{float(transform.a)} x {abs(float(transform.e))} != {resolution}"
385
+ )
386
+
387
+ y_starts = _grid_starts(height, tile, stride)
388
+ x_starts = _grid_starts(width, tile, stride)
389
+ land_bool = np.asarray(land_mask, dtype=np.float32) > 0.5
390
+ table = _summed_area_table(land_bool)
391
+ max_land_fraction = float(grid_params.max_land_fraction)
392
+
393
+ records: list[dict[str, Any]] = []
394
+ patch_id = 0
395
+ for y0 in tqdm(
396
+ y_starts,
397
+ desc="Building land-mask patch grid",
398
+ unit="row",
399
+ dynamic_ncols=True,
400
+ ):
401
+ for x0 in x_starts:
402
+ land_fraction = _window_sum(table, y0=y0, x0=x0, tile=tile) / float(
403
+ tile * tile
404
+ )
405
+ left = float(transform.c) + (float(x0) * resolution)
406
+ right = left + (float(tile) * resolution)
407
+ top = float(transform.f) - (float(y0) * resolution)
408
+ bottom = top - (float(tile) * resolution)
409
+ lat_center = 0.5 * (float(bottom) + float(top))
410
+ lon_center = _center_lon_deg(float(left), float(right))
411
+ force_region = _force_include_region_for_patch(
412
+ lat_center=lat_center,
413
+ lon_center=lon_center,
414
+ land_fraction=land_fraction,
415
+ regions=grid_params.force_include_regions,
416
+ )
417
+ if land_fraction > max_land_fraction and force_region is None:
418
+ continue
419
+ records.append(
420
+ {
421
+ "patch_id": int(patch_id),
422
+ "grid_y0": int(y0),
423
+ "grid_x0": int(x0),
424
+ "lat0": float(bottom),
425
+ "lat1": float(top),
426
+ "lon0": float(left),
427
+ "lon1": float(right),
428
+ "lat_center": lat_center,
429
+ "lon_center": lon_center,
430
+ "land_fraction": float(land_fraction),
431
+ "ocean_fraction": float(1.0 - land_fraction),
432
+ "invalid_fraction": float(land_fraction),
433
+ "force_included": bool(force_region is not None),
434
+ "force_include_region": (
435
+ "" if force_region is None else force_region.name
436
+ ),
437
+ }
438
+ )
439
+ patch_id += 1
440
+
441
+ if not records:
442
+ raise RuntimeError("No valid patches were built from the land-mask grid.")
443
+ return pd.DataFrame.from_records(records)
depthdif_dataset/normalizations.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+
5
+ # Dataset-level statistics provided by user.
6
+ CELSIUS_TO_KELVIN_OFFSET = 273.15
7
+ Y_MEAN = 289.74267177946783
8
+ Y_STD = 10.933397487585731
9
+ SALINITY_MEAN = 34.54260282159372
10
+ SALINITY_STD = 1.158266487751096
11
+ PLOT_STD_MULTIPLIER = 2.5
12
+ PLOT_TEMP_MIN = -10.740821939496481
13
+ PLOT_TEMP_MAX = 43.92616549843217
14
+ PLOT_SALINITY_MIN = 30.0
15
+ PLOT_SALINITY_MAX = 40.0
16
+ PLOT_CMAP = "turbo"
17
+ PLOT_SALINITY_CMAP = "winter"
18
+
19
+
20
+ def temperature_normalize(mode: str, tensor: torch.Tensor) -> torch.Tensor:
21
+ """Compute temperature normalize and return the result.
22
+
23
+ Args:
24
+ mode (str): Input value.
25
+ tensor (torch.Tensor): Tensor input for the computation.
26
+
27
+ Returns:
28
+ torch.Tensor: Tensor output produced by this call.
29
+ """
30
+ if mode not in {"norm", "denorm"}:
31
+ raise ValueError("mode must be 'norm' or 'denorm'")
32
+
33
+ mean = torch.as_tensor(Y_MEAN, dtype=tensor.dtype, device=tensor.device)
34
+ std = torch.as_tensor(Y_STD, dtype=tensor.dtype, device=tensor.device)
35
+ kelvin_offset = torch.as_tensor(
36
+ CELSIUS_TO_KELVIN_OFFSET, dtype=tensor.dtype, device=tensor.device
37
+ )
38
+
39
+ if mode == "norm":
40
+ tensor_kelvin = tensor + kelvin_offset
41
+ return (tensor_kelvin - mean) / std
42
+ denorm_kelvin = tensor * std + mean
43
+ # Convert back to Celsius so callers keep receiving physical temperatures in C.
44
+ return denorm_kelvin - kelvin_offset
45
+
46
+
47
+ def salinity_normalize(mode: str, tensor: torch.Tensor) -> torch.Tensor:
48
+ """Compute salinity normalization and return the result.
49
+
50
+ Args:
51
+ mode (str): Input value.
52
+ tensor (torch.Tensor): Tensor input for the computation.
53
+
54
+ Returns:
55
+ torch.Tensor: Tensor output produced by this call.
56
+ """
57
+ if mode not in {"norm", "denorm"}:
58
+ raise ValueError("mode must be 'norm' or 'denorm'")
59
+
60
+ mean = torch.as_tensor(SALINITY_MEAN, dtype=tensor.dtype, device=tensor.device)
61
+ std = torch.as_tensor(SALINITY_STD, dtype=tensor.dtype, device=tensor.device)
62
+
63
+ if mode == "norm":
64
+ return (tensor - mean) / std
65
+ return tensor * std + mean
66
+
67
+
68
+ def salinity_to_plot_unit(
69
+ tensor: torch.Tensor,
70
+ *,
71
+ tensor_is_normalized: bool = True,
72
+ ) -> torch.Tensor:
73
+ """Compute salinity plot unit and return the result.
74
+
75
+ Args:
76
+ tensor (torch.Tensor): Tensor input for the computation.
77
+ tensor_is_normalized (bool): Boolean flag controlling behavior.
78
+
79
+ Returns:
80
+ torch.Tensor: Tensor output produced by this call.
81
+ """
82
+ salinity = (
83
+ salinity_normalize(mode="denorm", tensor=tensor)
84
+ if tensor_is_normalized
85
+ else tensor
86
+ )
87
+ s_min = torch.as_tensor(
88
+ PLOT_SALINITY_MIN, dtype=salinity.dtype, device=salinity.device
89
+ )
90
+ s_max = torch.as_tensor(
91
+ PLOT_SALINITY_MAX, dtype=salinity.dtype, device=salinity.device
92
+ )
93
+ denom = torch.clamp(s_max - s_min, min=torch.finfo(salinity.dtype).eps)
94
+ return ((salinity - s_min) / denom).clamp(0.0, 1.0)
95
+
96
+
97
+ def temperature_to_plot_unit(
98
+ tensor: torch.Tensor,
99
+ *,
100
+ tensor_is_normalized: bool = True,
101
+ ) -> torch.Tensor:
102
+ """Compute temperature to plot unit and return the result.
103
+
104
+ Args:
105
+ tensor (torch.Tensor): Tensor input for the computation.
106
+ tensor_is_normalized (bool): Boolean flag controlling behavior.
107
+
108
+ Returns:
109
+ torch.Tensor: Tensor output produced by this call.
110
+ """
111
+ temp = (
112
+ temperature_normalize(mode="denorm", tensor=tensor)
113
+ if tensor_is_normalized
114
+ else tensor
115
+ )
116
+ t_min = torch.as_tensor(PLOT_TEMP_MIN, dtype=temp.dtype, device=temp.device)
117
+ t_max = torch.as_tensor(PLOT_TEMP_MAX, dtype=temp.dtype, device=temp.device)
118
+ denom = torch.clamp(t_max - t_min, min=torch.finfo(temp.dtype).eps)
119
+ return ((temp - t_min) / denom).clamp(0.0, 1.0)
examples/torch_dataloader.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Example with all options:
2
+ # python examples/torch_dataloader.py --root . --split all --batch-size 2 --num-workers 0 --tile-size 128 --patch-stride 128 --max-land-fraction 0.30 --date-start 20000101 --date-end 20000101 --max-dates 1 --include-salinity --metadata-cache-dir /tmp/depthdif_cache --require-argo
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+ import sys
9
+ from typing import Any
10
+
11
+ REPO_ROOT = Path(__file__).resolve().parents[1]
12
+ if str(REPO_ROOT) not in sys.path:
13
+ sys.path.insert(0, str(REPO_ROOT))
14
+
15
+ from depthdif_dataset import ArgoGeoTIFFGriddedPatchDataset, build_dataloader
16
+
17
+
18
+ def _shape_or_value(value: Any) -> Any:
19
+ """Return tensor shapes for compact terminal output."""
20
+ return tuple(value.shape) if hasattr(value, "shape") else value
21
+
22
+
23
+ def main() -> None:
24
+ """Open the packaged dataset and print the first PyTorch batch."""
25
+ parser = argparse.ArgumentParser(description=__doc__)
26
+ parser.add_argument("--root", type=Path, default=REPO_ROOT)
27
+ parser.add_argument("--split", choices=("all", "train", "val"), default="all")
28
+ parser.add_argument("--batch-size", type=int, default=2)
29
+ parser.add_argument("--num-workers", type=int, default=0)
30
+ parser.add_argument("--tile-size", type=int, default=128)
31
+ parser.add_argument("--patch-stride", type=int, default=128)
32
+ parser.add_argument("--max-land-fraction", type=float, default=0.30)
33
+ parser.add_argument("--date-start", type=int, default=None)
34
+ parser.add_argument("--date-end", type=int, default=None)
35
+ parser.add_argument("--max-dates", type=int, default=1)
36
+ parser.add_argument("--include-salinity", action="store_true")
37
+ parser.add_argument(
38
+ "--metadata-cache-dir",
39
+ type=Path,
40
+ default=None,
41
+ help="Optional cache directory for patch/date metadata CSVs.",
42
+ )
43
+ parser.add_argument(
44
+ "--require-argo",
45
+ action="store_true",
46
+ help="Filter rows to patches with ARGO profiles; this may scan the compact ARGO store on first use.",
47
+ )
48
+ args = parser.parse_args()
49
+
50
+ dataset = ArgoGeoTIFFGriddedPatchDataset(
51
+ geotiff_root_dir=args.root,
52
+ split=args.split,
53
+ tile_size=args.tile_size,
54
+ patch_stride=args.patch_stride,
55
+ max_land_fraction=args.max_land_fraction,
56
+ date_start=args.date_start,
57
+ date_end=args.date_end,
58
+ max_dates=args.max_dates,
59
+ include_salinity=args.include_salinity,
60
+ require_argo_for_train=args.require_argo,
61
+ require_argo_for_val=args.require_argo,
62
+ require_argo_for_all=args.require_argo,
63
+ count_argo_support=args.require_argo,
64
+ metadata_cache_dir=args.metadata_cache_dir,
65
+ )
66
+ loader = build_dataloader(
67
+ dataset,
68
+ batch_size=args.batch_size,
69
+ num_workers=args.num_workers,
70
+ shuffle=True,
71
+ )
72
+ batch = next(iter(loader))
73
+
74
+ print(f"dataset rows: {len(dataset)}")
75
+ print(f"depth levels: {len(dataset.depth_axis_m)}")
76
+ print(
77
+ f"date coverage in this run: {dataset.available_dates[0]}..{dataset.available_dates[-1]}"
78
+ )
79
+ for key, value in batch.items():
80
+ if key == "info":
81
+ continue
82
+ print(f"{key}: {_shape_or_value(value)}")
83
+
84
+
85
+ if __name__ == "__main__":
86
+ main()
manifest.yaml CHANGED
The diff for this file is too large to render. See raw diff
 
metadata/citation.cff CHANGED
@@ -3,4 +3,4 @@ message: "If you use this dataset, cite DepthDif and the upstream EN4/ARGO, GLOR
3
  title: "DepthDif aligned ARGO profile collocation dataset"
4
  authors:
5
  - family-names: "DepthDif contributors"
6
- license: "other"
 
3
  title: "DepthDif aligned ARGO profile collocation dataset"
4
  authors:
5
  - family-names: "DepthDif contributors"
6
+ license: "CC-BY-4.0"
metadata/dataset_description.json CHANGED
@@ -1,19 +1,19 @@
1
  {
2
  "name": "OceanVariableReconstruction",
3
- "created_utc": "2026-05-21T06:26:40+00:00",
4
  "zarr_path": "data/argo_glors_ostia_ssh.zarr",
5
- "profile_count": 6637381,
6
  "glorys_depth_count": 50,
7
  "profile_date_range": {
8
- "start": 20100101,
9
  "end": 20240731,
10
- "start_iso": "2010-01-01",
11
  "end_iso": "2024-07-31"
12
  },
13
  "bbox": [
14
  -999.99,
15
  -999.99,
16
- 179.99985,
17
  168.8678
18
  ],
19
  "variables": [
@@ -78,13 +78,13 @@
78
  "zarr_attrs": {
79
  "description": "ARGO profiles enriched with freshly collocated GLORYS, OSTIA, sea-level, and SSS fields.",
80
  "created_by": "depth_recon.data.dataset_creation.export_aligned_argo.b_export_enriched_argo_profiles",
81
- "created_utc": "2026-05-20T14:16:25+00:00",
82
  "requested_date_range": {
83
- "start_date": 20100101,
84
  "end_date": 20240731
85
  },
86
- "batch_size": 2048,
87
- "cache_size_per_worker": 8,
88
  "max_profiles": null,
89
  "workers": 12,
90
  "path_policy": "No absolute source filesystem paths are stored. profile_source_file stores source filenames only.",
@@ -92,36 +92,36 @@
92
  "depth_axis": "GLORYS native depth coordinate, in meters, loaded from the first readable GLORYS file.",
93
  "source_file_summary": {
94
  "argo": {
95
- "file_count": 169,
96
- "first_file": "EN.4.2.2.f.profiles.g10.201001.nc",
97
  "last_file": "EN.4.2.2.f.profiles.g10.202407.nc"
98
  },
99
  "glorys": {
100
- "file_count": 843,
101
- "first_file": "mercatorglorys12v1_gl12_mean_20100101_R20100106.nc",
102
- "last_file": "mercatorglorys12v1_gl12_mean_20260220_R20260225.nc",
103
- "first_date": 20100101,
104
- "last_date": 20260220
105
  },
106
  "ostia": {
107
- "file_count": 5326,
108
- "first_file": "20100101120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc",
109
  "last_file": "20240731120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc",
110
- "first_date": 20100101,
111
  "last_date": 20240731
112
  },
113
  "sealevel": {
114
- "file_count": 5326,
115
- "first_file": "dt_global_allsat_phy_l4_20100101_20241016.nc",
116
  "last_file": "dt_global_allsat_phy_l4_20240731_20250429.nc",
117
- "first_date": 20100101,
118
  "last_date": 20240731
119
  },
120
  "sss": {
121
- "file_count": 5326,
122
- "first_file": "dataset-sss-ssd-rep-daily_20100101T1200Z_P20241017T0000Z.nc",
123
  "last_file": "dataset-sss-ssd-rep-daily_20240731T1200Z_P20260101T0000Z.nc",
124
- "first_date": 20100101,
125
  "last_date": 20240731
126
  }
127
  },
@@ -130,18 +130,18 @@
130
  "provider": "UK Met Office Hadley Centre",
131
  "product": "EN4.2.2 profile archive",
132
  "role": "In-situ profile observations projected onto the GLORYS depth grid.",
133
- "file_count": 169,
134
- "representative_file": "EN.4.2.2.f.profiles.g10.201001.nc",
135
- "first_file": "EN.4.2.2.f.profiles.g10.201001.nc",
136
  "last_file": "EN.4.2.2.f.profiles.g10.202407.nc",
137
  "global_attrs": {
138
  "licence": "EN4 is distributed under the Non Commercial Government Licence: http://www.nationalarchives.gov.uk/doc/non-commercial-government-licence/version/2/. The data are available for non-commercial use with attribution to the data providers, please see the product website (see global attribute: references) for terms and conditions.",
139
  "references": "Website and paper: https://www.metoffice.gov.uk/hadobs/en4/; Good, S. A., M. J. Martin and N. A. Rayner, 2013. EN4: quality controlled ocean temperature and salinity profiles and monthly objective analyses with uncertainty estimates, Journal of Geophysical Research: Oceans, 118, 6704-6716, doi:10.1002/2013JC009067",
140
- "history": "Fri Apr 2 19:50:52 2021: ncks -O -x -v TEMP_UNIQUE_ID,PSAL_UNIQUE_ID EN.4.2.2.f.profiles.g10.201001.nc EN.4.2.2.f.profiles.g10.201001.nc\nFri Apr 2 19:50:48 2021: ncks -O -x -v BKPT,BKPS EN.4.2.2.f.profiles.g10.201001.nc EN.4.2.2.f.profiles.g10.201001.nc\nFri Apr 2 19:22:43 2021: ncatted -a _FillValue,BKPS,c,f,99999.0 profiles.nc\nFri Apr 2 19:22:42 2021: ncatted -a _FillValue,BKPT,c,f,99999.0 profiles.nc\nFri Apr 2 19:22:40 2021: ncatted -a _FillValue,POTM_CORRECTED,c,f,99999.0 profiles.nc\nFri Apr 2 19:22:39 2021: ncatted -a _FillValue,TEMP,c,f,99999.0 profiles.nc\nFri Apr 2 19:22:37 2021: ncatted -a _FillValue,PSAL_CORRECTED,c,f,99999.0 profiles.nc\nFri Apr 2 19:22:25 2021: ncatted -a _FillValue,DEPH_CORRECTED,c,f,99999.0 profiles.nc",
141
  "NCO": "netCDF Operators version 4.7.5 (Homepage = http://nco.sf.net, Code = http://github.com/nco/nco)"
142
  },
143
  "dimensions": {
144
- "N_PROF": 31697,
145
  "N_CALIB": 1,
146
  "N_PARAM": 5,
147
  "N_LEVELS": 400,
@@ -354,15 +354,15 @@
354
  "provider": "Copernicus Marine Service",
355
  "product": "Global Ocean Physics Reanalysis / GLORYS12V1",
356
  "role": "3D ocean reanalysis fields and 2D model surface/ice fields sampled at profile points.",
357
- "file_count": 843,
358
- "representative_file": "mercatorglorys12v1_gl12_mean_20100101_R20100106.nc",
359
- "first_file": "mercatorglorys12v1_gl12_mean_20100101_R20100106.nc",
360
- "last_file": "mercatorglorys12v1_gl12_mean_20260220_R20260225.nc",
361
  "global_attrs": {
362
  "title": "daily mean fields from Global Ocean Physics Analysis and Forecast updated Daily",
363
  "easting": "longitude",
364
  "northing": "latitude",
365
- "history": "2017/08/19 20:09:56 MERCATOR OCEAN Netcdf creation",
366
  "source": "MERCATOR GLORYS12V1",
367
  "institution": "MERCATOR OCEAN",
368
  "references": "http://www.mercator-ocean.fr",
@@ -370,12 +370,12 @@
370
  "Conventions": "CF-1.4",
371
  "domain_name": "GL12",
372
  "field_type": "mean",
373
- "field_date": "2010-01-01 00:00:00",
374
- "field_julian_date": 21915.0,
375
  "julian_day_unit": "days since 1950-01-01 00:00:00",
376
- "forecast_range": "2-day_forecast",
377
  "forecast_type": "hindcast",
378
- "bulletin_date": "2010-01-06 00:00:00",
379
  "bulletin_type": "operational",
380
  "longitude_min": -180.0,
381
  "longitude_max": 179.9166717529297,
@@ -404,8 +404,8 @@
404
  "standard_name": "sea_water_potential_temperature",
405
  "units": "degrees_C",
406
  "unit_long": "Degrees Celsius",
407
- "valid_min": -32754,
408
- "valid_max": 19721,
409
  "cell_methods": "area: mean"
410
  }
411
  },
@@ -423,7 +423,7 @@
423
  "units": "1e-3",
424
  "unit_long": "Practical Salinity Unit",
425
  "valid_min": 1,
426
- "valid_max": 27001,
427
  "cell_methods": "area: mean"
428
  }
429
  },
@@ -440,8 +440,8 @@
440
  "standard_name": "eastward_sea_water_velocity",
441
  "units": "m s-1",
442
  "unit_long": "Meters per second",
443
- "valid_min": -3168,
444
- "valid_max": 3110,
445
  "cell_methods": "area: mean"
446
  }
447
  },
@@ -458,8 +458,8 @@
458
  "standard_name": "northward_sea_water_velocity",
459
  "units": "m s-1",
460
  "unit_long": "Meters per second",
461
- "valid_min": -3256,
462
- "valid_max": 3567,
463
  "cell_methods": "area: mean"
464
  }
465
  },
@@ -475,8 +475,8 @@
475
  "standard_name": "sea_surface_height_above_geoid",
476
  "units": "m",
477
  "unit_long": "Meters",
478
- "valid_min": -6349,
479
- "valid_max": 5181,
480
  "cell_methods": "area: mean"
481
  }
482
  },
@@ -493,7 +493,7 @@
493
  "units": "m",
494
  "unit_long": "Meters",
495
  "valid_min": 1,
496
- "valid_max": 12516,
497
  "cell_methods": "area: mean"
498
  }
499
  },
@@ -509,8 +509,8 @@
509
  "standard_name": "sea_water_potential_temperature_at_sea_floor",
510
  "units": "degrees_C",
511
  "unit_long": "Degrees Celsius",
512
- "valid_min": -32752,
513
- "valid_max": 19810,
514
  "cell_methods": "area: mean"
515
  }
516
  },
@@ -527,7 +527,7 @@
527
  "units": "m",
528
  "unit_long": "Meters",
529
  "valid_min": 1,
530
- "valid_max": 7672,
531
  "cell_methods": "area: mean where sea_ice"
532
  }
533
  },
@@ -544,7 +544,7 @@
544
  "units": "1",
545
  "unit_long": "Fraction",
546
  "valid_min": 1,
547
- "valid_max": 28027,
548
  "cell_methods": "area: mean where sea_ice"
549
  }
550
  },
@@ -560,8 +560,8 @@
560
  "standard_name": "eastward_sea_ice_velocity",
561
  "units": "m s-1",
562
  "unit_long": "Meters per second",
563
- "valid_min": -21266,
564
- "valid_max": 28902,
565
  "cell_methods": "area: mean where sea_ice"
566
  }
567
  },
@@ -577,8 +577,8 @@
577
  "standard_name": "northward_sea_ice_velocity",
578
  "units": "m s-1",
579
  "unit_long": "Meters per second",
580
- "valid_min": -32158,
581
- "valid_max": 23067,
582
  "cell_methods": "area: mean where sea_ice"
583
  }
584
  },
@@ -591,8 +591,8 @@
591
  "long_name": "Time (hours since 1950-01-01)",
592
  "standard_name": "time",
593
  "calendar": "gregorian",
594
- "valid_min": 525972.0,
595
- "valid_max": 525972.0,
596
  "units": "hours since 1950-01-01 00:00:00",
597
  "axis": "T"
598
  }
@@ -651,9 +651,9 @@
651
  "provider": "Copernicus Marine Service / UK Met Office OSTIA",
652
  "product": "SST_GLO_SST_L4_REP_OBSERVATIONS_010_011",
653
  "role": "Daily analysed sea-surface temperature and mask fields sampled at profile points.",
654
- "file_count": 5326,
655
- "representative_file": "20100101120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc",
656
- "first_file": "20100101120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc",
657
  "last_file": "20240731120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc",
658
  "global_attrs": {
659
  "Conventions": "CF-1.4, ACDD-1.3",
@@ -669,11 +669,11 @@
669
  "uuid": "a2df4a18-6f19-4772-9532-39307a0e2794",
670
  "gds_version_id": "2.4",
671
  "netcdf_version_id": "4.1",
672
- "date_created": "20190818T061207Z",
673
- "start_time": "20100101T000000Z",
674
- "time_coverage_start": "20100101T000000Z",
675
- "stop_time": "20100102T000000Z",
676
- "time_coverage_end": "20100102T000000Z",
677
  "file_quality_level": 3,
678
  "Metadata_Conventions": "Unidata Observation Dataset v1.0",
679
  "metadata_link": "http://podaac.jpl.nasa.gov/ws/metadata/dataset?format=gcmd&shortName=UKMO-L4HRfnd-GLOB-OSTIA",
@@ -834,9 +834,9 @@
834
  "product": "SEALEVEL_GLO_PHY_L4_MY_008_047",
835
  "dataset_id": "cmems_obs-sl_glo_phy-ssh_my_allsat-l4-duacs-0.125deg_P1D",
836
  "role": "Daily sea-level, geostrophic current, and ice-flag fields sampled at profile points.",
837
- "file_count": 5326,
838
- "representative_file": "dt_global_allsat_phy_l4_20100101_20241016.nc",
839
- "first_file": "dt_global_allsat_phy_l4_20100101_20241016.nc",
840
  "last_file": "dt_global_allsat_phy_l4_20240731_20250429.nc",
841
  "global_attrs": {
842
  "Conventions": "CF-1.6",
@@ -861,8 +861,8 @@
861
  "standard_name_vocabulary": "NetCDF Climate and Forecast (CF) Metadata Convention Standard Name Table v37",
862
  "summary": "SSALTO/DUACS Delayed-Time Level-4 sea surface height and derived variables measured by multi-satellite altimetry observations over Global Ocean.",
863
  "title": "DT merged all satellites Global Ocean Gridded SSALTO/DUACS Sea Surface Height L4 product and derived variables",
864
- "date_created": "2024-10-16T16:52:55Z",
865
- "history": "2024-10-16 16:52:55Z: Creation",
866
  "geospatial_lat_max": 89.9375,
867
  "geospatial_lat_min": -89.9375,
868
  "geospatial_lat_resolution": 0.125,
@@ -878,9 +878,9 @@
878
  "geospatial_vertical_units": "m",
879
  "time_coverage_duration": "P1D",
880
  "time_coverage_resolution": "P1D",
881
- "time_coverage_end": "2010-01-01T12:00:00Z",
882
- "time_coverage_start": "2009-12-31T12:00:00Z",
883
- "platform": "Jason-1 Interleaved, OSTM/Jason-2, Envisat"
884
  },
885
  "dimensions": {
886
  "latitude": 1440,
@@ -1106,9 +1106,9 @@
1106
  "product": "MULTIOBS_GLO_PHY_S_SURFACE_MYNRT_015_013",
1107
  "dataset_id": "cmems_obs-mob_glo_phy-sss_my_multi_P1D",
1108
  "role": "Daily sea-surface salinity, density, and sea-ice fields sampled at profile points.",
1109
- "file_count": 5326,
1110
- "representative_file": "dataset-sss-ssd-rep-daily_20100101T1200Z_P20241017T0000Z.nc",
1111
- "first_file": "dataset-sss-ssd-rep-daily_20100101T1200Z_P20241017T0000Z.nc",
1112
  "last_file": "dataset-sss-ssd-rep-daily_20240731T1200Z_P20260101T0000Z.nc",
1113
  "global_attrs": {
1114
  "Conventions": "CF-1.7",
@@ -1117,7 +1117,7 @@
1117
  "institution": "CNR",
1118
  "contact": "servicedesk.cmems@mercator-ocean.eu",
1119
  "netcdf_version_id": "4.9.3-development of Jun 4 2023 14:13:36",
1120
- "creation_date": "Thu 17 Oct 2024 10:57:11",
1121
  "product_version": "1.1",
1122
  "grid_resolution": "0.125 degrees",
1123
  "software_version": "SSS/SSD HR Processor v1.1",
@@ -1247,5 +1247,8 @@
1247
  "sealevel_tpa_correction": "The Copernicus source metadata marks this field as not implemented in the current product version, so values may be NaN."
1248
  }
1249
  },
1250
- "includes_geotiff_assets": true
 
 
 
1251
  }
 
1
  {
2
  "name": "OceanVariableReconstruction",
3
+ "created_utc": "2026-06-02T16:56:29+00:00",
4
  "zarr_path": "data/argo_glors_ostia_ssh.zarr",
5
+ "profile_count": 9485977,
6
  "glorys_depth_count": 50,
7
  "profile_date_range": {
8
+ "start": 20000101,
9
  "end": 20240731,
10
+ "start_iso": "2000-01-01",
11
  "end_iso": "2024-07-31"
12
  },
13
  "bbox": [
14
  -999.99,
15
  -999.99,
16
+ 179.999954,
17
  168.8678
18
  ],
19
  "variables": [
 
78
  "zarr_attrs": {
79
  "description": "ARGO profiles enriched with freshly collocated GLORYS, OSTIA, sea-level, and SSS fields.",
80
  "created_by": "depth_recon.data.dataset_creation.export_aligned_argo.b_export_enriched_argo_profiles",
81
+ "created_utc": "2026-06-01T13:53:04+00:00",
82
  "requested_date_range": {
83
+ "start_date": 20000101,
84
  "end_date": 20240731
85
  },
86
+ "batch_size": 8192,
87
+ "cache_size_per_worker": 4,
88
  "max_profiles": null,
89
  "workers": 12,
90
  "path_policy": "No absolute source filesystem paths are stored. profile_source_file stores source filenames only.",
 
92
  "depth_axis": "GLORYS native depth coordinate, in meters, loaded from the first readable GLORYS file.",
93
  "source_file_summary": {
94
  "argo": {
95
+ "file_count": 289,
96
+ "first_file": "EN.4.2.2.f.profiles.g10.200001.nc",
97
  "last_file": "EN.4.2.2.f.profiles.g10.202407.nc"
98
  },
99
  "glorys": {
100
+ "file_count": 1283,
101
+ "first_file": "mercatorglorys12v1_gl12_mean_20000101_R20000105.nc",
102
+ "last_file": "mercatorglorys12v1_gl12_mean_20240726_R20240731.nc",
103
+ "first_date": 20000101,
104
+ "last_date": 20240726
105
  },
106
  "ostia": {
107
+ "file_count": 8979,
108
+ "first_file": "20000101120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc",
109
  "last_file": "20240731120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc",
110
+ "first_date": 20000101,
111
  "last_date": 20240731
112
  },
113
  "sealevel": {
114
+ "file_count": 8979,
115
+ "first_file": "dt_global_allsat_phy_l4_20000101_20241016.nc",
116
  "last_file": "dt_global_allsat_phy_l4_20240731_20250429.nc",
117
+ "first_date": 20000101,
118
  "last_date": 20240731
119
  },
120
  "sss": {
121
+ "file_count": 8979,
122
+ "first_file": "dataset-sss-ssd-rep-daily_20000101T1200Z_P20241017T0000Z.nc",
123
  "last_file": "dataset-sss-ssd-rep-daily_20240731T1200Z_P20260101T0000Z.nc",
124
+ "first_date": 20000101,
125
  "last_date": 20240731
126
  }
127
  },
 
130
  "provider": "UK Met Office Hadley Centre",
131
  "product": "EN4.2.2 profile archive",
132
  "role": "In-situ profile observations projected onto the GLORYS depth grid.",
133
+ "file_count": 289,
134
+ "representative_file": "EN.4.2.2.f.profiles.g10.200001.nc",
135
+ "first_file": "EN.4.2.2.f.profiles.g10.200001.nc",
136
  "last_file": "EN.4.2.2.f.profiles.g10.202407.nc",
137
  "global_attrs": {
138
  "licence": "EN4 is distributed under the Non Commercial Government Licence: http://www.nationalarchives.gov.uk/doc/non-commercial-government-licence/version/2/. The data are available for non-commercial use with attribution to the data providers, please see the product website (see global attribute: references) for terms and conditions.",
139
  "references": "Website and paper: https://www.metoffice.gov.uk/hadobs/en4/; Good, S. A., M. J. Martin and N. A. Rayner, 2013. EN4: quality controlled ocean temperature and salinity profiles and monthly objective analyses with uncertainty estimates, Journal of Geophysical Research: Oceans, 118, 6704-6716, doi:10.1002/2013JC009067",
140
+ "history": "Wed Mar 24 13:36:17 2021: ncks -O -x -v TEMP_UNIQUE_ID,PSAL_UNIQUE_ID EN.4.2.2.f.profiles.g10.200001.nc EN.4.2.2.f.profiles.g10.200001.nc\nWed Mar 24 13:36:12 2021: ncks -O -x -v BKPT,BKPS EN.4.2.2.f.profiles.g10.200001.nc EN.4.2.2.f.profiles.g10.200001.nc\nWed Mar 24 13:25:27 2021: ncatted -a _FillValue,BKPS,c,f,99999.0 profiles.nc\nWed Mar 24 13:25:27 2021: ncatted -a _FillValue,BKPT,c,f,99999.0 profiles.nc\nWed Mar 24 13:25:26 2021: ncatted -a _FillValue,POTM_CORRECTED,c,f,99999.0 profiles.nc\nWed Mar 24 13:25:26 2021: ncatted -a _FillValue,TEMP,c,f,99999.0 profiles.nc\nWed Mar 24 13:25:25 2021: ncatted -a _FillValue,PSAL_CORRECTED,c,f,99999.0 profiles.nc\nWed Mar 24 13:25:21 2021: ncatted -a _FillValue,DEPH_CORRECTED,c,f,99999.0 profiles.nc",
141
  "NCO": "netCDF Operators version 4.7.5 (Homepage = http://nco.sf.net, Code = http://github.com/nco/nco)"
142
  },
143
  "dimensions": {
144
+ "N_PROF": 11320,
145
  "N_CALIB": 1,
146
  "N_PARAM": 5,
147
  "N_LEVELS": 400,
 
354
  "provider": "Copernicus Marine Service",
355
  "product": "Global Ocean Physics Reanalysis / GLORYS12V1",
356
  "role": "3D ocean reanalysis fields and 2D model surface/ice fields sampled at profile points.",
357
+ "file_count": 1283,
358
+ "representative_file": "mercatorglorys12v1_gl12_mean_20000101_R20000105.nc",
359
+ "first_file": "mercatorglorys12v1_gl12_mean_20000101_R20000105.nc",
360
+ "last_file": "mercatorglorys12v1_gl12_mean_20240726_R20240731.nc",
361
  "global_attrs": {
362
  "title": "daily mean fields from Global Ocean Physics Analysis and Forecast updated Daily",
363
  "easting": "longitude",
364
  "northing": "latitude",
365
+ "history": "2017/05/29 22:40:48 MERCATOR OCEAN Netcdf creation",
366
  "source": "MERCATOR GLORYS12V1",
367
  "institution": "MERCATOR OCEAN",
368
  "references": "http://www.mercator-ocean.fr",
 
370
  "Conventions": "CF-1.4",
371
  "domain_name": "GL12",
372
  "field_type": "mean",
373
+ "field_date": "2000-01-01 00:00:00",
374
+ "field_julian_date": 18262.0,
375
  "julian_day_unit": "days since 1950-01-01 00:00:00",
376
+ "forecast_range": "3-day_forecast",
377
  "forecast_type": "hindcast",
378
+ "bulletin_date": "2000-01-05 00:00:00",
379
  "bulletin_type": "operational",
380
  "longitude_min": -180.0,
381
  "longitude_max": 179.9166717529297,
 
404
  "standard_name": "sea_water_potential_temperature",
405
  "units": "degrees_C",
406
  "unit_long": "Degrees Celsius",
407
+ "valid_min": -32764,
408
+ "valid_max": 18468,
409
  "cell_methods": "area: mean"
410
  }
411
  },
 
423
  "units": "1e-3",
424
  "unit_long": "Practical Salinity Unit",
425
  "valid_min": 1,
426
+ "valid_max": 27353,
427
  "cell_methods": "area: mean"
428
  }
429
  },
 
440
  "standard_name": "eastward_sea_water_velocity",
441
  "units": "m s-1",
442
  "unit_long": "Meters per second",
443
+ "valid_min": -3510,
444
+ "valid_max": 3894,
445
  "cell_methods": "area: mean"
446
  }
447
  },
 
458
  "standard_name": "northward_sea_water_velocity",
459
  "units": "m s-1",
460
  "unit_long": "Meters per second",
461
+ "valid_min": -3234,
462
+ "valid_max": 3332,
463
  "cell_methods": "area: mean"
464
  }
465
  },
 
475
  "standard_name": "sea_surface_height_above_geoid",
476
  "units": "m",
477
  "unit_long": "Meters",
478
+ "valid_min": -6382,
479
+ "valid_max": 4883,
480
  "cell_methods": "area: mean"
481
  }
482
  },
 
493
  "units": "m",
494
  "unit_long": "Meters",
495
  "valid_min": 1,
496
+ "valid_max": 8881,
497
  "cell_methods": "area: mean"
498
  }
499
  },
 
509
  "standard_name": "sea_water_potential_temperature_at_sea_floor",
510
  "units": "degrees_C",
511
  "unit_long": "Degrees Celsius",
512
+ "valid_min": -32639,
513
+ "valid_max": 18498,
514
  "cell_methods": "area: mean"
515
  }
516
  },
 
527
  "units": "m",
528
  "unit_long": "Meters",
529
  "valid_min": 1,
530
+ "valid_max": 8041,
531
  "cell_methods": "area: mean where sea_ice"
532
  }
533
  },
 
544
  "units": "1",
545
  "unit_long": "Fraction",
546
  "valid_min": 1,
547
+ "valid_max": 28317,
548
  "cell_methods": "area: mean where sea_ice"
549
  }
550
  },
 
560
  "standard_name": "eastward_sea_ice_velocity",
561
  "units": "m s-1",
562
  "unit_long": "Meters per second",
563
+ "valid_min": -20539,
564
+ "valid_max": 32652,
565
  "cell_methods": "area: mean where sea_ice"
566
  }
567
  },
 
577
  "standard_name": "northward_sea_ice_velocity",
578
  "units": "m s-1",
579
  "unit_long": "Meters per second",
580
+ "valid_min": -32637,
581
+ "valid_max": 24967,
582
  "cell_methods": "area: mean where sea_ice"
583
  }
584
  },
 
591
  "long_name": "Time (hours since 1950-01-01)",
592
  "standard_name": "time",
593
  "calendar": "gregorian",
594
+ "valid_min": 438300.0,
595
+ "valid_max": 438300.0,
596
  "units": "hours since 1950-01-01 00:00:00",
597
  "axis": "T"
598
  }
 
651
  "provider": "Copernicus Marine Service / UK Met Office OSTIA",
652
  "product": "SST_GLO_SST_L4_REP_OBSERVATIONS_010_011",
653
  "role": "Daily analysed sea-surface temperature and mask fields sampled at profile points.",
654
+ "file_count": 8979,
655
+ "representative_file": "20000101120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc",
656
+ "first_file": "20000101120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc",
657
  "last_file": "20240731120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc",
658
  "global_attrs": {
659
  "Conventions": "CF-1.4, ACDD-1.3",
 
669
  "uuid": "a2df4a18-6f19-4772-9532-39307a0e2794",
670
  "gds_version_id": "2.4",
671
  "netcdf_version_id": "4.1",
672
+ "date_created": "20190813T064931Z",
673
+ "start_time": "20000101T000000Z",
674
+ "time_coverage_start": "20000101T000000Z",
675
+ "stop_time": "20000102T000000Z",
676
+ "time_coverage_end": "20000102T000000Z",
677
  "file_quality_level": 3,
678
  "Metadata_Conventions": "Unidata Observation Dataset v1.0",
679
  "metadata_link": "http://podaac.jpl.nasa.gov/ws/metadata/dataset?format=gcmd&shortName=UKMO-L4HRfnd-GLOB-OSTIA",
 
834
  "product": "SEALEVEL_GLO_PHY_L4_MY_008_047",
835
  "dataset_id": "cmems_obs-sl_glo_phy-ssh_my_allsat-l4-duacs-0.125deg_P1D",
836
  "role": "Daily sea-level, geostrophic current, and ice-flag fields sampled at profile points.",
837
+ "file_count": 8979,
838
+ "representative_file": "dt_global_allsat_phy_l4_20000101_20241016.nc",
839
+ "first_file": "dt_global_allsat_phy_l4_20000101_20241016.nc",
840
  "last_file": "dt_global_allsat_phy_l4_20240731_20250429.nc",
841
  "global_attrs": {
842
  "Conventions": "CF-1.6",
 
861
  "standard_name_vocabulary": "NetCDF Climate and Forecast (CF) Metadata Convention Standard Name Table v37",
862
  "summary": "SSALTO/DUACS Delayed-Time Level-4 sea surface height and derived variables measured by multi-satellite altimetry observations over Global Ocean.",
863
  "title": "DT merged all satellites Global Ocean Gridded SSALTO/DUACS Sea Surface Height L4 product and derived variables",
864
+ "date_created": "2024-10-16T01:14:28Z",
865
+ "history": "2024-10-16 01:14:28Z: Creation",
866
  "geospatial_lat_max": 89.9375,
867
  "geospatial_lat_min": -89.9375,
868
  "geospatial_lat_resolution": 0.125,
 
878
  "geospatial_vertical_units": "m",
879
  "time_coverage_duration": "P1D",
880
  "time_coverage_resolution": "P1D",
881
+ "time_coverage_end": "2000-01-01T12:00:00Z",
882
+ "time_coverage_start": "1999-12-31T12:00:00Z",
883
+ "platform": "ERS-2, Topex/Poseidon, Geosat Follow On"
884
  },
885
  "dimensions": {
886
  "latitude": 1440,
 
1106
  "product": "MULTIOBS_GLO_PHY_S_SURFACE_MYNRT_015_013",
1107
  "dataset_id": "cmems_obs-mob_glo_phy-sss_my_multi_P1D",
1108
  "role": "Daily sea-surface salinity, density, and sea-ice fields sampled at profile points.",
1109
+ "file_count": 8979,
1110
+ "representative_file": "dataset-sss-ssd-rep-daily_20000101T1200Z_P20241017T0000Z.nc",
1111
+ "first_file": "dataset-sss-ssd-rep-daily_20000101T1200Z_P20241017T0000Z.nc",
1112
  "last_file": "dataset-sss-ssd-rep-daily_20240731T1200Z_P20260101T0000Z.nc",
1113
  "global_attrs": {
1114
  "Conventions": "CF-1.7",
 
1117
  "institution": "CNR",
1118
  "contact": "servicedesk.cmems@mercator-ocean.eu",
1119
  "netcdf_version_id": "4.9.3-development of Jun 4 2023 14:13:36",
1120
+ "creation_date": "Thu 17 Oct 2024 10:53:20",
1121
  "product_version": "1.1",
1122
  "grid_resolution": "0.125 degrees",
1123
  "software_version": "SSS/SSD HR Processor v1.1",
 
1247
  "sealevel_tpa_correction": "The Copernicus source metadata marks this field as not implemented in the current product version, so values may be NaN."
1248
  }
1249
  },
1250
+ "includes_geotiff_assets": true,
1251
+ "license": "CC-BY-4.0",
1252
+ "license_url": "https://creativecommons.org/licenses/by/4.0/",
1253
+ "attribution_notice": "Use of this package should acknowledge DepthDif and the upstream EN4/ARGO, Copernicus Marine GLORYS, OSTIA, sea-level, and sea-surface-salinity products. See LICENSE for source-provider attribution and citation details."
1254
  }
metadata/stac-item.json CHANGED
@@ -5,7 +5,7 @@
5
  "bbox": [
6
  -999.99,
7
  -999.99,
8
- 179.99985,
9
  168.8678
10
  ],
11
  "geometry": {
@@ -17,11 +17,11 @@
17
  -999.99
18
  ],
19
  [
20
- 179.99985,
21
  -999.99
22
  ],
23
  [
24
- 179.99985,
25
  168.8678
26
  ],
27
  [
@@ -37,9 +37,12 @@
37
  },
38
  "properties": {
39
  "datetime": null,
40
- "start_datetime": "2010-01-01",
41
  "end_datetime": "2024-07-31",
42
- "created": "2026-05-21T06:26:40+00:00"
 
 
 
43
  },
44
  "assets": {
45
  "zarr": {
 
5
  "bbox": [
6
  -999.99,
7
  -999.99,
8
+ 179.999954,
9
  168.8678
10
  ],
11
  "geometry": {
 
17
  -999.99
18
  ],
19
  [
20
+ 179.999954,
21
  -999.99
22
  ],
23
  [
24
+ 179.999954,
25
  168.8678
26
  ],
27
  [
 
37
  },
38
  "properties": {
39
  "datetime": null,
40
+ "start_datetime": "2000-01-01",
41
  "end_datetime": "2024-07-31",
42
+ "created": "2026-06-02T16:56:29+00:00",
43
+ "license": "CC-BY-4.0",
44
+ "license_url": "https://creativecommons.org/licenses/by/4.0/",
45
+ "attribution": "Generated using E.U. Copernicus Marine Service Information and derived from EN4/ARGO, OSTIA, sea-level, and sea-surface-salinity source products. See LICENSE."
46
  },
47
  "assets": {
48
  "zarr": {
requirements-loader.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ numpy
2
+ pandas
3
+ pyarrow
4
+ PyYAML
5
+ rasterio
6
+ torch
7
+ tqdm
8
+ xarray
9
+ zarr