|
| 1 | +import numpy as np |
1 | 2 | import xarray as xr
|
2 | 3 | from numpy.testing import assert_array_equal
|
3 | 4 | from xarray.testing import assert_equal
|
4 | 5 |
|
5 | 6 | import cf_xarray as cfxr # noqa
|
6 | 7 |
|
7 | 8 | from ..datasets import airds, mollwds, rotds
|
| 9 | +from . import requires_cftime |
8 | 10 |
|
9 | 11 | try:
|
10 | 12 | from dask.array import Array as DaskArray
|
@@ -121,3 +123,36 @@ def test_vertices_to_bounds() -> None:
|
121 | 123 | # 2D case
|
122 | 124 | lon_b = cfxr.vertices_to_bounds(mollwds.lon_vertices, out_dims=("bounds", "x", "y"))
|
123 | 125 | assert_array_equal(mollwds.lon_bounds, lon_b)
|
| 126 | + |
| 127 | + |
| 128 | +@requires_cftime |
| 129 | +def test_bounds_to_vertices_cftime() -> None: |
| 130 | + import cftime |
| 131 | + |
| 132 | + # Create cftime objects for monthly bounds |
| 133 | + periods = 3 |
| 134 | + # start = cftime.DatetimeGregorian(2000, 1, 1) |
| 135 | + edges = [cftime.DatetimeGregorian(2000, m, 1) for m in range(1, periods + 2)] |
| 136 | + |
| 137 | + # Bounds as [start, end) for each month |
| 138 | + bnds = np.array([[edges[i], edges[i + 1]] for i in range(periods)]) |
| 139 | + mid = np.array([edges[i] + (edges[i + 1] - edges[i]) / 2 for i in range(periods)]) |
| 140 | + |
| 141 | + # Sample data |
| 142 | + values = xr.DataArray( |
| 143 | + np.arange(periods, dtype=float), dims=("time",), coords={"time": mid} |
| 144 | + ) |
| 145 | + |
| 146 | + # Build dataset with CF-style bounds |
| 147 | + ds = xr.Dataset( |
| 148 | + {"foo": values}, |
| 149 | + coords={ |
| 150 | + "time": ("time", mid, {"bounds": "time_bounds"}), |
| 151 | + "time_bounds": (("time", "bounds"), bnds), |
| 152 | + "bounds": ("bounds", [0, 1]), |
| 153 | + }, |
| 154 | + ) |
| 155 | + |
| 156 | + time_c = cfxr.bounds_to_vertices(ds.time_bounds, "bounds") |
| 157 | + time_b = cfxr.vertices_to_bounds(time_c, out_dims=("bounds", "time")) |
| 158 | + assert_array_equal(ds.time_bounds, time_b) |
0 commit comments