xCDAT / xcdat

An extension of xarray for climate data analysis on structured grids.
https://xcdat.readthedocs.io/en/latest/
Apache License 2.0
101 stars 11 forks source link

Add Z axis support for spatial averaging #596

Open tomvothecoder opened 5 months ago

tomvothecoder commented 5 months ago

Discussed in https://github.com/xCDAT/xcdat/discussions/591

Originally posted by **tomvothecoder** January 29, 2024 ### Is your feature request related to a problem? I'm running into a case where I need to average over the Z axis. The CDAT code being used is `cdutil.averager(tvar, axis="z")`, which I need to replace. xCDAT's [spatial averager](https://xcdat.readthedocs.io/en/stable/generated/xarray.Dataset.spatial.average.html#xarray.Dataset.spatial.average), which is based on `cdutil.averager()`, only supports rectilinear grids ("X" and "Y"). However, we do mention that the `get_weights()` method can be extended to support other axes: https://github.com/xCDAT/xcdat/blob/fbf1db68fd6328d5a534e0c1e57e22e6fdd70c76/xcdat/spatial.py#L246-L252 ### Are there are any possible answers you came across? _No response_ ### Describe alternatives you've considered _No response_ ### Additional context For the short-term, I might be able to use [xarray.DataArray.weighted](https://docs.xarray.dev/en/stable/generated/xarray.DataArray.weighted.html) directly. However, I still need to generate the weights xr.DataArray beforehand. ```python datarray.weighted(weights).mean("height") ```
pochedls commented 5 months ago

@tomvothecoder - FYI - I thought this might only be a couple lines and took a look. It ended up being a little more than I thought, but I committed a working prototype because I thought it might be helpful (needs validation, review to make sure the docs are updated correctly, and unit tests). It could be possible to combine some of the _get_XYZ_weights functionality, but maybe it is fine as-is. We can delete the branch if you have something in progress already. Or I can open a PR.

tomvothecoder commented 5 months ago

@pochedls Thanks for taking a stab at this so quickly! You can open a PR and tag me for review.

As a temporary workaround in e3sm_diags, I created a _get_z_weights() function that is based on xCDAT logic. I am planning on replacing it whenever xCDAT supports generating weights for the Z axis, which now seems sooner rather than later.