harbor run -t openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0387harbor download openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0387Harder: Self-contained xarray-like API with Cupy-backed arrays and parallelized GroupBy
Task
Enhance and harden the minimal, self-contained xarray-like API you will implement under /app/ to satisfy the provided pytest tests, including Cupy-backed arrays and a duck-typed where function. The solution must be self-contained (no real xarray dependency) and expose a lightweight Dataset and DataArray API with a Cupy-aware duck-typed where utility.
What to implement
1) Package structure (unchanged layout, stricter guarantees)
- Create a package at /app/xarray with:
- __init__.py that exposes a lightweight, xarray-like API (Dataset, DataArray) and a minimal duck-typed array interface compatible with Cupy.
- core/duck_array_ops.py with a where function compatible with Cupy arrays, falling back to NumPy when Cupy is not available.
- The package must be importable as xarray (i.e., import xarray should succeed in tests).
2) Core classes and signatures (enhanced correctness and robustness)
- Dataset
- __init__(self, data_vars: dict, coords: dict)
- data_vars: mapping from var_name to a tuple (dims, data) where:
- dims is a tuple of dimension names, e.g. ("time", "location")
- data is a NumPy array (tests may replace with Cupy arrays later)
- coords: mapping from dimension name to coordinate values (e.g., "time": times, "location": ["IA","IN","IL"])
- Validation: raise meaningful errors on inconsistent shapes or missing required keys. Do not crash silently on mismatches.
- __getitem__(self, key: str) -> DataArray
- Return a DataArray corresponding to the variable named key (e.g., "tmin" or "tmax").
- Attribute-style access (ds.tmax)
- ds.tmax should yield a DataArray-like object with a .data attribute that can be reassigned (the tests set ds.tmax.data = cp.asarray(ds.tmax.data)).
- Compatibility: ds["tmin"] should also return a DataArray for operations like (ds["tmin"] <= 0).
3) DataArray
- DataArray
- __init__(self, data, dims: tuple[str, ...], coords: dict[str, Any])
- data: a NumPy or Cupy array (tests may replace .data with cp.asarray)
- dims: e.g., ("time", "location")
- coords: dict mapping dimension names to coordinate arrays (e.g., {"time": times, "location": ["IA","IN","IL"]})
- @property data
- Access to the underlying array (NumPy or Cupy). Tests will replace this with Cupy arrays.
- __le__(self, other) -> DataArray
- Implement elementwise comparison, returning a new DataArray with the same dims and coords, and data being the result of self.data <= other, using Cupy semantics when data is a Cupy array.
- groupby(self, by: str) -> _GroupBy
- Support grouping by strings of the form "time.month" when the DataArray has a "time" dimension with a corresponding "time" coordinate (tests provide a pandas DatetimeIndex for time).
- Return a _GroupBy-like object that can be reduced with mean(dim).
4) GroupBy
- _GroupBy
- __init__(self, dataarray: DataArray, by: str)
- Store the parent DataArray and the grouping specification (e.g., "time.month").
- mean(self, dim: str) -> DataArray
- Implement the calendar-month grouping along the specified dimension.
- For grouping by "time.month" and dim == "time", compute the mean across the time dimension within each calendar month.
- Implementation specifics:
- Determine months for each time index from the coordinates (times[i].month) using the "time" coordinate.
- For each calendar month 1..12, compute the mean of dataarray.data[idxs, :] over the time indices idxs where month matches.
- Return a new DataArray with:
- data: an array (Cupy if input was Cupy) of shape (12, location_count) representing mean per month per location.
- dims: ("month", "location")
- coords: include "month": [1,2,...,12] and existing "location" coords from the original DataArray.
- Performance/parallelism: implement the per-month mean computations in parallel using a ThreadPoolExecutor to demonstrate a parallel, CPU-bound approach. This mirrors a realistic approach for large data where months can be processed independently.
- Edge cases:
- If there are empty time indices for a given month, return NaN for that month (or a well-defined fallback) and ensure the result maintains the correct dtype.
- If the input time dimension is missing or malformed, raise a clear error.
- The tests only require that the resulting .data is a Cupy array in the grouped result, but the implementation should be correct and parallelized.
5) Duck array operations: where
- /app/xarray/core/duck_array_ops.py
- def where(condition, x, y):
- Return cupy.where(condition, x, y) if Cupy is available and inputs are Cupy arrays or compatible.
- Ensure it gracefully falls back to NumPy when Cupy is not installed or inputs are NumPy arrays.
- The function should be usable with Cupy-backed boolean conditions and data, as used by the tests.
6) Behavior and compatibility notes (hardening for robustness)
- The implementation must be self-contained and not rely on the real external xarray package.
- The tests use Cupy arrays. Ensure all operations that operate on data use Cupy when the underlying data is a Cupy array. If data is NumPy-based, fall back gracefully and allow reassignment of .data to Cupy with cp.asarray in tests.
- The where function must be importable as from xarray.core.duck_array_ops import where and must return a Cupy ndarray when Cupy is present and inputs are Cupy-compatible.
- Design approach:
- Keep a minimal but consistent API surface: Dataset, DataArray, and GroupBy-like behavior.
- Implement a small, explicit duck-typed path for Cupy arrays. Avoid importing the real xarray package.
- Use a small internal DataArray class to track dims and coords; remain duck-typed to support only what tests exercise.
- Prefer explicit validation and clear error messages for misuse or mismatched shapes.
7) Location to implement
- All code must be placed under /app/xarray/ (as a package) with the following structure:
- /app/xarray/__init__.py
- /app/xarray/core/duck_array_ops.py
8) Acceptance criteria
- The tests provided in the prompt pass:
- test_cupy_import passes (Cupy is installed in the test environment and importable).
- test_check_data_stays_on_gpu passes: the boolean result from groupby mean produces a Cupy ndarray in DataArray.data.
- test_where passes: where function from xarray.core.duck_array_ops returns a Cupy ndarray and its result is truthy after .all().
- Performance and concurrency:
- GroupBy.mean uses parallel computation (ThreadPoolExecutor) for per-month reductions to demonstrate concurrency and responsiveness on large data.
- Edge cases:
- Empty or degenerate inputs are handled gracefully with explicit errors or well-defined defaults (e.g., NaNs for empty months).
- Compatibility:
- The API remains intentionally small and dependency-free aside from Cupy for accelerated arrays, with NumPy as a safe fallback.
Deliverable
- A working /app/xarray package implementing the above subset of an xarray-like API, enough for the tests to run and pass, with the specified class/method signatures and behaviors, including a parallelized GroupBy mean path and Cupy-aware duck-array operations.