Skip to content

Commit

Permalink
adjust docstrings for GL01, minor corrections
Browse files Browse the repository at this point in the history
  • Loading branch information
Zeitsperre committed Nov 26, 2024
1 parent 2cac5aa commit c01da2e
Show file tree
Hide file tree
Showing 40 changed files with 1,283 additions and 843 deletions.
3 changes: 2 additions & 1 deletion xclim/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,8 @@ def get_command(self, ctx, cmd_name) -> click.Command: # numpydoc ignore=PR01,R
)
@click.pass_context
def cli(ctx, **kwargs): # numpydoc ignore=PR01
"""Entry point for the command line interface.
"""
Entry point for the command line interface.
Manages the global options.
"""
Expand Down
3 changes: 2 additions & 1 deletion xclim/core/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ def raise_warn_or_log(
err_type: type = ValueError,
stacklevel: int = 1,
):
"""Raise, warn or log an error according.
"""
Raise, warn or log an error according.
Parameters
----------
Expand Down
17 changes: 10 additions & 7 deletions xclim/core/bootstrapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@


def percentile_bootstrap(func: Callable) -> Callable:
"""Decorator applying a bootstrap step to the calculation of exceedance over a percentile threshold.
"""
Decorator applying a bootstrap step to the calculation of exceedance over a percentile threshold.
This feature is experimental.
Expand Down Expand Up @@ -78,7 +79,8 @@ def wrapper(*args, **kwargs): # numpydoc ignore=GL08


def bootstrap_func(compute_index_func: Callable, **kwargs) -> xarray.DataArray:
r"""Bootstrap the computation of percentile-based indices.
r"""
Bootstrap the computation of percentile-based indices.
Indices measuring exceedance over percentile-based thresholds (such as tx90p) may contain artificial discontinuities
at the beginning and end of the reference period used to calculate percentiles. The bootstrap procedure can reduce
Expand All @@ -103,10 +105,6 @@ def bootstrap_func(compute_index_func: Callable, **kwargs) -> xarray.DataArray:
xr.DataArray
The result of func with bootstrapping.
References
----------
:cite:cts:`zhang_avoiding_2005`
Notes
-----
This function is meant to be used by the `percentile_bootstrap` decorator.
Expand All @@ -122,6 +120,10 @@ def bootstrap_func(compute_index_func: Callable, **kwargs) -> xarray.DataArray:
Compute index function using percentile
Average output from index function over all resampled time series
Else compute index function using original percentile
References
----------
:cite:cts:`zhang_avoiding_2005`
"""
# Identify the input and the percentile arrays from the bound arguments
per_key = None
Expand Down Expand Up @@ -236,7 +238,8 @@ def _get_year_label(year_dt) -> str:
def build_bootstrap_year_da(
da: DataArray, groups: dict[Any, slice], label: Any, dim: str = "time"
) -> DataArray:
"""Return an array where a group in the original is replaced by every other groups along a new dimension.
"""
Return an array where a group in the original is replaced by every other groups along a new dimension.
Parameters
----------
Expand Down
81 changes: 52 additions & 29 deletions xclim/core/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@


def doy_from_string(doy: DayOfYearStr, year: int, calendar: str) -> int:
"""Return the day-of-year corresponding to an "MM-DD" string for a given year and calendar.
"""
Return the day-of-year corresponding to an "MM-DD" string for a given year and calendar.
Parameters
----------
Expand All @@ -98,7 +99,8 @@ def doy_from_string(doy: DayOfYearStr, year: int, calendar: str) -> int:


def get_calendar(obj: Any, dim: str = "time") -> str:
"""Return the calendar of an object.
"""
Return the calendar of an object.
Parameters
----------
Expand All @@ -111,16 +113,16 @@ def get_calendar(obj: Any, dim: str = "time") -> str:
dim : str
Name of the coordinate to check (if `obj` is a DataArray or Dataset).
Raises
------
ValueError
If no calendar could be inferred.
Returns
-------
str
The Climate and Forecasting (CF) calendar name.
Will always return "standard" instead of "gregorian", following CF conventions 1.9.
Will always return "standard" instead of "gregorian", following CF-Conventions v1.9.
Raises
------
ValueError
If no calendar could be inferred.
"""
if isinstance(obj, xr.DataArray | xr.Dataset):
return obj[dim].dt.calendar
Expand All @@ -140,7 +142,8 @@ def get_calendar(obj: Any, dim: str = "time") -> str:


def common_calendar(calendars: Sequence[str], join="outer") -> str:
"""Return a calendar common to all calendars from a list.
"""
Return a calendar common to all calendars from a list.
Uses the hierarchy: 360_day < noleap < standard < all_leap.
Expand Down Expand Up @@ -213,7 +216,8 @@ def convert_doy(
missing: Any = np.nan,
dim: str = "time",
) -> xr.DataArray | xr.Dataset:
"""Convert the calendar of day of year (doy) data.
"""
Convert the calendar of day of year (doy) data.
Parameters
----------
Expand Down Expand Up @@ -303,7 +307,8 @@ def convert_doy(


def ensure_cftime_array(time: Sequence) -> np.ndarray | Sequence[cftime.datetime]:
"""Convert an input 1D array to a numpy array of cftime objects.
"""
Convert an input 1D array to a numpy array of cftime objects.
Python's datetime are converted to cftime.DatetimeGregorian ("standard" calendar).
Expand Down Expand Up @@ -345,7 +350,8 @@ def percentile_doy(
beta: float = 1.0 / 3.0,
copy: bool = True,
) -> xr.DataArray:
"""Percentile value for each day of the year.
"""
Percentile value for each day of the year.
Return the climatological percentile over a moving window around each day of the year. Different quantile estimators
can be used by specifying `alpha` and `beta` according to specifications given by :cite:t:`hyndman_sample_1996`.
Expand Down Expand Up @@ -438,7 +444,8 @@ def percentile_doy(


def build_climatology_bounds(da: xr.DataArray) -> list[str]:
"""Build the climatology_bounds property with the start and end dates of input data.
"""
Build the climatology_bounds property with the start and end dates of input data.
Parameters
----------
Expand All @@ -456,7 +463,8 @@ def build_climatology_bounds(da: xr.DataArray) -> list[str]:


def compare_offsets(freqA: str, op: str, freqB: str) -> bool: # noqa
"""Compare offsets string based on their approximate length, according to a given operator.
"""
Compare offsets string based on their approximate length, according to a given operator.
Offset are compared based on their length approximated for a period starting
after 1970-01-01 00:00:00. If the offsets are from the same category (same first letter),
Expand Down Expand Up @@ -495,7 +503,8 @@ def compare_offsets(freqA: str, op: str, freqB: str) -> bool: # noqa


def parse_offset(freq: str) -> tuple[int, str, bool, str | None]:
"""Parse an offset string.
"""
Parse an offset string.
Parse a frequency offset and, if needed, convert to cftime-compatible components.
Expand Down Expand Up @@ -535,7 +544,8 @@ def parse_offset(freq: str) -> tuple[int, str, bool, str | None]:


def construct_offset(mult: int, base: str, start_anchored: bool, anchor: str | None):
"""Reconstruct an offset string from its parts.
"""
Reconstruct an offset string from its parts.
Parameters
----------
Expand Down Expand Up @@ -566,7 +576,8 @@ def construct_offset(mult: int, base: str, start_anchored: bool, anchor: str | N


def is_offset_divisor(divisor: str, offset: str):
"""Check that divisor is a divisor of offset.
"""
Check that divisor is a divisor of offset.
A frequency is a "divisor" of another if a whole number of periods of the
former fit within a single period of the latter.
Expand Down Expand Up @@ -630,7 +641,8 @@ def is_offset_divisor(divisor: str, offset: str):
def _interpolate_doy_calendar(
source: xr.DataArray, doy_max: int, doy_min: int = 1
) -> xr.DataArray:
"""Interpolate from one set of dayofyear range to another.
"""
Interpolate from one set of dayofyear range to another.
Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1
to 365).
Expand Down Expand Up @@ -672,7 +684,8 @@ def _interpolate_doy_calendar(
def adjust_doy_calendar(
source: xr.DataArray, target: xr.DataArray | xr.Dataset
) -> xr.DataArray:
"""Interpolate from one set of dayofyear range to another calendar.
"""
Interpolate from one set of dayofyear range to another calendar.
Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1 to 365).
Expand Down Expand Up @@ -712,7 +725,8 @@ def has_similar_doys(


def resample_doy(doy: xr.DataArray, arr: xr.DataArray | xr.Dataset) -> xr.DataArray:
"""Create a temporal DataArray where each day takes the value defined by the day-of-year.
"""
Create a temporal DataArray where each day takes the value defined by the day-of-year.
Parameters
----------
Expand Down Expand Up @@ -752,7 +766,8 @@ def time_bnds( # noqa: C901
freq: str | None = None,
precision: str | None = None,
):
"""Find the time bounds for a datetime index.
"""
Find the time bounds for a datetime index.
As we are using datetime indices to stand in for period indices, assumptions regarding the period
are made based on the given freq.
Expand Down Expand Up @@ -866,7 +881,8 @@ def shift_time(t): # numpydoc ignore=GL08
def climatological_mean_doy(
arr: xr.DataArray, window: int = 5
) -> tuple[xr.DataArray, xr.DataArray]:
"""Calculate the climatological mean and standard deviation for each day of the year.
"""
Calculate the climatological mean and standard deviation for each day of the year.
Parameters
----------
Expand Down Expand Up @@ -894,7 +910,8 @@ def climatological_mean_doy(
def within_bnds_doy(
arr: xr.DataArray, *, low: xr.DataArray, high: xr.DataArray
) -> xr.DataArray:
"""Return whether array values are within bounds for each day of the year.
"""
Return whether array values are within bounds for each day of the year.
Parameters
----------
Expand All @@ -918,7 +935,8 @@ def within_bnds_doy(
def _doy_days_since_doys(
base: xr.DataArray, start: DayOfYearStr | None = None
) -> tuple[xr.DataArray, xr.DataArray, xr.DataArray]:
"""Calculate dayofyear to days since, or the inverse.
"""
Calculate dayofyear to days since, or the inverse.
Parameters
----------
Expand Down Expand Up @@ -968,7 +986,8 @@ def doy_to_days_since(
start: DayOfYearStr | None = None,
calendar: str | None = None,
) -> xr.DataArray:
"""Convert day-of-year data to days since a given date.
"""
Convert day-of-year data to days since a given date.
This is useful for computing meaningful statistics on doy data.
Expand Down Expand Up @@ -1039,7 +1058,8 @@ def days_since_to_doy(
start: DayOfYearStr | None = None,
calendar: str | None = None,
) -> xr.DataArray:
"""Reverse the conversion made by :py:func:`doy_to_days_since`.
"""
Reverse the conversion made by :py:func:`doy_to_days_since`.
Converts data given in days since a specific date to day-of-year.
Expand Down Expand Up @@ -1106,7 +1126,8 @@ def select_time(
date_bounds: tuple[str, str] | None = None,
include_bounds: bool | tuple[bool, bool] = True,
) -> DataType:
"""Select entries according to a time period.
"""
Select entries according to a time period.
This conveniently improves xarray's :py:meth:`xarray.DataArray.where` and :py:meth:`xarray.DataArray.sel`
with fancier ways of indexing over time elements. In addition to the data `da` and argument `drop`,
Expand Down Expand Up @@ -1252,7 +1273,8 @@ def stack_periods(
align_days: bool = True,
pad_value=dtypes.NA,
):
"""Construct a multi-period array.
"""
Construct a multi-period array.
Stack different equal-length periods of `da` into a new 'period' dimension.
Expand Down Expand Up @@ -1459,7 +1481,8 @@ def stack_periods(
def unstack_periods(
da: xr.DataArray | xr.Dataset, dim: str = "period"
) -> xr.DataArray | xr.Dataset:
"""Unstack an array constructed with :py:func:`stack_periods`.
"""
Unstack an array constructed with :py:func:`stack_periods`.
Can only work with periods stacked with a ``stride`` that divides ``window`` in an odd number of sections.
When ``stride`` is smaller than ``window``, only the center-most stride of each window is kept,
Expand Down
6 changes: 4 additions & 2 deletions xclim/core/cfchecks.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@

@cfcheck
def check_valid(var: xr.DataArray, key: str, expected: str | Sequence[str]):
r"""Check that a variable's attribute has one of the expected values and raise a ValidationError if otherwise.
r"""
Check that a variable's attribute has one of the expected values and raise a ValidationError if otherwise.
Parameters
----------
Expand Down Expand Up @@ -53,7 +54,8 @@ def check_valid(var: xr.DataArray, key: str, expected: str | Sequence[str]):
def cfcheck_from_name(
varname: str, vardata: xr.DataArray, attrs: list[str] | None = None
):
"""Perform cfchecks on a DataArray using specifications from xclim's default variables.
"""
Perform cfchecks on a DataArray using specifications from xclim's default variables.
Parameters
----------
Expand Down
19 changes: 11 additions & 8 deletions xclim/core/datachecks.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
def check_freq(
var: xr.DataArray, freq: str | Sequence[str], strict: bool = True
) -> None:
"""Raise an error if not series has not the expected temporal frequency or is not monotonically increasing.
"""
Raise an error if not series has not the expected temporal frequency or is not monotonically increasing.
Parameters
----------
Expand Down Expand Up @@ -60,7 +61,8 @@ def check_freq(


def check_daily(var: xr.DataArray) -> None:
"""Raise an error if series has a frequency other that daily, or is not monotonically increasing.
"""
Raise an error if series has a frequency other that daily, or is not monotonically increasing.
Parameters
----------
Expand All @@ -76,19 +78,20 @@ def check_daily(var: xr.DataArray) -> None:

@datacheck
def check_common_time(inputs: Sequence[xr.DataArray]) -> None:
"""Raise an error if the list of inputs doesn't have a single common frequency.
"""
Raise an error if the list of inputs doesn't have a single common frequency.
Parameters
----------
inputs : Sequence of xr.DataArray
Input arrays.
Raises
------
ValidationError
- if the frequency of any input can't be inferred
- if inputs have different frequencies
- if inputs have a daily or hourly frequency, but they are not given at the same time of day.
Parameters
----------
inputs : Sequence of xr.DataArray
Input arrays.
"""
# Check all have the same freq
freqs = [xr.infer_freq(da.time) for da in inputs]
Expand Down
Loading

0 comments on commit c01da2e

Please sign in to comment.