-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbase.py
More file actions
1865 lines (1616 loc) · 76.8 KB
/
Copy pathbase.py
File metadata and controls
1865 lines (1616 loc) · 76.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import subprocess
import sys
import warnings
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import cftime
import dask.array as da
import netCDF4 as nc
import numpy as np
import psutil
import xarray as xr
from cftime import date2num
from access_moppy.qc import validate_cmip7_output
from access_moppy.utilities import (
FrequencyMismatchError,
IncompatibleFrequencyError,
ResamplingRequiredWarning,
calculate_latitude_bounds,
calculate_longitude_bounds,
calculate_time_bounds,
normalize_cf_time_units,
parse_cmip6_table_frequency,
type_mapping,
validate_and_resample_if_needed,
validate_cmip6_frequency_compatibility,
)
logger = logging.getLogger(__name__)
class DatasetChunker:
"""
Handles rechunking of xarray datasets according to rules introduced in the CMIP7 standard.
Rules:
- Time coordinates: single chunk (no chunking along time for coordinates)
- Time bounds: single chunk (no chunking along time for bounds)
- Data variables: chunked into at least 4MB blocks
"""
def __init__(self, target_chunk_size_mb: float = 4.0):
"""
Initialize the DatasetChunker.
Args:
target_chunk_size_mb: Target chunk size in megabytes for data variables
"""
self.target_chunk_size_mb = target_chunk_size_mb
self.target_chunk_size_bytes = target_chunk_size_mb * 1024 * 1024
def calculate_chunk_size_for_variable(self, var: xr.DataArray) -> Dict[str, int]:
"""
Calculate appropriate chunk sizes for a variable to achieve at least 4MB chunks.
Args:
var: xarray DataArray
Returns:
Dictionary of dimension names to chunk sizes
"""
chunks = {}
# Calculate total elements per chunk needed for minimum target size
element_size = var.dtype.itemsize
min_target_elements = self.target_chunk_size_bytes // element_size
# For time-dependent variables, start with time dimension
if "time" in var.dims:
time_size = var.sizes["time"]
# Calculate elements in other dimensions (spatial elements per time step)
other_elements = 1
for dim in var.dims:
if dim != "time":
other_elements *= var.sizes[dim]
# Determine minimum time steps needed for at least 4MB
if other_elements > 0:
# Calculate minimum time steps needed
min_time_steps = max(
1, (min_target_elements + other_elements - 1) // other_elements
) # Ceiling division
# Don't exceed available time steps
time_chunks = min(time_size, min_time_steps)
else:
time_chunks = time_size
chunks["time"] = time_chunks
# Other dimensions: keep as single chunks for simplicity
for dim in var.dims:
if dim != "time":
chunks[dim] = var.sizes[dim]
else:
# Non-time variables: keep as single chunks
for dim in var.dims:
chunks[dim] = var.sizes[dim]
return chunks
def rechunk_dataset(self, ds: xr.Dataset) -> xr.Dataset:
"""
Apply chunking rules to rechunk the dataset.
Args:
ds: Input xarray Dataset
Returns:
Rechunked xarray Dataset
"""
try:
ds_chunks = ds.chunks
except AttributeError:
logger.debug("Dataset is not chunked, skipping rechunking")
return ds
except ValueError as err:
if "inconsistent chunks along dimension" not in str(err):
raise
logger.debug(
"Dataset has inconsistent chunking across variables; "
"calling unify_chunks() before rechunking"
)
ds = ds.unify_chunks()
ds_chunks = ds.chunks
if not any(ds_chunks.values() if ds_chunks else []):
logger.debug("Dataset is not chunked, skipping rechunking")
return ds
logger.debug(
"Applying dataset rechunking with rules: "
"time coordinates=single chunk, "
"time bounds=single chunk, "
"data variables=at least %sMB chunks",
self.target_chunk_size_mb,
)
rechunked_coords = {}
rechunked_data_vars = {}
for var_name in ds.variables:
var = ds[var_name]
# Apply chunking rules based on variable type
if var_name.endswith("_bnds") or var_name.endswith("_bounds"):
# Time bounds: single chunk for all dimensions
chunks = {dim: var.sizes[dim] for dim in var.dims}
logger.debug(" %s: time bounds -> single chunk", var_name)
elif (
var_name
in [
"time",
"lat",
"lon",
"latitude",
"longitude",
"x",
"y",
"height",
"lev",
]
or var.dims == ()
):
# Coordinate variables and scalars: single chunk
chunks = {dim: var.sizes[dim] for dim in var.dims}
if var.dims:
logger.debug(" %s: coordinate -> single chunk", var_name)
else:
# Data variables: calculate 4MB chunks
chunks = self.calculate_chunk_size_for_variable(var)
chunk_info = ", ".join(
[f"{dim}:{size}" for dim, size in chunks.items()]
)
logger.debug(" %s: data variable -> %s", var_name, chunk_info)
try:
rechunked_var = var.chunk(chunks)
except Exception as e:
logger.warning("Could not rechunk variable '%s': %s", var_name, e)
rechunked_var = var
if var_name in ds.coords:
rechunked_coords[var_name] = rechunked_var
else:
rechunked_data_vars[var_name] = rechunked_var
# Use assign_coords + assign to preserve all dataset metadata
# (coordinate attributes, encoding, and dataset structure)
rechunked_ds = ds.assign_coords(rechunked_coords).assign(rechunked_data_vars)
logger.debug("Dataset rechunking completed")
return rechunked_ds
class CMORiser:
"""
Base class for CMORisers, providing shared logic for CMORisation across different CMIP versions.
"""
type_mapping = type_mapping
def __init__(
self,
input_data: Optional[Union[str, List[str], xr.Dataset, xr.DataArray]] = None,
*,
output_path: str,
vocab: Any,
variable_mapping: Dict[str, Any],
compound_name: str,
drs_root: Optional[Path] = None,
validate_frequency: bool = False,
enable_resampling: bool = False,
resampling_method: str = "auto",
enable_chunking: bool = True,
chunk_size_mb: float = 4.0,
enable_compression: bool = True,
compression_level: int = 4,
# Backward compatibility
input_paths: Optional[Union[str, List[str]]] = None,
):
# Handle backward compatibility and validation
if input_paths is not None and input_data is None:
warnings.warn(
"The 'input_paths' parameter is deprecated. Use 'input_data' instead.",
DeprecationWarning,
stacklevel=2,
)
input_data = input_paths
elif input_paths is not None and input_data is not None:
raise ValueError(
"Cannot specify both 'input_data' and 'input_paths'. Use 'input_data'."
)
elif input_paths is None and input_data is None:
raise ValueError("Must specify either 'input_data' or 'input_paths'.")
# Determine input type and handle appropriately
self.input_is_xarray = isinstance(input_data, (xr.Dataset, xr.DataArray))
if self.input_is_xarray:
# For xarray inputs, store the dataset directly
if isinstance(input_data, xr.DataArray):
self.input_dataset = input_data.to_dataset()
else:
self.input_dataset = input_data
self.input_paths = [] # Empty list for compatibility
else:
# For file paths, store as before
self.input_paths = (
input_data
if isinstance(input_data, list)
else [input_data]
if input_data
else []
)
self.input_dataset = None
self.output_path = output_path
# Extract cmor_name from compound_name
_, self.cmor_name = compound_name.split(".")
self.vocab = vocab
self.mapping = variable_mapping
self.drs_root = Path(drs_root) if drs_root is not None else None
self.version_date = datetime.now().strftime("%Y%m%d")
self.validate_frequency = validate_frequency
self.compound_name = compound_name
self.enable_resampling = enable_resampling
self.resampling_method = resampling_method
self.enable_chunking = enable_chunking
self.enable_compression = enable_compression
self.compression_level = compression_level
self.chunker = (
DatasetChunker(
target_chunk_size_mb=chunk_size_mb,
)
if enable_chunking
else None
)
self.ds = None
def __getitem__(self, key):
return self.ds[key]
def __getattr__(self, attr):
# This is only called if the attr is not found on CMORiser itself
return getattr(self.ds, attr)
def __setitem__(self, key, value):
self.ds[key] = value
def __repr__(self):
return repr(self.ds)
def _is_fx_variable(self) -> bool:
"""Return True when compound_name corresponds to a fixed-field CMIP table."""
if not self.compound_name:
return False
table_id = self.compound_name.split(".", 1)[0].lower()
return table_id.endswith("fx")
def _squeeze_fx_singleton_time(self) -> None:
"""Drop UM-style singleton time axis for fixed (fx) variables."""
if (
self.ds is not None
and self._is_fx_variable()
and "time" in self.ds.dims
and self.ds.sizes.get("time") == 1
):
self.ds = self.ds.isel(time=0, drop=True)
def load_dataset(self, required_vars: Optional[List[str]] = None):
"""
Load dataset from input files or use provided xarray objects with optional frequency validation.
Args:
required_vars: Optional list of required variables to extract
"""
# If input is already an xarray object, use it directly
if self.input_is_xarray:
self.ds = (
self.input_dataset.copy()
) # Make a copy to avoid modifying original
# SAFEGUARD: Convert cftime coordinates to numeric if present
self.ds = self._ensure_numeric_time_coordinates(self.ds)
# Apply variable filtering if required_vars is specified
if required_vars:
available_vars = set(self.ds.data_vars) | set(self.ds.coords)
vars_to_keep = set(required_vars) & available_vars
if vars_to_keep != set(required_vars):
missing_vars = set(required_vars) - available_vars
warnings.warn(
f"Some required variables not found in dataset: {missing_vars}. "
f"Available variables: {available_vars}"
)
# Keep only required data variables
data_vars_to_keep = vars_to_keep & set(self.ds.data_vars)
# Collect dimensions used by these data variables
used_dims = set()
for var in data_vars_to_keep:
used_dims.update(self.ds[var].dims)
# Exclude auxiliary time dimension
if "time_0" in used_dims:
self.ds = self.ds.isel(time_0=0, drop=True)
used_dims.remove("time_0")
# Step 1: Keep only required data variables
self.ds = self.ds[list(data_vars_to_keep)]
# Step 2: Drop coordinates not in used_dims
coords_to_drop = [c for c in self.ds.coords if c not in used_dims]
if coords_to_drop:
self.ds = self.ds.drop_vars(coords_to_drop)
logger.debug(
"Dropped %d unused coordinate(s): %s",
len(coords_to_drop),
coords_to_drop,
)
else:
# If no input files were provided, initialise an empty Dataset.
# This supports self-contained formula calculations (e.g. using
# load_ressource_data nested expressions) that do not need an
# external primary dataset.
if not self.input_paths:
self.ds = xr.Dataset()
return
# Original file-based loading logic
def _preprocess(ds):
ds = ds[list(required_vars & set(ds.data_vars))]
# Canonicalize UM auxiliary time dimensions (time_0/time_1) to
# a single "time" axis when the selected variables use exactly
# one such axis. Keep that primary axis and drop the unused one.
selected_data_vars = list(ds.data_vars)
used_time_dims = {
dim
for var in selected_data_vars
for dim in ds[var].dims
if dim.startswith("time")
}
primary_time_dim = "time" if "time" in used_time_dims else None
if primary_time_dim is None and len(used_time_dims) == 1:
primary_time_dim = next(iter(used_time_dims))
if primary_time_dim and primary_time_dim != "time":
ds = ds.rename({primary_time_dim: "time"})
used_time_dims.discard(primary_time_dim)
used_time_dims.add("time")
aux_time_coords = [
c
for c in ("time_0", "time_1")
if c in ds.coords and c not in used_time_dims
]
if aux_time_coords:
ds = ds.drop_vars(aux_time_coords)
return ds
# Open the first file once to probe its structure. This single handle
# is reused for both the frequency-validation time-independence check
# and the _has_time check below, avoiding a duplicate open and the
# file-handle leak that an unguarded open_dataset would cause.
with xr.open_dataset(self.input_paths[0], decode_cf=False) as _probe:
_probe_dims = set(_probe.dims)
_probe_target_vars = (
[v for v in required_vars if v in _probe.data_vars]
if required_vars
else list(_probe.data_vars)
)
_has_time = any(
any(dim.startswith("time") for dim in _probe[v].dims)
for v in _probe_target_vars
)
# Validate frequency consistency and CMIP6 compatibility before concatenation
# Skip validation for time-independent variables (e.g., areacello, static grids)
if self.validate_frequency and len(self.input_paths) > 0:
# Check if this is a time-dependent variable by examining the compound_name
# Time-independent variables typically have "fx" (fixed) in their table ID
is_time_independent = (
self.compound_name and "fx" in self.compound_name.lower()
) or not any(dim.startswith("time") for dim in _probe_dims)
if is_time_independent:
logger.debug(
"Skipping frequency validation for time-independent variable"
)
else:
try:
# Enhanced validation with CMIP frequency compatibility
# Use CMIP6-specific validation if available, otherwise skip
if (
hasattr(self.vocab, "__class__")
and "CMIP6" in self.vocab.__class__.__name__
):
detected_freq, resampling_required = (
validate_cmip6_frequency_compatibility(
self.input_paths,
self.compound_name,
time_coord="time",
interactive=sys.stdin.isatty(),
)
)
if resampling_required:
logger.debug(
"Temporal resampling will be applied: %s -> CMIP6 target frequency",
detected_freq,
)
else:
logger.debug(
"Validated compatible temporal frequency: %s",
detected_freq,
)
else:
logger.debug(
"Skipping detailed frequency validation for this CMIP version"
)
except (FrequencyMismatchError, IncompatibleFrequencyError) as e:
raise e # Re-raise these specific errors as-is
except InterruptedError as e:
raise e # Re-raise user abort
except Exception as e:
warnings.warn(
f"Could not validate temporal frequency: {e}. "
f"Proceeding with concatenation but results may be inconsistent."
)
if _has_time:
# Multi-variable mappings (e.g. ocean formulas requiring temp +
# rho_dzt + area_t) may source each variable from separate files
# that share identical time axes. Nested concat along time can
# duplicate timestamps in that case, so prefer coordinate-based
# combine when multiple required variables are requested.
prefer_by_coords = bool(required_vars and len(required_vars) > 1)
# One dask chunk per file along time. Sub-monthly inputs (e.g.
# daily tasmax/tasmin) are stored with per-timestep on-disk HDF5
# chunking; the default chunks={} inherits that, so a 31-day file
# becomes 31 chunks and the task graph explodes (~650k tasks over
# a multi-decade run), which is what drives the distributed
# workers out of memory on those variables. Collapsing to one
# chunk per file cuts the graph ~26x and the compute memory ~5x
# with bit-identical results; monthly inputs (time size 1) are
# unaffected.
common_kwargs = {
"engine": "netcdf4",
"decode_cf": False,
"chunks": {"time": -1},
"data_vars": "minimal",
"coords": "minimal",
"compat": "override",
"preprocess": _preprocess,
"parallel": True,
}
if prefer_by_coords:
try:
self.ds = xr.open_mfdataset(
self.input_paths,
combine="by_coords",
**common_kwargs,
)
except Exception as err:
warnings.warn(
"Coordinate-based file combination failed; "
"falling back to nested time concatenation. "
f"Original error: {err}"
)
self.ds = xr.open_mfdataset(
self.input_paths,
combine="nested",
concat_dim="time",
**common_kwargs,
)
else:
self.ds = xr.open_mfdataset(
self.input_paths,
combine="nested", # avoids costly dimension alignment
concat_dim="time",
**common_kwargs,
)
else:
# Time-independent (fx) file — do not add a spurious time dimension
self.ds = xr.open_dataset(
self.input_paths[0],
engine="netcdf4",
decode_cf=False,
chunks={},
)
if required_vars:
vars_to_keep = [v for v in required_vars if v in self.ds.data_vars]
self.ds = self.ds[vars_to_keep]
# UM source files can include a time=1 axis for static fields.
# Keep squeeze behavior centralized in _squeeze_fx_singleton_time().
# UM source files can carry time=1 for fixed fields even when loaded
# through the time-aware branch. Squeeze once here before any downstream
# frequency handling, rechunking, or missing-value normalization.
self._squeeze_fx_singleton_time()
# Apply temporal resampling if enabled and needed
if self.enable_resampling and self.compound_name:
try:
logger.debug(
"Checking if temporal resampling is needed for %s", self.cmor_name
)
self.ds, was_resampled = validate_and_resample_if_needed(
self.ds,
self.compound_name,
self.cmor_name,
time_coord="time",
method=self.resampling_method,
)
if was_resampled:
logger.debug(
"Applied temporal resampling to match CMIP requirements"
)
else:
logger.debug("No resampling needed - frequency already compatible")
except (FrequencyMismatchError, IncompatibleFrequencyError) as e:
raise e # Re-raise validation errors
except Exception as e:
raise RuntimeError(f"Failed to resample dataset: {e}")
elif self.enable_resampling and not self.compound_name:
warnings.warn(
"Resampling enabled but no compound_name provided. "
"Cannot determine target frequency for resampling.",
ResamplingRequiredWarning,
)
# Apply intelligent rechunking if enabled
if self.enable_chunking and self.chunker:
logger.debug("Applying intelligent dataset rechunking...")
self.ds = self.chunker.rechunk_dataset(self.ds)
logger.debug("Dataset rechunking completed")
# Normalize missing values to NaN early for consistent processing
self._normalize_missing_values_early()
def _ensure_numeric_time_coordinates(self, ds: xr.Dataset) -> xr.Dataset:
"""
Convert cftime objects in time-related coordinates to numeric values.
This safeguard prevents TypeError when cftime objects are implicitly
cast to numeric types in downstream operations (e.g., atmosphere.py line 174).
Args:
ds: Input dataset that may contain cftime coordinates
Returns:
Dataset with numeric time coordinates
"""
# List of common time-related coordinate names to check
time_coords = ["time", "time_bnds", "time_bounds"]
for coord_name in time_coords:
if coord_name not in ds.coords:
continue
coord = ds[coord_name]
# Check if coordinate contains cftime objects
if coord.size > 0:
# Get first value to check type
first_val = (
coord.isel({coord.dims[0]: 0}).values.item()
if coord.size > 0
else None
)
if first_val is not None and isinstance(first_val, cftime.datetime):
# Extract time encoding attributes
units = coord.attrs.get("units")
calendar = coord.attrs.get("calendar", "proleptic_gregorian")
if units is None:
warnings.warn(
f"Coordinate '{coord_name}' contains cftime objects but has no 'units' attribute. "
f"Using default: 'days since 0001-01-01'. "
f"Results may be incorrect.",
UserWarning,
)
units = "days since 0001-01-01"
# Convert cftime to numeric
try:
numeric_values = date2num(
coord.values, units=units, calendar=calendar
)
# Create new attributes dict with units and calendar
new_attrs = coord.attrs.copy()
new_attrs["units"] = units
new_attrs["calendar"] = calendar
# Replace coordinate with numeric values, preserving attributes
ds[coord_name] = (coord.dims, numeric_values, new_attrs)
logger.debug(
"Converted '%s' from cftime to numeric (%s, %s)",
coord_name,
units,
calendar,
)
except Exception as e:
warnings.warn(
f"Failed to convert '{coord_name}' from cftime to numeric: {e}. "
f"This may cause errors in downstream processing.",
UserWarning,
)
return ds
def sort_time_dimension(self):
if "time" in self.ds.dims:
self.ds = self.ds.sortby("time")
self._validate_time_axis_integrity()
def _validate_time_axis_integrity(self) -> None:
"""Enforce strict CMOR time-axis requirements.
The time coordinate must be strictly increasing, have no duplicate
timestamps, and contain no gaps for the expected sampling cadence.
"""
if "time" not in self.ds.coords:
return
time_index = self.ds.get_index("time")
duplicated = time_index.duplicated()
if duplicated.any():
duplicate_values = list(dict.fromkeys(time_index[duplicated].tolist()))
preview = duplicate_values[:5]
raise ValueError(
"Time coordinate contains duplicate timestamps. "
f"Found {len(duplicate_values)} duplicated value(s), including: {preview}"
)
if not time_index.is_monotonic_increasing:
raise ValueError(
"Time coordinate is not monotonic increasing after sorting. "
"This indicates an invalid time axis for CMORisation."
)
if len(time_index) < 2:
return
self._validate_time_gaps_from_bounds_or_frequency()
def _validate_time_gaps_from_bounds_or_frequency(self) -> None:
"""Validate that there are no missing timesteps.
Prefer CF time-bounds continuity when available. Otherwise fall back to
coarse frequency-aware checks derived from the target CMIP table.
"""
bounds = self._get_time_bounds_for_gap_validation()
if bounds is not None:
if self._time_bounds_have_gaps(bounds):
raise ValueError(
"Time bounds are not contiguous. Missing or overlapping "
"timesteps detected in the CMOR time axis."
)
return
freq_hint = self._target_frequency_hint()
if freq_hint is None:
return
time_da = self.ds["time"]
time_values = time_da.values
time_units = time_da.attrs.get("units")
# Numeric time coordinates (e.g. 0, 1, 2) are often synthetic in unit
# tests or pre-decoded placeholders. Frequency-fallback checks are not
# reliable there without explicit decoded datetimes, so only apply this
# fallback to datetime-like axes. Bounds-based checks above still apply.
if np.issubdtype(np.asarray(time_values).dtype, np.number):
logger.debug(
"Skipping frequency-fallback gap validation for numeric time axis"
)
return
deltas_days = [
self._time_delta_days(
time_values[i],
time_values[i + 1],
time_units=time_units,
)
for i in range(len(time_values) - 1)
]
if freq_hint == "daily":
invalid = [d for d in deltas_days if not np.isclose(d, 1.0, atol=1e-6)]
elif freq_hint == "monthly":
invalid = [d for d in deltas_days if d < 27.0 or d > 32.0]
elif freq_hint == "yearly":
invalid = [d for d in deltas_days if d < 360.0 or d > 370.0]
else:
invalid = []
if invalid:
raise ValueError(
"Missing timesteps detected in time coordinate for expected "
f"'{freq_hint}' cadence. Invalid interval day-lengths include: {invalid[:5]}"
)
def _get_time_bounds_for_gap_validation(self) -> Optional[xr.DataArray]:
"""Return the time bounds variable when available and shape-compatible."""
time_var = self.ds.get("time")
if time_var is None:
return None
candidate_names = []
bounds_name = time_var.attrs.get("bounds")
if bounds_name:
candidate_names.append(bounds_name)
candidate_names.extend(["time_bnds", "time_bounds", "time_bnd"])
seen = set()
for name in candidate_names:
if name in seen:
continue
seen.add(name)
if name not in self.ds:
continue
bounds = self.ds[name]
if bounds.ndim != 2 or bounds.shape[-1] != 2:
continue
if bounds.shape[0] != self.ds.sizes.get("time"):
continue
return bounds
return None
@staticmethod
def _time_bounds_have_gaps(bounds: xr.DataArray) -> bool:
"""Return True when adjacent intervals are not perfectly contiguous."""
values = bounds.values
if values.shape[0] < 2:
return False
left = values[:-1, 1]
right = values[1:, 0]
if np.issubdtype(np.asarray(left).dtype, np.number):
scale = max(float(np.nanmax(np.abs(values))), 1.0)
atol = scale * 1e-10
return bool(np.any(~np.isclose(left, right, rtol=0.0, atol=atol)))
return bool(np.any(left != right))
@staticmethod
def _time_delta_days(
start: Any, end: Any, time_units: Optional[str] = None
) -> float:
"""Compute day-length between two timestamps for numpy/cftime values."""
diff = end - start
if isinstance(diff, np.timedelta64):
return float(diff / np.timedelta64(1, "s")) / 86400.0
if np.isscalar(diff) and isinstance(
diff, (int, float, np.integer, np.floating)
):
return CMORiser._numeric_delta_to_days(float(diff), time_units)
if hasattr(diff, "total_seconds"):
return float(diff.total_seconds()) / 86400.0
return float(diff.days) + float(getattr(diff, "seconds", 0)) / 86400.0
@staticmethod
def _numeric_delta_to_days(delta: float, time_units: Optional[str]) -> float:
"""Convert numeric coordinate deltas to days using CF units when possible."""
if not time_units:
return delta
interval = str(time_units).split("since", 1)[0].strip().lower()
if interval in {"day", "days", "d"}:
return delta
if interval in {"hour", "hours", "hr", "hrs", "h"}:
return delta / 24.0
if interval in {"minute", "minutes", "min", "mins", "m"}:
return delta / 1440.0
if interval in {"second", "seconds", "sec", "secs", "s"}:
return delta / 86400.0
return delta
@staticmethod
def _days_to_numeric_units(days: float, time_units: Optional[str]) -> float:
"""Convert day-length values back to the numeric coordinate units."""
if not time_units:
return days
interval = str(time_units).split("since", 1)[0].strip().lower()
if interval in {"day", "days", "d"}:
return days
if interval in {"hour", "hours", "hr", "hrs", "h"}:
return days * 24.0
if interval in {"minute", "minutes", "min", "mins", "m"}:
return days * 1440.0
if interval in {"second", "seconds", "sec", "secs", "s"}:
return days * 86400.0
return days
def _align_subdaily_point_time_to_square_grid(self) -> None:
"""Align point-sampled sub-daily timestamps to day-boundary slots.
Some ACCESS streams begin point-sampled sub-daily series at +3h/+6h.
WCRP TIME001 expects these frequencies to be square on the canonical
daily grid. Shift the whole time axis (and time bounds if present) by
that leading offset.
"""
if "time" not in self.ds.coords or self.cmor_name not in self.ds:
return
table_id = (self.compound_name or "").split(".", 1)[0]
table_hours = {
"3hr": 3.0,
"3hrPt": 3.0,
"6hrPlevPt": 6.0,
}
target_hours = table_hours.get(table_id)
if target_hours is None:
return
cell_methods = str(self.ds[self.cmor_name].attrs.get("cell_methods", ""))
if "time: point" not in cell_methods:
return
time_da = self.ds["time"]
values = np.asarray(time_da.values)
if values.size == 0 or not np.issubdtype(values.dtype, np.number):
return
time_units = time_da.attrs.get("units")
if not isinstance(time_units, str) or "since" not in time_units:
return
first_value = float(values.flat[0])
first_days = self._numeric_delta_to_days(first_value, time_units)
leading_offset_days = first_days - np.floor(first_days)
if np.isclose(leading_offset_days, 0.0, atol=1e-10):
return
target_days = target_hours / 24.0
if not np.isclose(leading_offset_days, target_days, atol=1e-8):
return
shift_units = self._days_to_numeric_units(leading_offset_days, time_units)
self.ds["time"] = xr.DataArray(
values - shift_units,
dims=time_da.dims,
coords=time_da.coords,
attrs=time_da.attrs,
)
bounds_name = time_da.attrs.get("bounds")
if isinstance(bounds_name, str) and bounds_name in self.ds:
bnds = self.ds[bounds_name]
if np.issubdtype(np.asarray(bnds.values).dtype, np.number):
self.ds[bounds_name] = xr.DataArray(
bnds.values - shift_units,
dims=bnds.dims,
coords=bnds.coords,
attrs=bnds.attrs,
)
logger.debug(
"Shifted '%s' time axis by %.6f %s to align sub-daily point timestamps",
self.cmor_name,
shift_units,
time_units.split("since", 1)[0].strip(),
)
def rechunk_dataset(self):
"""
Apply intelligent rechunking to the dataset.
This method can be called separately from load_dataset if rechunking
is needed at a different stage in the processing pipeline.
"""
if self.enable_chunking and self.chunker and self.ds is not None:
logger.debug("Applying dataset rechunking...")
self.ds = self.chunker.rechunk_dataset(self.ds)
logger.debug("Dataset rechunking completed")
else:
if not self.enable_chunking:
logger.debug("Chunking is disabled, skipping rechunking")
elif not self.chunker:
logger.debug("No chunker available, skipping rechunking")
else:
logger.debug("No dataset loaded, cannot rechunk")
def _target_frequency_hint(self):
"""Map the CMOR table's target frequency to a coarse label
("daily"/"monthly"/"yearly") for time-bounds construction.
Used only as a fallback when the time axis has a single point and the
frequency cannot be inferred from point spacing. Returns None when the
frequency is not determinable or is sub-daily.
"""
if not self.compound_name:
return None
try:
target = parse_cmip6_table_frequency(self.compound_name)
except Exception:
return None
days = target.total_seconds() / 86400
if 0.9 <= days <= 1.1:
return "daily"
if 28 <= days <= 31:
return "monthly"
if 360 <= days <= 366:
return "yearly"
return None
def calculate_missing_bounds_variables(self, bnds_required):
"""Calculate missing bounds variables for coordinates."""
for bnds_var in bnds_required:
# Extract coordinate name by removing "_bnds" suffix
coord_name = bnds_var.replace("_bnds", "")
if bnds_var not in self.ds.data_vars and bnds_var not in self.ds.coords:
if coord_name not in self.ds.coords:
raise ValueError(
f"Cannot calculate bounds '{bnds_var}': coordinate '{coord_name}' not found. "
f"Available coordinates: {sorted(self.ds.coords)}"
)
# Warn user that bounds are missing and will be calculated automatically
warnings.warn(
f"'{bnds_var}' not found in raw data. Automatically calculating bounds for '{coord_name}' coordinate.",
UserWarning,
stacklevel=3,
)
# Determine which calculation function to use based on coordinate name
if coord_name in ["time", "t"]:
# Calculate time bounds - atmosphere uses "bnds"
self.ds[bnds_var] = calculate_time_bounds(
self.ds,
time_coord=coord_name,
bnds_name="bnds", # Atmosphere uses "bnds"
# Fallback for a single time point (e.g. one resampled
# year) where the frequency cannot be inferred.
freq_hint=self._target_frequency_hint(),
)