The previous notebook covered the most common utilities of xclim.sdba for conventionnal cases. Here we explore more advanced usage of xclim.sdba tools.

Adjustment processes can be very heavy when we need to compute them over large regions and long timeseries. Using small groupings (like time.dayofyear ) adds precision and robustness, but also decuplates the load and computing complexity. Fortunately, unlike the heroic pioneers of scientific computing who managed to write parallelized Fortran, we now have dask. With only a few parameters, we can magically distribute the computing load to multiple workers and threads.

A good first read on the use of dask within xarray are the latter’s Optimization tips.

Some xclim.sdba-specific tips:

• Most adjustment method will need to perform operation on the whole time coordinate, so it is best to optimize chunking along the other dimensions. This is often different from how public data is shared, where more universal 3D chunks are used.

Chunking of outputs can be controlled in xarray’s to_netcdf. We also suggest using Zarr files. According to its creators, zarr stores should give better performances, especially because of their better ability for parallel I/O. See Dataset.to_zarr and this useful rechunking package.

• One of the main bottleneck for adjustments with small groups is that dask needs to build and optimize an enormous task graph. This issue has been greatly reduced with xclim 0.27 and the use of map_blocks in the adjustment methods. However, not all adjustment methods use this optimized syntax.

In order to help dask, one can split the processing in parts. For splitting traning and adjustment, see the section below.

• Another massive bottleneck of parallelization of xarray is the thread-locking behaviour of some methods. It is quite difficult to isolate and avoid those lockings, so one of the best workaround is to use Dask configurations with many processes and few threads. The former do not share memory and thus are not impacted when a lock is activated from a thread in another worker. However, this adds many memory transfer operations and, by experience, reduces dask’s ability to parallelize some pipelines. Such a dask Client is usually created with a large n_workers and a small threads_per_worker.

• Sometimes, datasets have auxiliary coordinates (for example : lat / lon in a rotated pole dataset). Xarray handles these variables as data variables and will not load them if dask is used. However, in some operations, xclim or xarray will trigger an access to those variables, triggering computations each time, since they are dask-backed. To avoid this behaviour, one can load the coordinates, or simply remove them from the inputs.

## LOESS smoothing and detrending

As described in Cleveland (1979), locally weighted linear regressions are multiple regression methods using a nearest-neighbor approach. Instead of using all data points to compute a linear or polynomial regression, LOESS algorithms compute a local regression for each point in the dataset, using only the k-nearest neighbors as selected by a weighting function. This weighting function must fulfill some strict requirements, see the doc of xclim.sdba.loess.loess_smoothing for more details.

In xclim’s implementation, the user can choose between local constancy ($$d=0$$, local estimates are weighted averages) and local linearity ($$d=1$$, local estimates are taken from linear regressions). Two weighting functions are currently implemented : “tricube” ($$w(x) = (1 - x^3)^3$$) and “gaussian” ($$w(x) = e^{-x^2 / 2\sigma^2}$$). Finally, the number of Cleveland’s robustifying iterations is controllable through niter. After computing an estimate of $$y(x)$$, the weights are modulated by a function of the distance between the estimate and the points and the procedure is started over. These iterations are made to weaken the effect of outliers on the estimate.

The next example shows the application of the LOESS to daily temperature data. The black line and dot are the estimated $$y$$, outputs of the sdba.loess.loess_smoothing function, using local linear regression (passing $$d = 1$$), a window spanning 20% ($$f = 0.2$$) of the domain, the “tricube” weighting function and only one iteration. The red curve illustrates the weighting function on January 1st 2014, where the red circles are the nearest-neighbors used in the estimation.

[1]:

import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from xclim.sdba import loess

%matplotlib inline

[2]:

# Daily temperature data from xarray's tutorials
ds = xr.tutorial.open_dataset("air_temperature").resample(time="D").mean()
tas = ds.isel(lat=0, lon=0).air

# Compute the smoothed series
f = 0.2
ys = loess.loess_smoothing(tas, d=1, weights="tricube", f=f, niter=1)

# Plot data points and smoothed series
fig, ax = plt.subplots()
ax.plot(tas.time, tas, "o", fillstyle="none")
ax.plot(tas.time, ys, "k")
ax.set_xlabel("Time")
ax.set_ylabel("Temperature [K]")

## The code below calls internal functions to demonstrate how the weights are computed.

# LOESS algorithms as implemented here use scaled coordinates.
x = tas.time
x = (x - x[0]) / (x[-1] - x[0])
xi = x[366]
ti = tas.time[366]

# Weighting function take the distance with all neighbors scaled by the r parameter as input
r = int(f * tas.time.size)
h = np.sort(np.abs(x - xi))[r]
weights = loess._tricube_weighting(np.abs(x - xi).values / h)

# Plot nearest neighbors and weighing function
wax = ax.twinx()
wax.plot(tas.time, weights, color="indianred")
ax.plot(
tas.time, tas.where(tas * weights > 0), "o", color="lightcoral", fillstyle="none"
)

ax.plot(ti, ys[366], "ko")
wax.set_ylabel("Weights")
plt.show()


LOESS smoothing can suffer from heavy boundary effects. On the previous graph, we can associate the strange bend on the left end of the line to them. The next example shows a stronger case. Usually, $$\frac{f}{2}N$$ points on each side should be discarded. On the other hand, LOESS has the advantage of always staying within the bounds of the data.

### LOESS Detrending

In climate science, it can be used in the detrending process. xclim provides sdba.detrending.LoessDetrend in order to compute trend with the LOESS smoothing and remove them from timeseries.

First we create some toy data with a sinusoidal annual cycle, random noise and a linear temperature increase.

[3]:

time = xr.cftime_range("1990-01-01", "2049-12-31", calendar="noleap")
tas = xr.DataArray(
(
10 * np.sin(time.dayofyear * 2 * np.pi / 365)
+ 5 * (np.random.random_sample(time.size) - 0.5)  # Annual variability
+ np.linspace(0, 1.5, num=time.size)  # Random noise
),  # 1.5 degC increase in 60 years
dims=("time",),
coords={"time": time},
attrs={"units": "degC"},
name="temperature",
)
tas.plot()

[3]:

[<matplotlib.lines.Line2D at 0x7f0dc815d490>]


Then we compute the trend on the data. Here, we compute on the whole timeseries (group='time') with the parameters suggested above.

[4]:

from xclim.sdba.detrending import LoessDetrend

# Create the detrending object
det = LoessDetrend(group="time", d=0, niter=2, f=0.2)
# Fitting returns a new object and computes the trend.
fit = det.fit(tas)
# Get the detrended series
tas_det = fit.detrend(tas)

[5]:

fig, ax = plt.subplots()
fit.ds.trend.plot(ax=ax, label="Computed trend")
ax.plot(time, np.linspace(0, 1.5, num=time.size), label="Expected tred")
ax.plot([time[0], time[int(0.1 * time.size)]], [0.4, 0.4], linewidth=6, color="gray")
ax.plot([time[-int(0.1 * time.size)], time[-1]], [1.1, 1.1], linewidth=6, color="gray")
ax.legend()

[5]:

<matplotlib.legend.Legend at 0x7f0dcda4ac90>


As said earlier, this example shows how the Loess has strong boundary effects. It is recommended to remove the $$\frac{f}{2}\cdot N$$ outermost points on each side, as shown by the gray bars in the graph above.

## Initializing an Adjustment object from a training dataset

For large scale uses, when the training step deserves its own computation and write to disk, or simply when there are multiples sim to be adjusted with the same training, it is helpful to be able to instantiate the Adjustment objects from the training dataset itself. This trick relies on a global attribute “adj_params” set on the training dataset.

[6]:

import numpy as np
import xarray as xr

# Create toy data for the example, here fake temperature timeseries
t = xr.cftime_range("2000-01-01", "2030-12-31", freq="D", calendar="noleap")
ref = xr.DataArray(
(
-20 * np.cos(2 * np.pi * t.dayofyear / 365)
+ 2 * np.random.random_sample((t.size,))
+ 273.15
+ 0.1 * (t - t[0]).days / 365
),  # "warming" of 1K per decade,
dims=("time",),
coords={"time": t},
attrs={"units": "K"},
)
sim = xr.DataArray(
(
-18 * np.cos(2 * np.pi * t.dayofyear / 365)
+ 2 * np.random.random_sample((t.size,))
+ 273.15
+ 0.11 * (t - t[0]).days / 365
),  # "warming" of 1.1K per decade
dims=("time",),
coords={"time": t},
attrs={"units": "K"},
)

ref = ref.sel(time=slice(None, "2015-01-01"))
hist = sim.sel(time=slice(None, "2015-01-01"))

[7]:

from xclim.sdba.adjustment import QuantileDeltaMapping

QDM = QuantileDeltaMapping.train(
ref, hist, nquantiles=15, kind="+", group="time.dayofyear"
)
QDM

[7]:

QuantileDeltaMapping(group=Grouper(add_dims=[], name='time.dayofyear', window=1), kind='+')


The trained QDM exposes the training data in the ds attribute, Here, we will write it to disk, read it back and initialize an new object from it. Notice the adj_params in the dataset, that has the same value as the repr string printed just above. Also, notice the _xclim_adjustment attribute that contains a json string so we can rebuild the adjustment object later.

[8]:

QDM.ds

[8]:

<xarray.Dataset>
Dimensions:    (quantiles: 17, dayofyear: 365)
Coordinates:
* quantiles  (quantiles) float64 1e-06 0.03333 0.1 0.1667 ... 0.9 0.9667 1.0
* dayofyear  (dayofyear) int64 1 2 3 4 5 6 7 8 ... 359 360 361 362 363 364 365
Data variables:
af         (dayofyear, quantiles) float64 -2.029 -1.981 ... -2.262 -2.081
hist_q     (dayofyear, quantiles) float64 255.5 255.6 255.9 ... 257.8 257.8
Attributes:
group:               time.dayofyear
group_compute_dims:  ['time']
group_window:        1
adj_params:          QuantileDeltaMapping(group=Grouper(add_dims=[], name...
[9]:

QDM.ds.to_netcdf("QDM_training.nc")
ds = xr.open_dataset("QDM_training.nc")
QDM2 = QuantileDeltaMapping.from_dataset(ds)
QDM2

[9]:

QuantileDeltaMapping(group=Grouper(add_dims=[], name='time.dayofyear', window=1), kind='+')


In the case above, creating a full object from the dataset doesn’t make the most sense since we are in the same python session, with the “old” object still available. This method effective when we reload the training data in a different python session, say on another computer. However, take note that there is no retrocompatiblity insurance. If the QuantileDeltaMapping class was to change in a new xclim version, one would not be able to create the new object from a dataset saved with the old one.

For the case where we stay in the same python session, it is still useful to trigger the dask computations. For small datasets, that could mean a simple QDM.ds.load(), but sometimes even the training data is too large to be full loaded in memory. In that case, we could also do:

[10]:

QDM.ds.to_netcdf("QDM_training2.nc")
ds = xr.open_dataset("QDM_training2.nc")
ds.attrs["title"] = "This is the dataset, but read from disk."
QDM.set_dataset(ds)
QDM.ds

[10]:

<xarray.Dataset>
Dimensions:    (quantiles: 17, dayofyear: 365)
Coordinates:
* quantiles  (quantiles) float64 1e-06 0.03333 0.1 0.1667 ... 0.9 0.9667 1.0
* dayofyear  (dayofyear) int64 1 2 3 4 5 6 7 8 ... 359 360 361 362 363 364 365
Data variables:
af         (dayofyear, quantiles) float64 -2.029 -1.981 ... -2.262 -2.081
hist_q     (dayofyear, quantiles) float64 255.5 255.6 255.9 ... 257.8 257.8
Attributes:
group:               time.dayofyear
group_compute_dims:  time
group_window:        1
title:               This is the dataset, but read from disk.
[11]:

QDM2.adjust(sim)

[11]:

<xarray.DataArray 'scen' (time: 11315)>
array([254.15481624, 254.54558997, 253.80793402, ..., 258.46364433,
257.80385424, 256.6991244 ])
Coordinates:
* time     (time) object 2000-01-01 00:00:00 ... 2030-12-31 00:00:00
Attributes:
units:            K
history:          [2022-01-07 21:42:22] : Bias-adjusted with QuantileDelt...
bias_adjustment:  QuantileDeltaMapping(group=Grouper(add_dims=[], name='t...

## Retrieving extra output diagnostics

To fully understand what is happening during the bias-adjustment process, sdba can output diagnostic variables, giving more visibility to what the adjustment is doing behind the scene. This behaviour, a verbose option, is controlled by the sdba_extra_output option, set with xclim.set_options. When True, train calls are instructed to include additional variables to the training datasets. In addition, the adjust calls will always output a dataset, with scen and, depending on the algorithm, other diagnostics variables. See the documentation of each Adjustment objects to see what extra variables are available.

For the moment, this feature is still in construction and only a few Adjustment actually provide extra outputs. Please open issues on the Github repo if you have needs or ideas of interesting diagnostic variables.

For example, QDM.adjust adds sim_q, which gives the quantile of each element of sim within its group.

[12]:

from xclim import set_options

with set_options(sdba_extra_output=True):
QDM = QuantileDeltaMapping.train(
ref, hist, nquantiles=15, kind="+", group="time.dayofyear"
)

out.sim_q

[12]:

<xarray.DataArray 'sim_q' (time: 11315)>
array([0.12903226, 0.16129032, 0.03225806, ..., 1.        , 1.        ,
0.87096774])
Coordinates:
* time     (time) object 2000-01-01 00:00:00 ... 2030-12-31 00:00:00
Attributes:
group:               time.dayofyear
group_compute_dims:  time
group_window:        1
long_name:           Group-wise quantiles of sim.

Some Adjustment methods require that the adjusted data (sim) be of the same length (same number of points) than the training data (ref and hist). This requirements often ensure conservation of statistical properties and a better representation of the climate change signal over the long adjusted timeseries.

In opposition to a conventionnal “rolling window”, here it is the years that are the base units of the window, not the elements themselves. xclim implements sdba.construct_moving_yearly_window and sdba.unpack_moving_yearly_window to manipulate data in that goal. The “construct” function cuts the data in overlapping windows of a certain length (in years) and stacks them along a new "movingdim" dimension, alike to xarray’s da.rolling(time=win).construct('movingdim'), but with yearly steps. The step between each window can also be controlled. This argument is an indicator of how many years overlap between each window. With a value of 1 (the default), a window will have window - 1 years overlapping with the previous one. step = window will result in no overlap at all.

By default, the result is chunked along this 'movingdim' dimension. For this reason, the method is expected to be more computationally efficient (when using dask) than looping over the windows.

Note that this results in two restrictions:

1. The constructed array has the same “time” axis for all windows. This is a problem if the actual year is of importance for the adjustment, but this is not the case for any of xclim’s current adjustment methods.

2. The input timeseries must be in a calendar with uniform year lengths. For daily data, this means only the “360_day”, “noleap” and “all_leap” calendars are supported.

The “unpack” function does the opposite : it concatenates the windows together to recreate the original timeseries. Only the central step years are kept from each window. Which means the final timeseries has (window - step) / 2 years missing on either side, with the extra year missing on the right in case of an odd (window - step).

Here, asref and hist cover 15 years, we will use a window of 15 on sim. With a step of 2, this means the first window goes from 2000 to 2014 (inclusive). The last window goes from 2016 to 2030. window - step = 13, so 6 years will be missing at the beginning of the final scen and 7 years at the end.

[13]:

QDM = QuantileDeltaMapping.train(
ref, hist, nquantiles=15, kind="+", group="time.dayofyear"
)


[14]:

sim

[14]:

<xarray.DataArray (time: 11315)>
array([256.168473, 256.206541, 255.902366, ..., 260.480787, 260.471372,
259.23288 ])
Coordinates:
* time     (time) object 2000-01-01 00:00:00 ... 2030-12-31 00:00:00
Attributes:
units:    K
[15]:

from xclim.sdba import construct_moving_yearly_window, unpack_moving_yearly_window

sim_win = construct_moving_yearly_window(sim, window=15, step=2)
sim_win

[15]:

<xarray.DataArray (movingwin: 9, time: 5475)>
array([[256.16847268, 256.20654077, 255.90236634, ..., 258.29290004,
258.65450373, 257.66416028],
[255.53044669, 256.07620369, 257.34988762, ..., 258.26625731,
257.89390212, 258.81099668],
[255.74665584, 256.32683033, 256.98827206, ..., 259.09482439,
258.52940888, 258.44233677],
...,
[257.20961828, 257.193029  , 257.78413598, ..., 259.57728151,
258.63750564, 258.85629694],
[257.5221675 , 258.40170712, 257.71982238, ..., 259.77604668,
259.46143203, 259.3501499 ],
[257.44899856, 258.59666562, 257.27141864, ..., 260.48078683,
260.47137247, 259.23288036]])
Coordinates:
* movingwin  (movingwin) object 2000-01-01 00:00:00 ... 2016-01-01 00:00:00
* time       (time) object 2000-01-01 00:00:00 ... 2014-12-31 00:00:00
Attributes:
units:    K
[16]:

scen_win = unpack_moving_yearly_window(QDM.adjust(sim_win))
scen_win

[16]:

<xarray.DataArray 'scen' (time: 6570)>
array([254.64180509, 254.21656066, 255.34942617, ..., 256.36945987,
256.08841231, 257.6430471 ])
Coordinates:
* time     (time) object 2006-01-01 00:00:00 ... 2023-12-31 00:00:00
Attributes:
units:            K
history:          [2022-01-07 21:42:26] : Bias-adjusted with QuantileDelt...
bias_adjustment:  QuantileDeltaMapping(group=Grouper(add_dims=[], name='t...

Here is another short example, with an uneven number of years. Here sim goes from 2000 to 2029 (30 years instead of 31). With a step of 2 and a window of 15, the first window goes again from 2000 to 2014, but the last one is now from 2014 to 2028. The next window would be 2016-2030, but that last year doesn’t exist. The final timeseries is thus from 2006 to 2021, 6 years missing at the beginning, like last time and 8 years missing at the end.

[17]:

sim_win = construct_moving_yearly_window(
sim.sel(time=slice("2000", "2029")), window=15, step=2
)
sim_win

[17]:

<xarray.DataArray (movingwin: 8, time: 5475)>
array([[256.16847268, 256.20654077, 255.90236634, ..., 258.29290004,
258.65450373, 257.66416028],
[255.53044669, 256.07620369, 257.34988762, ..., 258.26625731,
257.89390212, 258.81099668],
[255.74665584, 256.32683033, 256.98827206, ..., 259.09482439,
258.52940888, 258.44233677],
...,
[257.55439008, 257.61090875, 257.72812383, ..., 257.91586535,
258.57233142, 258.11803746],
[257.20961828, 257.193029  , 257.78413598, ..., 259.57728151,
258.63750564, 258.85629694],
[257.5221675 , 258.40170712, 257.71982238, ..., 259.77604668,
259.46143203, 259.3501499 ]])
Coordinates:
* movingwin  (movingwin) object 2000-01-01 00:00:00 ... 2014-01-01 00:00:00
* time       (time) object 2000-01-01 00:00:00 ... 2014-12-31 00:00:00
Attributes:
units:    K
[18]:

sim2 = unpack_moving_yearly_window(sim_win)
sim2

[18]:

<xarray.DataArray (time: 5840)>
array([256.89339251, 255.95544277, 257.41346138, ..., 258.88742954,
259.23279934, 259.21959306])
Coordinates:
* time     (time) object 2006-01-01 00:00:00 ... 2021-12-31 00:00:00
Attributes:
units:    K