Skip to content

Commit

Permalink
Merge pull request #1149 from PCMDI/lee1043_improve_docstrings_20240926
Browse files Browse the repository at this point in the history
Improve doc and enable more functions in API doc
  • Loading branch information
lee1043 authored Sep 26, 2024
2 parents e4f5aa2 + 241ea0d commit 66fc459
Show file tree
Hide file tree
Showing 9 changed files with 391 additions and 20 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ Release Notes and History

| <div style="width:300%">[Versions]</div> | Update summary |
| ------------- | ------------------------------------- |
| [v3.6.1] | Technical update, additional QC repair functions
| [v3.6] | New capability (regional application of precip variability) and technical update
| [v3.5.2] | Technical update, QC tools, new modes for modes of variability metrics (PSA1, PSA2)
| [v3.5.1] | Technical update
Expand Down Expand Up @@ -147,6 +148,7 @@ Release Notes and History


[Versions]: https://github.com/PCMDI/pcmdi_metrics/releases
[v3.6.1]: https://github.com/PCMDI/pcmdi_metrics/releases/tag/v3.6.1
[v3.6]: https://github.com/PCMDI/pcmdi_metrics/releases/tag/v3.6
[v3.5.2]: https://github.com/PCMDI/pcmdi_metrics/releases/tag/v3.5.2
[v3.5.1]: https://github.com/PCMDI/pcmdi_metrics/releases/tag/v3.5.1
Expand Down
16 changes: 12 additions & 4 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@ APIs for Developers

.. currentmodule:: pcmdi_metrics

Below is a list of APIs available in `pcmdi_metrics (> v3.6)` for developers.
Below is a list of APIs available in `pcmdi_metrics (> v3.6.1)` for developers.

Data load
~~~~~~~~~
.. autosummary::
:toctree: generated/

io.xcdat_open


Land-sea mask
Expand All @@ -29,7 +36,7 @@ Grid and regrid


Custom calendars
~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
.. autosummary::
:toctree: generated/

Expand Down Expand Up @@ -67,13 +74,14 @@ Retrieve data from xarray Dataset
io.select_subset


Quality control (QC)
~~~~~~~~~~~~~~~~~~~~
Quality control (QC) and repair
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
:toctree: generated/

utils.check_daily_time_axis
utils.check_monthly_time_axis
utils.regenerate_time_axis


Miscellaneous tools
Expand Down
1 change: 1 addition & 0 deletions pcmdi_metrics/io/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from .xcdat_dataset_io import ( # noqa # isort:skip
da_to_ds,
get_axis_list,
get_calendar,
get_data_list,
get_grid,
get_latitude_bounds_key,
Expand Down
65 changes: 62 additions & 3 deletions pcmdi_metrics/io/xcdat_dataset_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,8 @@ def get_time_bounds_key(ds: Union[xr.Dataset, xr.DataArray]) -> str:
str
The key for the time bounds.
"""

lat_key = get_time_key(ds)
return ds[lat_key].attrs["bounds"]
time_key = get_time_key(ds)
return ds[time_key].attrs["bounds"]


def get_latitude_bounds_key(ds: Union[xr.Dataset, xr.DataArray]) -> str:
Expand Down Expand Up @@ -456,3 +455,63 @@ def get_grid(
lat_bnds_key = get_latitude_bounds_key(d)
lon_bnds_key = get_longitude_bounds_key(d)
return d[[lat_key, lon_key, lat_bnds_key, lon_bnds_key]]


def get_calendar(d: Union[xr.Dataset, xr.DataArray]) -> str:
"""
Get the calendar type from an xarray Dataset or DataArray.
Parameters
----------
d : xarray.Dataset or xarray.DataArray
The input xarray object containing a time dimension.
Returns
-------
str
The calendar type as a string (e.g., 'proleptic_gregorian', 'noleap', '360_day').
Raises
------
ValueError
If no time dimension is found in the input.
AttributeError
If the calendar information cannot be extracted from the time dimension.
Notes
-----
This function first attempts to retrieve the calendar from the time dimension's
encoding. If that fails, it tries to get the calendar from the time dimension's
datetime accessor. If both methods fail, it raises an AttributeError.
Examples
--------
>>> import xarray as xr
>>> import pandas as pd
>>> dates = xr.cftime_range('2000-01-01', periods=365)
>>> ds = xr.Dataset({'time': dates, 'data': ('time', range(365))})
>>> get_calendar(ds)
'standard'
See Also
--------
get_time : Function to extract the time dimension from a Dataset or DataArray.
"""
time = get_time(d)

if time is None:
raise ValueError("No time dimension found in the input.")

try:
calendar = time.encoding.get("calendar")
if calendar is not None:
return calendar
except AttributeError:
pass

try:
return time.dt.calendar
except AttributeError:
raise AttributeError(
"Unable to determine calendar type from the time dimension."
)
15 changes: 9 additions & 6 deletions pcmdi_metrics/io/xcdat_openxml.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,27 @@
def xcdat_open(
infile: Union[str, list], data_var: str = None, decode_times: bool = True
) -> xr.Dataset:
"""Open input file (netCDF, or xml generated by cdscan)
"""
Open input file (netCDF, or xml generated by cdscan)
Parameters
----------
infile : Union[str, list]
list of string, or string, for path of file(s) to open using xcdat
list of string, or string, for path of file(s) to open using xcdat.
data_var : str, optional
key of the non-bounds data variable to keep in the Dataset, alongside any existing bounds data variables, by default None, which loads all data variables
key of the non-bounds data variable to keep in the Dataset, alongside any existing bounds data variables.
By default None, which loads all data variables.
decode_times : bool, optional
If True, attempt to decode times encoded in the standard NetCDF datetime format into cftime.datetime objects. Otherwise, leave them encoded as numbers. This keyword may not be supported by all the backends, by default True
If True, attempt to decode times encoded in the standard NetCDF datetime format into cftime.datetime objects.
Otherwise, leave them encoded as numbers. This keyword may not be supported by all the backends, by default True.
Returns
-------
xr.Dataset
xarray dataset opened via xcdat
Usage
-----
Examples
--------
>>> from pcmdi_metrics.io import xcdat_open
# Open a single netCDF file
>>> ds = xcdat_open('mydata.nc')
Expand Down
6 changes: 6 additions & 0 deletions pcmdi_metrics/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@
generate_calendar_months,
subset_timesteps_in_custom_season,
)
from .dates import (
extract_date_components,
find_overlapping_dates,
regenerate_time_axis,
replace_date_pattern,
)
from .grid import (
calculate_area_weights,
calculate_grid_area,
Expand Down
Loading

0 comments on commit 66fc459

Please sign in to comment.