Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve docs #708

Merged
merged 58 commits into from
Dec 12, 2021
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
d781ef3
intersphinx xclim
Dec 9, 2021
feb88e1
Update climpred/classes.py
aaronspring Dec 9, 2021
f38064d
Update climpred/classes.py
aaronspring Dec 9, 2021
445f439
smoothing almost done
Dec 9, 2021
70c8314
smoothing done
Dec 9, 2021
555ff85
classes.py
Dec 9, 2021
533a6cd
Merge branch 'docs' of https://github.com/aaronspring/climpred into docs
Dec 9, 2021
e2b86b8
stats checks reference
Dec 9, 2021
47aa5ea
fix comparison
Dec 9, 2021
a5ae204
fix tutorial
Dec 9, 2021
64182c0
add PredictionEnsemble to API
Dec 9, 2021
b68c639
fix test
Dec 9, 2021
2c42418
alignment.py
Dec 9, 2021
998230d
started with metrics.py
Dec 9, 2021
d45b84d
Update climpred/tutorial.py
aaronspring Dec 10, 2021
0aa78ee
Update climpred/tutorial.py
aaronspring Dec 10, 2021
845bdd8
Update docs/source/conf.py
aaronspring Dec 10, 2021
69c913e
fix \
Dec 10, 2021
7172ee4
Merge branch 'docs' of https://github.com/aaronspring/climpred into docs
Dec 10, 2021
240d452
link to docs more
Dec 10, 2021
c99a67f
fix doctests
Dec 10, 2021
04abd1f
comparisons.py
Dec 10, 2021
a626959
transpose_and_rechunk only ds
Dec 10, 2021
1e858a7
fix
Dec 10, 2021
801137b
fix
Dec 10, 2021
2a088c5
fix .pre-commit pydocstyles ignoring tests
Dec 10, 2021
83fc990
fix tests
Dec 11, 2021
dab8865
new doctests with crps
Dec 11, 2021
ffd8f16
contrib
Dec 11, 2021
af10284
contrib
Dec 11, 2021
59d5113
settingupdata
Dec 11, 2021
1c66821
init datasets
Dec 11, 2021
494d763
docs
Dec 11, 2021
36f8347
try fix
Dec 11, 2021
3bf5680
fix __repr__ doc8 error
Dec 11, 2021
0d1842e
small fix
Dec 11, 2021
8fa69e1
reference
Dec 11, 2021
c23b309
fix
Dec 11, 2021
160ecb3
fix
Dec 11, 2021
ca7b4cb
fix
Dec 11, 2021
79f723f
fix
Dec 11, 2021
0db7160
flake8 on docs
Dec 11, 2021
40ebd2e
fix
Dec 11, 2021
dc87401
refactor hind -> initialized
Dec 11, 2021
4c21f82
use resample_iterations from xskillscore
Dec 11, 2021
782c587
enable pydocstyle
Dec 11, 2021
291cf17
ignore doc8
Dec 12, 2021
ace4528
fix CL
Dec 12, 2021
d9d4e6a
rm flake8 ignores
Dec 12, 2021
b617532
flake8 errors fixed
Dec 12, 2021
4910de9
fix
Dec 12, 2021
125999c
fix bias_removal weeks
Dec 12, 2021
87eb677
fix
Dec 12, 2021
0e6c3be
fix
Dec 12, 2021
7143406
fix weekofyear
Dec 12, 2021
80376f2
Update reference_forecast.rst
aaronspring Dec 12, 2021
c23e1a7
Update classes.py
aaronspring Dec 12, 2021
1b5ebec
fix
Dec 12, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ repos:
hooks:
- id: isort

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.910-1
hooks:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.910-1
hooks:
- id: mypy
exclude: "asv_bench"
additional_dependencies: [
Expand All @@ -44,3 +44,25 @@ repos:
# Dependencies that are typed
numpy,
]

- repo: https://github.com/pycqa/pydocstyle
rev: 6.1.1
hooks:
- id: pydocstyle
args:
- --ignore=D301
- --max-line-length=93
- --convention google # https://google.github.io/styleguide/pyguide.html#Comments

- repo: https://github.com/pycqa/doc8
rev: 0.10.1
hooks:
- id: doc8

- repo: https://github.com/keewis/blackdoc
rev: v0.3.4
hooks:
- id: blackdoc
args:
- --include=*.py
- --exclude=CHANGELOG.rst
139 changes: 85 additions & 54 deletions CHANGELOG.rst

Large diffs are not rendered by default.

62 changes: 45 additions & 17 deletions climpred/alignment.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
"""Align ``initialized`` ``valid_time=init+lead`` with ``observations`` ``time``."""

from typing import Dict, List, Optional, Tuple, Union

import dask
import numpy as np
import xarray as xr
Expand All @@ -7,10 +11,17 @@
from .exceptions import CoordinateError
from .utils import get_multiple_lead_cftime_shift_args, shift_cftime_index

returnType = Tuple[Dict[float, xr.DataArray], Dict[float, xr.CFTimeIndex]]


def return_inits_and_verif_dates(forecast, verif, alignment, reference=None, hist=None):
"""Returns initializations and verification dates for an arbitrary number of leads
per a given alignment strategy.
def return_inits_and_verif_dates(
forecast: xr.Dataset,
verif: xr.Dataset,
alignment: str,
reference: Optional[Union[str, List[str]]] = None,
hist: Optional[xr.Dataset] = None,
) -> returnType:
"""Return initializations and verification dates per a given alignment strategy.

Args:
forecast (``xarray`` object): Prediction ensemble with ``init`` dim renamed to
Expand All @@ -27,7 +38,7 @@ def return_inits_and_verif_dates(forecast, verif, alignment, reference=None, his
against the observations provided. This changes both the set of
initializations and the verification window used at each lead.

Returns:
Return:
inits (dict): Keys are the lead time integer, values are an ``xr.DataArray`` of
initialization dates.
verif_dates (dict): Keys are the lead time integer, values are an
Expand Down Expand Up @@ -81,11 +92,14 @@ def return_inits_and_verif_dates(forecast, verif, alignment, reference=None, his
)
elif alignment == "maximize":
return _maximize_alignment(init_lead_matrix, all_verifs, leads)
else:
raise ValueError


def _maximize_alignment(init_lead_matrix, all_verifs, leads):
"""Returns initializations and verification dates, maximizing the degrees of freedom
at each lead individually.
def _maximize_alignment(
init_lead_matrix: xr.DataArray, all_verifs: xr.DataArray, leads: xr.DataArray
) -> returnType:
"""Return inits and verif dates, maximizing the samples at each lead individually.

See ``return_inits_and_verif_dates`` for descriptions of expected variables.
"""
Expand All @@ -106,9 +120,15 @@ def _maximize_alignment(init_lead_matrix, all_verifs, leads):
return inits, verif_dates


def _same_inits_alignment(init_lead_matrix, valid_inits, all_verifs, leads, n, freq):
"""Returns initializations and verification dates, maintaining a common set of inits
at all leads.
def _same_inits_alignment(
init_lead_matrix: xr.DataArray,
valid_inits: xr.DataArray,
all_verifs: xr.DataArray,
leads: xr.DataArray,
n: int,
freq: str,
) -> returnType:
"""Return inits and verif dates, maintaining a common set of inits at all leads.

See ``return_inits_and_verif_dates`` for descriptions of expected variables.
"""
Expand All @@ -117,14 +137,20 @@ def _same_inits_alignment(init_lead_matrix, valid_inits, all_verifs, leads, n, f
inits = {lead: inits for lead in leads}
verif_dates = {
lead: shift_cftime_index(inits[lead], "time", n, freq)
for (lead, n) in zip(leads, n)
for (lead, n) in zip(leads, n) # type: ignore
}
return inits, verif_dates


def _same_verifs_alignment(init_lead_matrix, valid_inits, all_verifs, leads, n, freq):
"""Returns initializations and verification dates, maintaining a common verification
window at all leads.
def _same_verifs_alignment(
init_lead_matrix: xr.DataArray,
valid_inits: xr.DataArray,
all_verifs: xr.DataArray,
leads: xr.DataArray,
n: int,
freq: str,
) -> returnType:
"""Return inits and verifs, maintaining a common verification window at all leads.

See ``return_inits_and_verif_dates`` for descriptions of expected variables.
"""
Expand All @@ -150,8 +176,10 @@ def _same_verifs_alignment(init_lead_matrix, valid_inits, all_verifs, leads, n,
return inits, verif_dates


def _construct_init_lead_matrix(forecast, n, freq, leads):
"""Returns xr.DataArray of "real time" (init + lead) over all inits and leads.
def _construct_init_lead_matrix(
forecast: xr.Dataset, n: Tuple[int], freq: str, leads: xr.DataArray
) -> xr.DataArray:
"""Return xr.DataArray of "valid time" (init + lead) over all inits and leads.

Arguments:
forecast (``xarray object``): Prediction ensemble with ``init`` dim renamed to
Expand All @@ -162,7 +190,7 @@ def _construct_init_lead_matrix(forecast, n, freq, leads):
``CFTimeIndex.shift(value, str)``.
leads (list, array, xr.DataArray of ints): Leads to return offset for.

Returns:
Return:
init_lead_matrix (``xr.DataArray``): DataArray with x=inits and y=lead with
values corresponding to "real time", or ``init + lead`` over all inits and
leads.
Expand Down
109 changes: 65 additions & 44 deletions climpred/bias_removal.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ def div(a, b):
def leave_one_out(bias, dim):
"""Leave-one-out creating a new dimension 'sample' and fill with np.NaN.

See also: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.LeaveOneOut.html"""
See also:
* https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.LeaveOneOut.html # noqa: E501
"""
bias_nan = []
for i in range(bias[dim].size):
bias_nan.append(
Expand Down Expand Up @@ -277,27 +279,31 @@ def gaussian_bias_removal(
train_init=None,
**metric_kwargs,
):
"""Calc bias based on OPTIONS['seasonality'] and remove bias from py:class:`~climpred.classes.HindcastEnsemble`.
"""Calc bias based on ``OPTIONS['seasonality']`` and remove bias from
py:class:`~climpred.classes.HindcastEnsemble`.

Args:
hindcast (HindcastEnsemble): hindcast.
alignment (str): which inits or verification times should be aligned?
- maximize/None: maximize the degrees of freedom by slicing ``hind`` and
``verif`` to a common time frame at each lead.
- same_inits: slice to a common init frame prior to computing
metric. This philosophy follows the thought that each lead should be
based on the same set of initializations.
- same_verif: slice to a common/consistent verification time frame prior
to computing metric. This philosophy follows the thought that each lead
should be based on the same set of verification dates.

- ``maximize``: maximize the degrees of freedom by slicing ``initialized``
and ``verif`` to a common time frame at each lead.
- ``same_inits``: slice to a common ``init`` frame prior to computing
metric. This philosophy follows the thought that each lead should be
based on the same set of initializations.
- ``same_verif``: slice to a common/consistent verification time frame prior
to computing metric. This philosophy follows the thought that each lead
should be based on the same set of verification dates.

how (str): what kind of bias removal to perform. Select
from ['additive_mean', 'multiplicative_mean','multiplicative_std']. Defaults to 'additive_mean'.
cv (bool or str): Defaults to True.
from ``['additive_mean', 'multiplicative_mean','multiplicative_std']``.
Defaults to ``'additive_mean'``.
cv (bool or str): Defaults to ``True``.

- True: Use cross validation in bias removal function.
- ``True``: Use cross validation in bias removal function.
This excludes the given initialization from the bias calculation.
- 'LOO': see True
- False: include the given initialization in the calculation, which
- ``'LOO'``: see ``True``
- ``False``: include the given initialization in the calculation, which
is much faster and but yields similar skill with a large N of
initializations.

Expand Down Expand Up @@ -401,26 +407,30 @@ def bias_correction(
train_init=None,
**metric_kwargs,
):
"""Calc bias based on OPTIONS['seasonality'] and remove bias from py:class:`~climpred.classes.HindcastEnsemble`.
"""Calc bias based on OPTIONS['seasonality'] and remove bias from
py:class:`~climpred.classes.HindcastEnsemble`.

Args:
hindcast (HindcastEnsemble): hindcast.
alignment (str): which inits or verification times should be aligned?
- maximize/None: maximize the degrees of freedom by slicing ``hind`` and
``verif`` to a common time frame at each lead.
- same_inits: slice to a common init frame prior to computing
metric. This philosophy follows the thought that each lead should be
based on the same set of initializations.
- same_verif: slice to a common/consistent verification time frame prior
to computing metric. This philosophy follows the thought that each lead
should be based on the same set of verification dates.

- ``maximize``: maximize the degrees of freedom by slicing ``initialized``
and ``verif`` to a common time frame at each lead.
- ``same_inits``: slice to a common ``init`` frame prior to computing
metric. This philosophy follows the thought that each lead should be
based on the same set of initializations.
- ``same_verif``: slice to a common/consistent verification time frame prior
to computing metric. This philosophy follows the thought that each lead
should be based on the same set of verification dates.

how (str): what kind of bias removal to perform. Select
from ['additive_mean', 'multiplicative_mean','multiplicative_std']. Defaults to 'additive_mean'.
from ``['additive_mean', 'multiplicative_mean','multiplicative_std']``.
Defaults to ``'additive_mean'``.
cv (bool): Use cross validation in bias removal function. This
excludes the given initialization from the bias calculation. With False,
include the given initialization in the calculation, which is much faster
but yields similar skill with a large N of initializations.
Defaults to True.
Defaults to ``True``.

Returns:
HindcastEnsemble: bias removed hindcast.
Expand All @@ -435,12 +445,16 @@ def bc_func(
cv=False,
**metric_kwargs,
):
"""Wrapping https://github.com/pankajkarman/bias_correction/blob/master/bias_correction.py.
"""Wrapping
https://github.com/pankajkarman/bias_correction/blob/master/bias_correction.py.

Functions to perform bias correction of datasets to remove biases across datasets. Implemented methods include:
- quantile mapping: https://rmets.onlinelibrary.wiley.com/doi/pdf/10.1002/joc.2168)
Functions to perform bias correction of datasets to remove biases across
datasets. Implemented methods include:
- quantile_mapping:
https://rmets.onlinelibrary.wiley.com/doi/pdf/10.1002/joc.2168)
- modified quantile mapping: https://www.sciencedirect.com/science/article/abs/pii/S0034425716302000?via%3Dihub
- scaled distribution mapping (Gamma and Normal Corrections): https://www.hydrol-earth-syst-sci.net/21/2649/2017/
- scaled distribution mapping (Gamma and Normal Corrections):
https://www.hydrol-earth-syst-sci.net/21/2649/2017/
"""
corrected = []
seasonality = OPTIONS["seasonality"]
Expand Down Expand Up @@ -507,7 +521,6 @@ def bc_func(
)
dim_used = dim2 if "member" in forecast.dims else dim

# using bias-correction: https://github.com/pankajkarman/bias_correction/blob/master/bias_correction.py
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
bc = XBiasCorrection(
Expand Down Expand Up @@ -574,22 +587,27 @@ def xclim_sdba(
train_init=None,
**metric_kwargs,
):
"""Calc bias based on grouper to be passed as metric_kwargs and remove bias from py:class:`~climpred.classes.HindcastEnsemble`.
"""Calc bias based on ``grouper`` to be passed as ``metric_kwargs`` and remove bias
from py:class:`~climpred.classes.HindcastEnsemble`.

See climpred.constants.XCLIM_BIAS_CORRECTION_METHODS for implemented methods for ``how``.
See :py:func:`~climpred.constants.XCLIM_BIAS_CORRECTION_METHODS` for implemented
methods for ``how``.

Args:
hindcast (HindcastEnsemble): hindcast.
alignment (str): which inits or verification times should be aligned?
- maximize/None: maximize the degrees of freedom by slicing ``hind`` and
``verif`` to a common time frame at each lead.
- same_inits: slice to a common init frame prior to computing
metric. This philosophy follows the thought that each lead should be
based on the same set of initializations.
- same_verif: slice to a common/consistent verification time frame prior
to computing metric. This philosophy follows the thought that each lead
should be based on the same set of verification dates.
how (str): not used

- ``maximize``: maximize the degrees of freedom by slicing ``initialized``
and ``verif`` to a common time frame at each lead.
- ``same_inits``: slice to a common ``init`` frame prior to computing
metric. This philosophy follows the thought that each lead should be
based on the same set of initializations.
- ``same_verif``: slice to a common/consistent verification time frame prior
to computing metric. This philosophy follows the thought that each lead
should be based on the same set of verification dates.

how (str): methods for bias reduction, see
:py:func:`~climpred.constants.XCLIM_BIAS_CORRECTION_METHODS`
cv (bool): Use cross validation in removal function. This
excludes the given initialization from the bias calculation. With False,
include the given initialization in the calculation, which is much faster
Expand All @@ -609,9 +627,12 @@ def bc_func(
cv=False,
**metric_kwargs,
):
"""Wrapping https://github.com/Ouranosinc/xclim/blob/master/xclim/sdba/adjustment.py.
"""Wrapping
https://github.com/Ouranosinc/xclim/blob/master/xclim/sdba/adjustment.py.

Functions to perform bias correction of datasets to remove biases across datasets. See climpred.constants.XCLIM_BIAS_CORRECTION_METHODS for implemented methods.
Functions to perform bias correction of datasets to remove biases across
datasets. See :py:func:`~climpred.constants.XCLIM_BIAS_CORRECTION_METHODS`
for implemented methods.
"""
seasonality = OPTIONS["seasonality"]
dim = "time"
Expand Down
Loading