|
3 | 3 | from uxarray.io.utils import _get_source_dims_dict, _parse_grid_type |
4 | 4 |
|
5 | 5 |
|
| 6 | +def _open_dataset_with_fallback(filename_or_obj, chunks=None, **kwargs): |
| 7 | + """Internal utility function to open datasets with fallback to netcdf4 engine. |
| 8 | +
|
| 9 | + Attempts to use Xarray's default read engine first, which may be "h5netcdf" |
| 10 | + or "scipy" after v2025.09.0. If that fails (typically for h5-incompatible files), |
| 11 | + falls back to using the "netcdf4" engine. |
| 12 | +
|
| 13 | + Parameters |
| 14 | + ---------- |
| 15 | + filename_or_obj : str, Path, file-like or DataStore |
| 16 | + Strings and Path objects are interpreted as a path to a netCDF file |
| 17 | + or an OpenDAP URL and opened with python-netCDF4, unless the filename |
| 18 | + ends with .gz, in which case the file is gunzipped and opened with |
| 19 | + scipy.io.netcdf (only netCDF3 supported). |
| 20 | + chunks : int, dict, 'auto' or None, optional |
| 21 | + If chunks is provided, it is used to load the new dataset into dask |
| 22 | + arrays. |
| 23 | + **kwargs |
| 24 | + Additional keyword arguments passed to xr.open_dataset |
| 25 | +
|
| 26 | + Returns |
| 27 | + ------- |
| 28 | + xr.Dataset |
| 29 | + The opened dataset |
| 30 | + """ |
| 31 | + try: |
| 32 | + # Try opening with xarray's default read engine |
| 33 | + return xr.open_dataset(filename_or_obj, chunks=chunks, **kwargs) |
| 34 | + except Exception: |
| 35 | + # If it fails, use the "netcdf4" engine as backup |
| 36 | + # Extract engine from kwargs to prevent duplicate parameter error |
| 37 | + engine = kwargs.pop("engine", "netcdf4") |
| 38 | + return xr.open_dataset(filename_or_obj, engine=engine, chunks=chunks, **kwargs) |
| 39 | + |
| 40 | + |
6 | 41 | def _map_dims_to_ugrid( |
7 | 42 | ds, |
8 | 43 | _source_dims_dict, |
@@ -69,7 +104,7 @@ def match_chunks_to_ugrid(grid_filename_or_obj, chunks): |
69 | 104 | # No need to rename |
70 | 105 | return chunks |
71 | 106 |
|
72 | | - ds = xr.open_dataset(grid_filename_or_obj, chunks=chunks) |
| 107 | + ds = _open_dataset_with_fallback(grid_filename_or_obj, chunks=chunks) |
73 | 108 | grid_spec, _, _ = _parse_grid_type(ds) |
74 | 109 |
|
75 | 110 | source_dims_dict = _get_source_dims_dict(ds, grid_spec) |
|
0 commit comments