Skip to content

Commit

Permalink
Remove outdated imports and old FutureWarnings (#461)
Browse files Browse the repository at this point in the history
<!-- Please ensure the PR fulfills the following requirements! -->
<!-- If this is your first PR, make sure to add your details to the
AUTHORS.rst! -->
### Pull Request Checklist:
- [x] This PR addresses an already opened issue (for bug fixes /
features)
    - This PR fixes #xyz
- [x] (If applicable) Documentation has been added / updated (for bug
fixes / features).
- [x] (If applicable) Tests have been added.
- [x] This PR does not seem to break the templates.
- [x] CHANGELOG.rst has been updated (with summary of main changes).
- [x] Link to issue (:issue:`number`) and pull request (:pull:`number`)
has been added.

### What kind of change does this PR introduce?

* Removes `Union, Optional` imports that aren't used anymore.
* Removes deprecated functions and arguments that are 10+ months old. 

### Does this PR introduce a breaking change?

* Only for people still using the deprecated functions.


### Other information:
  • Loading branch information
RondeauG authored Sep 19, 2024
2 parents ca356af + 5a48376 commit 1af9105
Show file tree
Hide file tree
Showing 18 changed files with 16 additions and 172 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ Breaking changes
* `convert_calendar` in ``clean_up`` now uses `xarray` instead of `xclim`. Keywords aren't compatible between the two, but given that `xclim` will abandon its function, no backwards compatibility was sought. (:pull:`450`).
* `attrs_to_remove` and `remove_all_attrs_except` in ``clean_up`` now use real regex. It should not be too breaking since a `fullmatch()` is used, but `*` is now `.*`. (:pull:`450`).
* Python 3.9 is no longer supported. (:pull:`456`).
* Functions and arguments that were deprecated in `xscen` v0.8.0 or earlier have been removed. (:pull:`461`).

Internal changes
^^^^^^^^^^^^^^^^
Expand Down
115 changes: 1 addition & 114 deletions src/xscen/aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from copy import deepcopy
from pathlib import Path
from types import ModuleType
from typing import Optional, Union

import geopandas as gpd
import numpy as np
Expand All @@ -34,7 +33,6 @@
logger = logging.getLogger(__name__)

__all__ = [
"climatological_mean",
"climatological_op",
"compute_deltas",
"produce_horizon",
Expand All @@ -47,64 +45,6 @@ def _(s):
return s


@parse_config
def climatological_mean(
ds: xr.Dataset,
*,
window: int | None = None,
min_periods: int | None = None,
interval: int = 1,
periods: list[str] | list[list[str]] | None = None,
to_level: str | None = "climatology",
) -> xr.Dataset:
"""Compute the mean over 'year' for given time periods, respecting the temporal resolution of ds.
Parameters
----------
ds : xr.Dataset
Dataset to use for the computation.
window : int, optional
Number of years to use for the time periods.
If left at None and periods is given, window will be the size of the first period.
If left at None and periods is not given, the window will be the size of the input dataset.
min_periods : int, optional
For the rolling operation, minimum number of years required for a value to be computed.
If left at None and the xrfreq is either QS or AS and doesn't start in January, min_periods will be one less than window.
If left at None, it will be deemed the same as 'window'.
interval : int
Interval (in years) at which to provide an output.
periods : list of str or list of lists of str, optional
Either [start, end] or list of [start, end] of continuous periods to be considered.
This is needed when the time axis of ds contains some jumps in time.
If None, the dataset will be considered continuous.
to_level : str, optional
The processing level to assign to the output.
If None, the processing level of the inputs is preserved.
Returns
-------
xr.Dataset
Returns a Dataset of the climatological mean, by calling climatological_op with option op=='mean'.
"""
warnings.warn(
"xs.climatological_mean is deprecated and will be abandoned in a future release. "
"Use xs.climatological_op with option op=='mean' instead.",
category=FutureWarning,
)
return climatological_op(
ds,
op="mean",
window=window,
min_periods=min_periods,
stride=interval,
periods=periods,
rename_variables=False,
to_level=to_level,
horizons_as_dim=False,
)


@parse_config
def climatological_op( # noqa: C901
ds: xr.Dataset,
Expand Down Expand Up @@ -767,24 +707,6 @@ def spatial_mean( # noqa: C901
xarray.Dataset.mean, xarray.Dataset.interp, xesmf.SpatialAverager
"""
kwargs = kwargs or {}
if method == "mean":
warnings.warn(
"xs.spatial_mean with method=='mean' is deprecated and will be abandoned in a future release. "
"Use method=='cos-lat' instead for a more robust but similar method.",
category=FutureWarning,
)
elif method == "interp_coord":
warnings.warn(
"xs.spatial_mean with method=='interp_coord' is deprecated. Use method=='interp_centroid' instead.",
category=FutureWarning,
)
method = "interp_centroid"
if call_clisops:
warnings.warn(
"call_clisops has been renamed and is deprecated. Use spatial_subset instead.",
category=FutureWarning,
)
spatial_subset = call_clisops

if region == "global":
region = {
Expand All @@ -798,21 +720,6 @@ def spatial_mean( # noqa: C901
else:
region["lon_bnds"] = [-180, 180]

if (
(region is not None)
and (region["method"] in region)
and (isinstance(region[region["method"]], dict))
):
warnings.warn(
"You seem to be using a deprecated version of region. Please use the new formatting.",
category=FutureWarning,
)
region = deepcopy(region)
if "buffer" in region:
region["tile_buffer"] = region.pop("buffer")
_kwargs = region.pop(region["method"])
region.update(_kwargs)

if (
(region is not None)
and (spatial_subset is None)
Expand Down Expand Up @@ -873,19 +780,6 @@ def spatial_mean( # noqa: C901
f"weighted mean(dim={[d for d in ds.cf.axes['X'] + ds.cf.axes['Y']]}) using a 'cos-lat' approximation of areacella (in deg2)"
)

# This simply calls .mean() over the spatial dimensions
elif method == "mean":
if "dim" not in kwargs:
kwargs["dim"] = ds.cf.axes["X"] + ds.cf.axes["Y"]

ds_agg = ds.mean(keep_attrs=True, **kwargs)

# Prepare the History field
new_history = (
f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] "
f"xarray.mean(dim={kwargs['dim']}) - xarray v{xr.__version__}"
)

# This calls .interp() to a pair of coordinates
elif method == "interp_centroid":
# Find the centroid
Expand All @@ -896,7 +790,7 @@ def spatial_mean( # noqa: C901
kwargs[ds.cf.axes["Y"][0]] = ds[ds.cf.axes["Y"][0]].mean().values
else:
if region["method"] == "gridpoint":
if len(region["lon"] != 1):
if len(region["lon"]) != 1:
raise ValueError(
"Only a single location should be used with interp_centroid."
)
Expand Down Expand Up @@ -1045,7 +939,6 @@ def produce_horizon( # noqa: C901
periods: list[str] | list[list[str]] | None = None,
warminglevels: dict | None = None,
to_level: str | None = "horizons",
period: list | None = None,
) -> xr.Dataset:
"""
Compute indicators, then the climatological mean, and finally unstack dates in order
Expand Down Expand Up @@ -1084,12 +977,6 @@ def produce_horizon( # noqa: C901
"If you want to use produce_horizon for multiple warming levels, "
"extract the full time series and use the `warminglevels` argument instead."
)
if period is not None:
warnings.warn(
"The 'period' argument is deprecated and will be removed in a future version. Use 'periods' instead.",
category=FutureWarning,
)
periods = [standardize_periods(period, multiple=False)]

all_periods = []
if periods is not None:
Expand Down
1 change: 0 additions & 1 deletion src/xscen/biasadjust.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import logging
from copy import deepcopy
from typing import Optional, Union

import xarray as xr
import xclim as xc
Expand Down
2 changes: 1 addition & 1 deletion src/xscen/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from functools import reduce
from operator import or_
from pathlib import Path
from typing import Any, Optional, Union
from typing import Any

import fsspec as fs
import intake_esm
Expand Down
2 changes: 1 addition & 1 deletion src/xscen/catutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from itertools import chain, combinations, product
from multiprocessing import Pool
from pathlib import Path
from typing import Any, Optional, Union
from typing import Any

import cftime
import netCDF4
Expand Down
2 changes: 1 addition & 1 deletion src/xscen/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
from copy import deepcopy
from functools import wraps
from pathlib import Path
from typing import Any, Optional
from typing import Any

import xarray as xr
import xclim as xc
Expand Down
1 change: 0 additions & 1 deletion src/xscen/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from copy import deepcopy
from pathlib import Path
from types import ModuleType
from typing import Optional, Union

import numpy as np
import xarray as xr
Expand Down
18 changes: 0 additions & 18 deletions src/xscen/ensembles.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from copy import deepcopy
from itertools import chain, groupby
from pathlib import Path
from typing import Optional, Union

import numpy as np
import xarray as xr
Expand Down Expand Up @@ -253,7 +252,6 @@ def generate_weights( # noqa: C901
skipna: bool = True,
v_for_skipna: str | None = None,
standardize: bool = False,
experiment_weights: bool = False,
) -> xr.DataArray:
"""Use realization attributes to automatically generate weights along the 'realization' dimension.
Expand Down Expand Up @@ -291,8 +289,6 @@ def generate_weights( # noqa: C901
Variable to use for skipna=False. If None, the first variable in the first dataset is used.
standardize : bool
If True, the weights are standardized to sum to 1 (per timestep/horizon, if skipna=False).
experiment_weights : bool
Deprecated. Use balance_experiments instead.
Notes
-----
Expand All @@ -309,23 +305,9 @@ def generate_weights( # noqa: C901
xr.DataArray
Weights along the 'realization' dimension, or 2D weights along the 'realization' and 'time/horizon' dimensions if skipna=False.
"""
if experiment_weights is True:
warnings.warn(
"`experiment_weights` has been renamed and will be removed in a future release. Use `balance_experiments` instead.",
category=FutureWarning,
)
balance_experiments = True

if isinstance(datasets, list):
datasets = {i: datasets[i] for i in range(len(datasets))}

if independence_level == "all":
warnings.warn(
"The independence level 'all' is deprecated and will be removed in a future version. Use 'model' instead.",
category=FutureWarning,
)
independence_level = "model"

if independence_level not in ["model", "GCM", "institution"]:
raise ValueError(
f"'independence_level' should be between 'model', 'GCM', and 'institution', received {independence_level}."
Expand Down
1 change: 0 additions & 1 deletion src/xscen/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from collections.abc import Callable, Sequence
from copy import deepcopy
from pathlib import Path
from typing import Optional, Union

import numpy as np
import pandas as pd
Expand Down
1 change: 0 additions & 1 deletion src/xscen/indicators.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from functools import partial
from pathlib import Path
from types import ModuleType
from typing import Optional, Union

import pandas as pd
import xarray as xr
Expand Down
1 change: 0 additions & 1 deletion src/xscen/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from collections.abc import Sequence
from inspect import signature
from pathlib import Path
from typing import Optional, Union
from zipfile import ZipFile

import h5py
Expand Down
5 changes: 2 additions & 3 deletions src/xscen/reduce.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Functions to reduce an ensemble of simulations."""

import warnings
from typing import Optional, Union

import numpy as np
import xarray as xr
Expand Down Expand Up @@ -37,7 +36,7 @@ def build_reduction_data(
2D DataArray of dimensions "realization" and "criteria", to be used as input for ensemble reduction.
"""
warnings.warn(
"This function will be dropped in a future version, as it is now redundant with xclim.ensembles.make_criteria."
"This function will be dropped in v0.11.0, as it is now redundant with xclim.ensembles.make_criteria."
"Either use xclim.ensembles.make_criteria directly (preceded by xclim.ensembles.create_ensemble if needed) or "
"use xscen's reduce_ensemble function to build the criteria and reduce the ensemble in one step.",
FutureWarning,
Expand Down Expand Up @@ -128,7 +127,7 @@ def reduce_ensemble(
You can use py:func:`xscen.utils.unstack_dates` on seasonal or monthly indicators to this end.
"""
warnings.warn(
"This function has been moved to xscen.ensembles.reduce_ensemble. This version will be dropped in a future release.",
"This function has been moved to xscen.ensembles.reduce_ensemble. This version will be dropped in v0.11.0.",
FutureWarning,
)
return reduce_ensemble(
Expand Down
1 change: 0 additions & 1 deletion src/xscen/regrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import warnings
from copy import deepcopy
from pathlib import Path
from typing import Optional, Union

import cartopy.crs as ccrs
import cf_xarray as cfxr
Expand Down
1 change: 0 additions & 1 deletion src/xscen/scripting.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
from io import BytesIO
from pathlib import Path
from traceback import format_exception
from typing import Optional, Union

import xarray as xr
from matplotlib.figure import Figure
Expand Down
1 change: 0 additions & 1 deletion src/xscen/spatial.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import warnings
from collections.abc import Sequence
from pathlib import Path
from typing import Optional, Union

import clisops.core.subset
import dask
Expand Down
2 changes: 0 additions & 2 deletions src/xscen/testing.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"""Testing utilities for xscen."""

from typing import Optional, Union

import cartopy.crs as ccrs
import numpy as np
import pandas as pd
Expand Down
2 changes: 1 addition & 1 deletion src/xscen/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from itertools import chain
from pathlib import Path
from types import ModuleType
from typing import Optional, TextIO, Union
from typing import TextIO

import cftime
import flox.xarray
Expand Down
Loading

0 comments on commit 1af9105

Please sign in to comment.